package com.cweb.controller;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson.JSONObject;
import com.cweb.config.SysConst;
import com.hfkj.common.utils.HttpsUtils;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.config.WxMaConfig;
import com.hfkj.model.ResponseData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/wechat")
@Api(value = "微信授权")
public class WechatController {

    private static final Logger log = LoggerFactory.getLogger(WechatController.class);

    @RequestMapping(value = "/getAccessToken", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "解析")
    public ResponseData getAccessToken(@RequestParam(value = "code", required = true) String code) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("appid", SysConst.getSysConfig().getWxAppId());
            params.put("secret", SysConst.getSysConfig().getWxAppSecret());
            params.put("code", code);
            params.put("grant_type", "authorization_code");
            return ResponseMsgUtil.success(HttpsUtils.doGet("https://api.weixin.qq.com/sns/oauth2/access_token", params));

        } catch (Exception e) {
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/wxMiniHandleCode", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "微信小程序code解析")
    public ResponseData wxMiniHandleCode(@RequestBody JSONObject body) {
        try {
            if (body == null|| StringUtils.isBlank(body.getString("code"))) {
                log.error("LoginController --> phone() error!", "请求参数校验失败");
            }
            WxMaJscode2SessionResult session = WxMaConfig.getMaService().jsCode2SessionInfo(body.getString("code"));

            //保存小程序用户登录的openId及sessionKey信息
            JSONObject jo = new JSONObject();
            jo.put("openId", session.getOpenid());
            return ResponseMsgUtil.success(jo);
        } catch (Exception e) {
            return ResponseMsgUtil.exception(e);
        }
    }
}
