package com.hzya.frame.dingtalk.util;

import cn.hutool.core.util.StrUtil;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.tea.TeaException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.time.Instant;

/**
 * @Description 钉钉获取accessToken
 * @Author xiangerlin
 * @Date 2024/8/27 14:05
 **/
public class DingTalkAccessToken {
    static Logger logger = LoggerFactory.getLogger(DingTalkAccessToken.class);
    //token
    private static String accessToken;
    //过期时间
    private static Instant expireTime;
    private static final Long CACHE_EXPIRY_TIME = 7000L; // 缓存有效时间（秒）
    //应用key
    private static String appKey;
    //应用密钥
    private static String appSecret;
    @Value("${dingtalk.appKey:}")
    public static void setAppKey(String appKey) {
        DingTalkAccessToken.appKey = appKey;
    }
    @Value("${dingtalk.appSecret:}")
    public static void setAppSecret(String appSecret) {
        DingTalkAccessToken.appSecret = appSecret;
    }

    /**
     * 获取token
     * @return
     */
    public static String getAccessToken(){
        return getAccessToken(appKey,appSecret);
    }
    /**
     * 获取accessToken
     *
     * @param appKey
     * @param appSecret
     * @return
     */
    public static String getAccessToken(String appKey,String appSecret) {
        //判断是否过期 如果没过期直接返回
        if (null != accessToken && expireTime != null && Instant.now().isBefore(expireTime)) {
            return accessToken;
        }
        //获取新的accessToken
        accessToken = fetchNewAccessToken(appKey,appSecret);
        //过期时间设置成当前事件+7000s，预留200s的时间
        expireTime = Instant.now().plusSeconds(CACHE_EXPIRY_TIME);
        return accessToken;
    }

    /**
     * 获取新的accessToken
     *
     * @return
     */
    private static String fetchNewAccessToken(String appKey,String appSecret) {
        try {
            //查询应用上配置的钉钉信息
            if (StrUtil.isNotEmpty(appKey) && StrUtil.isNotEmpty(appSecret)) {
                //查询应用上的信息
                com.aliyun.dingtalkoauth2_1_0.Client client = DingTalkAccessToken.createClient();
                com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest getAccessTokenRequest = new com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest()
                        .setAppKey(appKey)
                        .setAppSecret(appSecret);
                GetAccessTokenResponse accessToken = client.getAccessToken(getAccessTokenRequest);
                String accessToken1 = accessToken.getBody().getAccessToken();
                return accessToken1;
            }
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }
            logger.error("获取钉钉token出错:{}", _err);
        }
        return null;
    }

    /**
     * 使用 Token 初始化账号Client
     *
     * @return Client
     * @throws Exception
     */
    private static com.aliyun.dingtalkoauth2_1_0.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkoauth2_1_0.Client(config);
    }
}
