package com.trade.service.contract.util.esign;

import com.alibaba.fastjson2.JSONObject;
import com.trade.common.redis.RedisCache;
import com.trade.common.utils.SpringUtils;

import java.text.MessageFormat;
import java.util.concurrent.TimeUnit;

/**
 * e签宝获取token
 */
public class ESignTokenHelper {

    private static RedisCache redisCache;

    /**
     * 获取token 实际使用中，可获取token后，放在redis缓存中，如果是非分布式架构，也可使用guava的LoadingCache或者自己构建本地缓存来存储该token，
     * 缓存存储时，需要注意缓存失效截止时间expiresIn
     */
    public static void getTokenData() {
        JSONObject result = ESignTools.doCommHttp(RequestType.GET,
                ESignConfig.getToken_URL(ESignConfig.PROJECT_ID_V2, ESignConfig.PROJECT_SECRET_V2), null);
        result = ESignJSONHelper.castDataJson(result, JSONObject.class);
        getRedisCache().setCacheObject(ESignConstant.TOKEN, result.getString("token"), 60 * 60, TimeUnit.SECONDS);
        getRedisCache().setCacheObject(ESignConstant.REFRESH_TOKEN, result.getString("refreshToken"), 60 * 60,
                TimeUnit.SECONDS);
    }

    /**
     * 刷新token 刷新token后，新旧token共存时间为5分钟，实际使用中，若使用redis或者guava的LoadingCache或自建本地缓存的方式来存储token，请注意刷新缓存时间
     * 
     * @param refreshToken {@link String} 之前获取token时返回的refreshToken
     */
    public static JSONObject refreshToken(String refreshToken) {
        JSONObject result = ESignTools.doCommHttp(RequestType.GET,
                ESignConfig.refreshToken_URL(ESignConfig.PROJECT_ID_V2, refreshToken), null);
        result = ESignJSONHelper.castDataJson(result, JSONObject.class);
        int errCode = result.getIntValue("code");
        if (0 != errCode) {
            throw new RuntimeException(
                    MessageFormat.format("刷新token失败,失败信息：errCode = {0}, msg = {1}", errCode, result.get("msg")));
        } else {
            getRedisCache().setCacheObject(ESignConstant.TOKEN, result.getString("token"));
            getRedisCache().setCacheObject(ESignConstant.REFRESH_TOKEN, result.getString("refreshToken"));
        }
        return result;
    }

    private static RedisCache getRedisCache() {
        if (redisCache == null) {
            redisCache = SpringUtils.getBean(RedisCache.class);
        }
        return redisCache;
    }
}
