package org.xyzh.common.wechat.config;

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

import jakarta.annotation.PostConstruct;

/**
 * @description    微信初始化配置，从系统配置中加载微信客服参数
 * @filename    WeChatInit.java
 * @author    yslg
 * @copyright xyzh
 * @since 2025-12-19
 */
@Component
public class WeChatKefuInit {

    private static final Logger logger = LoggerFactory.getLogger(WeChatKefuInit.class);

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

    private static WeChatKefuConfig weChatConfig;

    @PostConstruct
    public void init() {
        logger.info("初始化微信客服配置...");
        weChatConfig = new WeChatKefuConfig();
        loadConfig();
    }

    public void loadConfig() {
        try {
            weChatConfig.setCorpId(getConfigValue("wechat.kefu.corpId"));
            weChatConfig.setSecret(getConfigValue("wechat.kefu.secret"));
            weChatConfig.setToken(getConfigValue("wechat.kefu.token"));
            weChatConfig.setEncodingAesKey(getConfigValue("wechat.kefu.encodingAesKey"));
            weChatConfig.setOpenKfid(getConfigValue("wechat.kefu.openKfid"));
            weChatConfig.setWelcomeTemplate(getConfigValue("wechat.kefu.welcomeTemplate"));
            logger.info("微信客服配置加载完成: corpId={}, openKfid={}", weChatConfig.getCorpId(), weChatConfig.getOpenKfid());
        } catch (Exception e) {
            logger.error("加载微信客服配置失败", e);
        }
    }

    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;
    }

    public static WeChatKefuConfig getConfig() {
        return weChatConfig;
    }

    public void refreshConfig() {
        loadConfig();
    }
}
