package cn.axzo.msg.center.wx.notices.compont;

import cn.axzo.msg.center.common.consts.ConstPool;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.redis.RedissonWxRedisOps;
import me.chanjar.weixin.cp.config.impl.WxCpTpRedissonConfigImpl;
import me.chanjar.weixin.cp.tp.service.impl.BaseWxCpTpServiceImpl;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author cn
 * @version 1.0
 * @description
 * @date 2023/5/31 17:16
 */
@Component
@RequiredArgsConstructor
public class WxCpTpProcessorFactory implements InitializingBean {
    private final RedissonClient redissonClient;

    private static final Map<String, BaseWxCpTpServiceImpl<?, ?>> CORP_SUITE_PROCESSOR_MAP = new HashMap<>();
    private static final Map<String, WxCpTpRedissonConfigImpl> CORP_CONFIG_MAP = new HashMap<>();


    private String buildConfigKey(String corpId, String suiteId) {
        return corpId + ConstPool.REDIS_KEY_SPLIT + suiteId;
    }

    private WxCpTpRedissonConfigImpl buildConfig(String corpId, String providerSecret, String suiteId, String suiteSecret,
                                                 String token,
                                                 String aesKey) {
        return WxCpTpRedissonConfigImpl.builder().
                wxRedisOps(new RedissonWxRedisOps(redissonClient)).
                providerSecret(providerSecret).
                suiteId(suiteId).
                token(token).
                aesKey(aesKey).
                suiteSecret(suiteSecret).
                corpId(corpId).
                build();
    }

    public BaseWxCpTpServiceImpl<?, ?> getServiceImpl(String corpId, String suiteId) {
        return CORP_SUITE_PROCESSOR_MAP.get(buildConfigKey(corpId, suiteId));
    }

    public WxCpTpRedissonConfigImpl getConfig(String corpId) {
        return CORP_CONFIG_MAP.get(corpId);
    }

    private void initProcessors() {
        WxCpTpProcessor wxCpTpProcessor = new WxCpTpProcessor();
        WxCpTpRedissonConfigImpl wxCpTpRedissonConfig = buildConfig("ww140cb46df62ffbe2", "uG3u51Fl4PZ9CLdwYA2Bpwsd3vBzsquVuEEkbueiRwpGhPx4IzTZ9vuaL4FdQN5B",
                "", "", "cjMayOvnGYHtG", "AaB8P33GN33VLNJLHOFIXShrF7vWVWRc6UlMeAzzLoG");
        wxCpTpProcessor.setWxCpTpConfigStorage(wxCpTpRedissonConfig);
        CORP_CONFIG_MAP.put(wxCpTpRedissonConfig.getCorpId(), wxCpTpRedissonConfig);
        CORP_SUITE_PROCESSOR_MAP.put(buildConfigKey(wxCpTpRedissonConfig.getCorpId(), wxCpTpRedissonConfig.getSuiteId()), wxCpTpProcessor);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        initProcessors();
    }
}
