package com.kiisoo.ic.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Maps;
import com.kiisoo.ic.base.entity.BasicConfigDO;
import com.kiisoo.ic.base.mapper.BasicConfigDOMapper;
import lombok.val;
import me.chanjar.weixin.common.util.http.apache.DefaultApacheHttpClientBuilder;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.api.impl.WxCpServiceOkHttpImpl;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import me.chanjar.weixin.cp.message.WxCpMessageRouter;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Configuration
@EnableConfigurationProperties(WxCpProperties.class)
@Service
public class WxCpConfiguration {

    private static Map<Integer, WxCpServiceOkHttpImpl> cpServices = Maps.newHashMap();

    public static Integer APPLICATIONID = 100004;

    @Autowired
    private BasicConfigDOMapper basicConfigDOMapper;

    public static WxCpServiceOkHttpImpl getCpService(Integer agentId) {
        return cpServices.get(agentId);
    }

    @PostConstruct
    public void initServices() {
        QueryWrapper<BasicConfigDO> baseParams = new QueryWrapper<>();
        baseParams.eq("code","CP_CORPID");
        BasicConfigDO basicConfigDO = basicConfigDOMapper.selectOne(baseParams);

        QueryWrapper<BasicConfigDO> confParams = new QueryWrapper<>();
        confParams.likeRight("code","CP_");
        confParams.ne("code","CP_CORPID");
        List<BasicConfigDO> confConfigDO = basicConfigDOMapper.selectList(confParams);
        Map<String,Map<String,String>> confMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(confConfigDO)){
            confConfigDO.forEach(conf -> {
                Map<String, String> oneConf = confMap.get(conf.getCode());
                if (oneConf == null){
                    oneConf = new HashMap<>();
                    oneConf.put(conf.getConfKey(),conf.getConfValue());
                    confMap.put(conf.getCode(),oneConf);
                }else{
                    oneConf.put(conf.getConfKey(),conf.getConfValue());
                }
            });
        }


        cpServices = confMap.keySet().stream().map(a -> {
            val configStorage = new WxCpDefaultConfigImpl();
            configStorage.setCorpId(basicConfigDO.getConfValue());
            configStorage.setAgentId(Integer.valueOf(confMap.get(a).get("agentId")));
            configStorage.setCorpSecret(confMap.get(a).get("secret"));
            configStorage.setToken(confMap.get(a).get("token"));
            configStorage.setAesKey(confMap.get(a).get("aesKey"));
            val service = new WxCpServiceOkHttpImpl();
            service.setWxCpConfigStorage(configStorage);

            DefaultApacheHttpClientBuilder clientBuilder = DefaultApacheHttpClientBuilder.get();
            clientBuilder.setConnectionRequestTimeout(6000);//从连接池获取链接的超时时间(单位ms)
            clientBuilder.setSoTimeout(5000);//连接池socket超时时间(单位ms)
            clientBuilder.setIdleConnTimeout(60000);//空闲链接的超时时间(单位ms)
            clientBuilder.setCheckWaitTime(60000);//空闲链接的检测周期(单位ms)
            clientBuilder.setMaxConnPerHost(10);//每路最大连接数
            clientBuilder.setMaxTotalConn(200);//连接池最大连接数
            configStorage.setApacheHttpClientBuilder(clientBuilder); //设置自定义的ApacheHttpClientBuilder

            return service;
        }).collect(Collectors.toMap(service -> service.getWxCpConfigStorage().getAgentId(), a -> a));

    }
}
