package org.xyzh.common.wechat.kefu.core;

import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.xyzh.api.system.service.SysConfigService;
import org.xyzh.common.core.domain.ResultDomain;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import jakarta.annotation.PostConstruct;

/**
 * @description    微信客服 AccessToken 管理器
 *                 负责获取和刷新 access_token
 * @filename    KefuAccessTokenManager.java
 * @author    yslg
 * @copyright xyzh
 * @since 2025-12-19
 */
@Component
public class KefuAccessTokenManager {

    private static final Logger logger = LoggerFactory.getLogger(KefuAccessTokenManager.class);
    private static final String BASE_URL = "https://qyapi.weixin.qq.com/cgi-bin";

    private final RestTemplate restTemplate = new RestTemplate();

    @DubboReference(version = "1.0.0", group = "system", check = false, retries = 0)
    private SysConfigService sysConfigService;

    private String corpId;
    private String secret;
    private String accessToken;
    private Long accessTokenExpireTime;

    @PostConstruct
    public void init() {
        loadConfig();
    }

    public void loadConfig() {
        corpId = getConfigValue("wechat.kefu.corpId");
        secret = getConfigValue("wechat.kefu.secret");
        logger.info("微信客服配置加载完成: corpId={}", corpId);
    }

    private String getConfigValue(String key) {
        if (sysConfigService == null) {
            logger.warn("SysConfigService 未注入，跳过配置加载: {}", key);
            return null;
        }
        ResultDomain<String> result = sysConfigService.getConfigValueByKey(key);
        if (result != null && result.getSuccess()) {
            return result.getData();
        }
        return null;
    }

    /**
     * 获取 access_token，如果过期自动刷新
     */
    public String getAccessToken() {
        if (accessToken != null && accessTokenExpireTime != null 
            && System.currentTimeMillis() < accessTokenExpireTime) {
            return accessToken;
        }
        return refreshAccessToken();
    }

    /**
     * 刷新 access_token
     */
    public String refreshAccessToken() {
        if (corpId == null || secret == null) {
            logger.error("微信配置不完整，无法获取access_token");
            return null;
        }

        String url = BASE_URL + "/gettoken?corpid=" + corpId + "&corpsecret=" + secret;

        try {
            String response = restTemplate.getForObject(url, String.class);
            JSONObject result = JSON.parseObject(response);

            if (result.getIntValue("errcode") == 0) {
                accessToken = result.getString("access_token");
                int expiresIn = result.getIntValue("expires_in");
                accessTokenExpireTime = System.currentTimeMillis() + (expiresIn - 200) * 1000L;
                logger.info("获取access_token成功，有效期: {}秒", expiresIn);
                return accessToken;
            } else {
                logger.error("获取access_token失败: {}", response);
                return null;
            }
        } catch (Exception e) {
            logger.error("获取access_token异常", e);
            return null;
        }
    }

    public String getCorpId() {
        return corpId;
    }

}
