package com.cxyxiaomo.epp.access.controller;

import com.alibaba.fastjson2.JSONObject;
import com.cxyxiaomo.epp.access.pojo.UnlimitedQRCodeParam;
import com.cxyxiaomo.epp.access.service.WeChatTokenServiceImpl;
import com.cxyxiaomo.epp.common.response.Res;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Objects;

@Controller
@RequestMapping("/access/wechat")
public class WeChatTokenController {

    @Autowired
    private WeChatTokenServiceImpl weChatTokenService;

    @GetMapping("/getAccessToken")
    @ResponseBody
    public Res getAccessToken() {
        String accessToken = weChatTokenService.getAccessToken();
        return Res.success(accessToken);
    }

    @GetMapping(value = "/getUnlimitedQRCode", produces = MediaType.IMAGE_PNG_VALUE)
    @ResponseBody
    @SneakyThrows
    public byte[] getUnlimitedQRCode(@RequestParam(value = "envVersion", required = false, defaultValue = "develop") String envVersion,
                                     @RequestParam(value = "page", required = false, defaultValue = "pages/index/index") String page,
                                     @RequestParam(value = "width", required = false, defaultValue = "430") Integer width,
                                     @RequestParam(value = "autoColor", required = false, defaultValue = "false") Boolean autoColor,
                                     @RequestParam(value = "isHyaline", required = false, defaultValue = "false") Boolean isHyaline,
                                     @RequestParam(value = "scene", required = true) String scene) {
        String accessToken = weChatTokenService.getAccessToken();
        UnlimitedQRCodeParam unlimitedQRCodeParam = new UnlimitedQRCodeParam();
        unlimitedQRCodeParam.setScene(scene);
        unlimitedQRCodeParam.setPage(page);
        unlimitedQRCodeParam.setEnvVersion(envVersion);
        unlimitedQRCodeParam.setWidth(width);
        unlimitedQRCodeParam.setAutoColor(autoColor);
        unlimitedQRCodeParam.setIsHyaline(isHyaline);
        okhttp3.ResponseBody responseBody = weChatTokenService.getUnlimitedQRCodeFromApi(accessToken, unlimitedQRCodeParam);

        try {
            // {"errcode":40001,"errmsg":"invalid credential, access_token is invalid or not latest, could get access_token by getStableAccessToken, more details at https://mmbizurl.cn/s/JtxxFh33r rid: 6446bac4-4a6b0410-118a16e7"}
            if (Objects.requireNonNull(responseBody.contentType()).subtype().equals("json")) {
                // 返回了 JSON 说明失败了
                String jsonString = responseBody.string();
                JSONObject jsonObject = JSONObject.parseObject(jsonString);
                String errcode = jsonObject.getString("errcode");
                if (errcode.equals("40001")) {
                    // 重新获取 Access Token
                    accessToken = weChatTokenService.getAccessToken(true);
                    responseBody = weChatTokenService.getUnlimitedQRCodeFromApi(accessToken, unlimitedQRCodeParam);
                } else if (errcode.equals("40013")) {
                    System.out.println("40013 invalid appid 不合法的 AppID ，请开发者检查 AppID 的正确性，避免异常字符，注意大小写\n" +
                            "docs: https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getAccessToken.html");
                    return null;
                }
            }
            // 返回了图片，直接返回
            return responseBody.bytes();
        } catch (NullPointerException ignored) {
            return null;
        }
    }

    @GetMapping(value = "/rpc/getOpenIdFromApi")
    @ResponseBody
    @SneakyThrows
    public Res getOpenIdFromApi(@RequestParam(value = "code", required = true) String code) {
        if (Objects.isNull(code) || "".equals(code)) {
            return Res.error("参数错误");
        }
        String openId = weChatTokenService.getOpenIdFromApi(code);
        if (openId == null) {
            return Res.error("微信OpenId接口调用失败，请刷新重试");
        }
        return Res.success(openId);
    }
}
