package vip.xiaonuo.biz.modular.api.controller;

import cn.hutool.core.util.ObjectUtil;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.asn1.ocsp.ResponseData;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.biz.modular.api.param.WeiXinRes;
import vip.xiaonuo.biz.modular.api.param.WxUserParam;
import vip.xiaonuo.biz.modular.api.service.ApiService;
import vip.xiaonuo.biz.modular.user.entity.BizUser;
import vip.xiaonuo.biz.modular.user.service.BizUserService;
import vip.xiaonuo.biz.modular.utils.SignUtil;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.pojo.CommonResult;
import vip.xiaonuo.common.prop.CommonProperties;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Tag(name = "微信公众号")
@RestController
@Validated
@Slf4j
public class ApiController {

    @Resource
    private CommonProperties commonProperties;

    @Resource
    private ApiService apiService;

    @Resource
    private BizUserService bizUserService;

    /***
     * 微信公众号验证接口
     * @param request
     * @param response
     */
    @GetMapping("/follow/wxOpen")
    public void get(HttpServletRequest request, HttpServletResponse response) {
        // 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，否则接入失败
            if (SignUtil.checkSignature(commonProperties.getOfficialToken(), signature, timestamp, nonce)) {
                out.print(echostr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }


    /**
     * 微信公众号操作事件(包括关注和取消动作操作)
     *
     * @param request
     * @param response
     */
    @PostMapping("/follow/wxOpen")
    public void officialCallback(HttpServletRequest request, HttpServletResponse response) {
        apiService.officialCallback(request, response);
    }


    /**
     * 微信小程序 _绑定公众号操作
     *
     * @param
     * @return
     */
    @ResponseBody
    @PostMapping("/wx/bindingWX")
    public CommonResult<String> bindingWX(@RequestBody WxUserParam wxUserParam) {
        log.info("==========用户ID:" + wxUserParam.getId() + "==========");
        log.info("==========微信js_Code:" + wxUserParam.getJs_code() + "==========");

        BizUser user = bizUserService.queryEntity(wxUserParam.getId());

        //Js_code 去交换 openId
        String js_code = wxUserParam.getJs_code();
        Map<String, Object> param = new HashMap<>(1);
        param.put("js_code", js_code);
        String res = apiService.weiXinSend(param);
        log.info("==========微信绑定接口返回:" + res + "==========");
        //解析微信返回内容
        WeiXinRes weiXinRes = new WeiXinRes().weixinResgistRes(res);
        if (!weiXinRes.getErrcode().equals(0)) {
            throw new CommonException(weiXinRes.getErrcode(), weiXinRes.getErrmsg());
        }
        log.info("==========微信绑定接口返回OpenId:" + weiXinRes.getOpenid() + "==========");
        log.info("==========微信绑定接口返回UnionId:" + weiXinRes.getUnionid() + "==========");
        user.setOpenId(weiXinRes.getOpenid());
        user.setUnionId(weiXinRes.getUnionid());
        bizUserService.updateById(user);
        return CommonResult.ok();
    }

}
