package com.customization.yll.liuzhoucitycollege.api;

import com.customization.yll.common.util.CacheUtil;
import com.customization.yll.liuzhoucitycollege.config.JinzhiConfiguraton;
import com.customization.yll.liuzhoucitycollege.integration.CustomTokenStore;
import com.wisedu.casp.sdk.api.token.TokenGatewayAccessTokenRequest;
import com.wisedu.casp.sdk.api.token.TokenGatewayAccessTokenResponse;
import com.wisedu.casp.sdk.core.Client;
import com.wisedu.casp.sdk.core.DefaultClient;
import org.jetbrains.annotations.Nullable;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;

/**
 * @author yaolilin
 * @desc 金智token管理，可以将token缓存，如果有redis则会缓存到redis
 * @date 2024/12/2
 **/
public class JinzhiTokenManager {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    public static final String TOKEN_CACHE_KEY = "jinzhi:token";
    private static final int CACHE_EXPIRE_TWO_HOUR = 60 * 60 * 2;

    /**
     * 获取token，如果失败返回空。token 会进行缓存
     * @return token
     */
    public String getToken() {
        String token = getTokenFromCache();
        if (token != null) {
            return token;
        }
        return getNewToken();
    }

    /**
     * 从缓存获取token，如果缓存中没有token则返回null
     * @return token
     */
    @Nullable
    public String getTokenFromCache() {
        Object value = CacheUtil.getCache(TOKEN_CACHE_KEY);
        if (value == null) {
            return null;
        }
        return (String) value;
    }

    /**
     * 获取新的token,不从缓存获取
     * @return token
     */
    public String getNewToken() {
        String token = callApiGetToken();
        if (token.isEmpty()) {
            log.error("token 获取为空");
            return "";
        }
        setTokenToCache(token);
        return token;
    }

    public void setTokenToCache(String token) {
        CacheUtil.putCache(TOKEN_CACHE_KEY, token, CACHE_EXPIRE_TWO_HOUR);
    }

    /**
     * 获取自定义金智token存储 CustomTokenStore
     * @return CustomTokenStore 实例
     */
    public CustomTokenStore getTokenStore() {
        Client client = new DefaultClient(JinzhiConfiguraton.getBaseUrl(),
                JinzhiConfiguraton.getAppId(), JinzhiConfiguraton.getAppSecret());
        return new CustomTokenStore(client);
    }

    private String callApiGetToken() {
        // 创建客户端
        String appId = JinzhiConfiguraton.getAppId();
        String appSecret = JinzhiConfiguraton.getAppSecret();
        Client client = new DefaultClient(JinzhiConfiguraton.getBaseUrl(), appId, appSecret);
        // 创建请求对象
        TokenGatewayAccessTokenRequest request = new TokenGatewayAccessTokenRequest();
        request.setAppId(appId);
        request.setAppSecret(appSecret);
        try {
            TokenGatewayAccessTokenResponse response = client.execute(request);
            if (!response.isSuccess()) {
                log.error("获取token失败，"+response.getErrmsg()+",errcode:"+response.getErrcode());
                return "";
            }
            return response.getData();
        } catch (Exception e) {
            log.error("获取token失败，请求发生异常",e);
            return "";
        }
    }
}
