package vip.xiaonuo.biz.api.wxapp.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import vip.xiaonuo.biz.api.wxapp.param.AccessTokenParam;
import vip.xiaonuo.biz.core.Const.BizStr;
import vip.xiaonuo.common.cache.CommonCacheOperator;
import vip.xiaonuo.common.exception.CommonException;

import javax.annotation.Resource;

@Slf4j
@Service
public class AccessTokenService {

    @Resource
    private CommonCacheOperator commonCacheOperator;

    public  String getAccessToken(AccessTokenParam param) {
        // 因为微信有限制次数跟有效期，所以需要存在redis中
        String token = commonCacheOperator.get("access_token") + "";
        // token失效或者为空
        if (StrUtil.isEmpty(token) || "null".equals(token)) {
            StringBuffer url = new StringBuffer("https://api.weixin.qq.com/cgi-bin/token");
            url.append("?grant_type=client_credential");
            url.append("&appid=").append(BizStr.APPID);
            url.append("&secret=").append(BizStr.SECRET);
            log.info(url.toString());
            String content = HttpUtil.get(url.toString());
            if (StrUtil.isEmpty(content) || !content.contains("access_token")) {
                log.info(content);
                throw new CommonException(500, "获取公众号accessToken失败;" + content);
            }
            token = JSONObject.parseObject(content).getString("access_token");
            // 设置时长(有效期2h)
            commonCacheOperator.put("access_token", token, 7000);
            param.setTimeOut(7000);
        }
        param.setToken(token);
        return token;
    }

    //小程序token
    public  String getCreateWxaQrCodeToken() {
        // 因为微信有限制次数跟有效期，所以需要存在redis中
        String token = commonCacheOperator.get("createWxaQrCode_token") + "";
        // token失效或者为空
        if (StrUtil.isEmpty(token) || "null".equals(token)) {
            StringBuffer url = new StringBuffer("https://api.weixin.qq.com/cgi-bin/token");
            url.append("?grant_type=client_credential");
            url.append("&appid=").append("wx3f56405be38c31fd");
            url.append("&secret=").append("8e1c83bd68300a60f2768f0faab39ab1");
            log.info(url.toString());
            String content = HttpUtil.get(url.toString());
            if (StrUtil.isEmpty(content) || !content.contains("access_token")) {
                log.info(content);
                throw new CommonException(500, "获取公众号accessToken失败;" + content);
            }
            token = JSONObject.parseObject(content).getString("access_token");
            // 设置时长(有效期2h)
            commonCacheOperator.put("createWxaQrCode_token", token, 7000);
        }
        return token;
    }

}
