package com.cyksj.config.corp;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.mapper.corp.WxCorpAppMapper;
import com.cyksj.model.entity.WxCorpApp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author chan
 * @date 2022/4/7 4:51 下午
 */
@Component
public class WeChatCorpFactory {

    @Autowired
    private WxCorpAppMapper corpAppMapper;

    private static Map<String, WxCorpApp> strategyBean = new ConcurrentHashMap<>();

    /**
     * 初始化
     *
     * @param corpId
     * @return
     */
    public static WxCorpApp getCorpConfigStrategy(String corpId) {
        if (StrUtil.isBlank(corpId)) {
            throw BusinessRuntimeException.getInstance("corpId is empty");
        }
        WxCorpApp corpApp = strategyBean.get(corpId);
        Objects.requireNonNull(corpApp, "corp config not exist");
        return corpApp;
    }

    @PostConstruct
    public void init() {
        List<WxCorpApp> wxCorpApps = corpAppMapper.selectList(Wrappers.lambdaQuery(WxCorpApp.class));
        wxCorpApps.forEach((corpApp)->{
            strategyBean.put(corpApp.getCorpId(), corpApp);
        });
    }

}
