package com.ruoyi.common.utils.dy;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

@Slf4j
public class DouYinAccessTokenUtil {

    // 存储每个租户的token和过期时间
    private static final ConcurrentHashMap<String, String> cachedTokens = new ConcurrentHashMap<>();
    private static final ConcurrentHashMap<String, Long> tokenExpirationTimes = new ConcurrentHashMap<>();

    @SneakyThrows
    public static String getToken(String appId, String appsecret) {
        String cacheKey = appId+ ":" + appsecret;
        if (isTokenExpired(cacheKey)) {
            log.info("token已过期，重新获取");
            String uri = "https://open.douyin.com/oauth/client_token/";

            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("client_key", appId);
            paramMap.put("client_secret", appsecret);
            paramMap.put("grant_type", "client_credential");

            String result= HttpUtil.post(uri, paramMap);
            JSONObject jsonObject = JSON.parseObject(result);
            JSONObject data = jsonObject.getJSONObject("data");
            String accessToken = data.getString("access_token");
            // 更新缓存
            cachedTokens.put(cacheKey, accessToken);
            tokenExpirationTimes.put(cacheKey, System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(3600L));
            return accessToken;
        }
        log.info("token未过期，直接使用");
        return cachedTokens.get(cacheKey);
    }

    /**判断token是否过期*/
    private static boolean isTokenExpired(String cacheKey) {
        Long expirationTime = tokenExpirationTimes.get(cacheKey);
        return expirationTime == null || System.currentTimeMillis() > expirationTime;
    }
}
