package com.ruoyi.common.utils.wx;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

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

@Slf4j
public class AccessTokenUtil {

    // 存储每个租户的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已过期，重新获取");
            WxMaService wxMaService = new WxMaServiceImpl();
            WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
            config.setAppid(appid);
            config.setSecret(appsecret);
            wxMaService.setWxMaConfig(config);
            String accessToken = wxMaService.getAccessToken();

            // 更新缓存
            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;
    }
}
