package com.jeeplus.weChat.controller;

import com.jeeplus.weChat.util.SignUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author 王强
 * @version 1.0
 * @date 2024-07-15 16:45
 */
@RestController
@Slf4j
public class WeChatController {

    private final String TOKEN = "wxs1314520"; // 你设置的Token

    @GetMapping("/wechat")
    public void sendMsgTest(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 微信加密签名.
        String signature = request.getParameter("signature");
        System.out.println("微信加密签名-》  " + signature);
        // 时间戳.
        String timestamp = request.getParameter("timestamp");
        System.out.println("微信加密签名时间戳-》  " + timestamp);
        // 随机数.
        String nonce = request.getParameter("nonce");
        System.out.println("微信加密签名随机数-》  " + nonce);
        // 随机字符串.
        String echostr = request.getParameter("echostr");
        // 请求校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败.
        PrintWriter out = response.getWriter();

        // 请求校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败.
        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
            out.print(echostr);
        }

        out.close();
        out = null;
    }

    @Autowired
    private WxMpService wxMpService;

    @Value("${wechat.projecturl}")
    private String projectUrl;

    @GetMapping("/auth")
    @ResponseBody
    public String auth(@RequestParam(value = "echostr", defaultValue = "没有获取到") String echostr) {
        return echostr;
    }

    /**
     * @author ：tao
     * @param: ：
     * @return： 重定向到获取用户信息的类
     * 微信授权登录
     */
    @GetMapping( value = "/authorize")
    public String authorize(@RequestParam(value = "returnUrl", defaultValue = "http://kqe4km.natappfree.cc/") String returnUrl) throws UnsupportedEncodingException {
        log.info("【微信网页授权】进来了，参数={}", returnUrl);
        System.out.println("进来了:" + returnUrl);
        //1. 配置
        //2. 调用方法
        String url = projectUrl + "api/userInfo";
        /*
         * 相当于这种形式
         * URLEncoder.decode(returnUrl,"UTF-8"
         * https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
         */
        String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAUTH2_SCOPE_USER_INFO, URLEncoder.encode(returnUrl, "utf-8"));
        log.info("【微信网页授权】获取code,result={}", redirectUrl);
        return "redirect:" + redirectUrl;

    }

    /**
     * @author ：tao
     * @param: ：
     * @return： 重定向
     * 获取用户信息类，最后重定向到指定url
     */
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code,
                           @RequestParam("state") String returnUrl) throws WxErrorException {
        /*当用户同意授权后，会回调所设置的url并把authorization code传过来，
        然后用这个code获得access token，其中也包含用户的openid等信息*/
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
        try {
            //获取access token
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            log.info("【AccessToken：】{}", wxMpOAuth2AccessToken.getAccessToken());
        } catch (WxErrorException e) {
            log.error("【微信网页授权】{}", e);
        }

        // 拿到openid
        String openId = wxMpOAuth2AccessToken.getOpenId();
        log.info("【openid：】{}", openId);
        log.info("【我是前端要回调的地址：】{}", returnUrl + "&openid=" + openId);
        // 顺便获取一下用户信息
        WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, "zh_CN");
        log.info("【用户信息：】{}", wxMpUser.toString());

        //注意拼接参数，第一个参数需要加问号，之后参数使用&拼接的问题
        //return "redirect:" + returnUrl + "/#/?openid=" + openId;
//        return "redirect:" + returnUrl;
        return wxMpUser.getOpenId();
    }
}

