package com.hfkj.config;


import com.alibaba.fastjson.JSONObject;

import com.hfkj.common.utils.HttpsUtils;
import com.hfkj.common.utils.RedisUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

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


/**
 * @serviceName WeChatQrcodeUtils.java
 * @author Sum1Dream
 * @version 1.0.0
 * @Description // 生成带参数的二维码
 * @createTime 16:11 2022/9/2
 **/
@Component
public class WeChatQrcodeUtils {

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


    @Resource
    private RedisUtil redisUtil;


    // 获取微信Token存入redis
    public String getWxToken(Boolean whetherRedis) {

        if (!whetherRedis) {
            Object token = redisUtil.get("WxToken");
            if (null != token) {
                return token.toString();
            }
        }

        log.info("获取最新微信token");

        // 获取access_token
        JSONObject params = new JSONObject();
        params.put("appid", CommonSysConst.getSysConfig().getWechatMpAppid());
        params.put("secret", CommonSysConst.getSysConfig().getWechatMpSecret());
        params.put("grant_type", "client_credential");
        JSONObject accessTokenObject = HttpsUtils.doPost("https://api.weixin.qq.com/cgi-bin/stable_token", params);
        redisUtil.set("WxToken", accessTokenObject.getString("access_token"), 7000);
        return accessTokenObject.getString("access_token");
    }


    // 获取签名
    public JSONObject getTicket(Boolean whetherRedis) {

        int WxTokenRequestNum = Integer.parseInt(redisUtil.get("WxTokenRequestNum") == null ? "1" : redisUtil.get("WxTokenRequestNum").toString());

        redisUtil.set("WxTokenRequestNum", WxTokenRequestNum + 1, 1000);

        String token = getWxToken(whetherRedis);
        ;

        log.info("获取微信token次数: " + WxTokenRequestNum);
        log.info("获取微信token-回调参数: " + token);

        JSONObject jsapiTicket;

        // 获取ticket
        Map<String, Object> ticketParams = new HashMap<>();
        ticketParams.put("access_token", token);
        ticketParams.put("type", "jsapi");
        jsapiTicket = HttpsUtils.doGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket", ticketParams);

        log.info("获取ticket-回调参数: " + jsapiTicket);

        if (jsapiTicket != null && jsapiTicket.getInteger("errcode") != 0 && WxTokenRequestNum < 6) {
            jsapiTicket = getTicket(true);
        }

        redisUtil.del("WxTokenRequestNum");
        return jsapiTicket;

    }
}
