package com.gree.mall.manager.config.wx;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.google.common.collect.Maps;
import com.gree.mall.manager.plus.entity.AdminCompanyWechat;
import com.gree.mall.manager.plus.entity.AdminCompanyWechatPayConfig;
import com.gree.mall.manager.plus.service.AdminCompanyWechatPayConfigService;
import com.gree.mall.manager.plus.service.AdminCompanyWechatService;
import com.gree.mall.manager.utils.RedisUtil;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

@Component
@Configuration
public class WxConfiguration {

    private final static String keyPath = "classpath:/static/apiclient_cert.p12";

    //企业微信  key=agentId
//    public static Map<String,Map<Integer, WxCpService>> cpServices =Maps.newConcurrentMap();
    //微信小程序API key = companyWechatId
    public static Map<String,WxMaService> wxMaService = Maps.newConcurrentMap();
    //微信支付服务 key = companyWechatId
    public static Map<String,WxPayService> wxPayServices = Maps.newConcurrentMap();
    //小程序微信支付服务 key = companyWechatId
    public static Map<String,WxPayService> wxSubPayServices = Maps.newConcurrentMap();


    //微信配置支付服务 key = companyWechatId
    public static Map<String,WxPayService> wxPayWebsitServices = Maps.newConcurrentMap();
    //小程序配置微信支付服务 key = companyWechatId
    public static Map<String,WxPayService> wxSubPayWebsitServices = Maps.newConcurrentMap();

    //微信公众号
    public static Map<String, WxMpService> wxMpServices = Maps.newConcurrentMap();
    //发货模板  key = companyWechatId
    public static Map<String,String> temFhNotice = Maps.newConcurrentMap();

    @Value("${wechat.payment.notifyUrl}")
    private String notifyUrl;
//    @Value("${wechat.payment.refundNotifyUrl}")
//    private String refundNotifyUrl;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    AdminCompanyWechatService AdminCompanyWechatService;


    @Autowired
    AdminCompanyWechatPayConfigService adminCompanyWechatPayConfigService;


    @PostConstruct
    public void initWxServices() {
        //查询企业微信配置
        List<AdminCompanyWechat> list = AdminCompanyWechatService.list();
        List<AdminCompanyWechatPayConfig> adminCompanyWechatPayConfigs = adminCompanyWechatPayConfigService.list();
        reloadWxConfig(list);
        reloadWxWebsitConfig(adminCompanyWechatPayConfigs);
    }

    private void reloadWxWebsitConfig(List<AdminCompanyWechatPayConfig> list) {

        for (AdminCompanyWechatPayConfig adminCompanyWechatPayConfig : list) {
            if(StringUtils.isBlank(adminCompanyWechatPayConfig.getMchId()) || StringUtils.isBlank(adminCompanyWechatPayConfig.getSubAppId())){
                continue;
            }

            //初始化微信支付服务
            initWxPayService(adminCompanyWechatPayConfig,notifyUrl);
            initWxSubPayService(adminCompanyWechatPayConfig,notifyUrl);
        }
    }

    /**
     * 初始化微信小程序支付服务
     * @param adminCompanyWechatPayConfig
     */
    private static void initWxSubPayService(AdminCompanyWechatPayConfig adminCompanyWechatPayConfig,String notifyUrl){
        if(StringUtils.isAnyBlank(adminCompanyWechatPayConfig.getAppletAppid())){
            return;
        }
        String path = keyPath.toLowerCase();
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setAppId(adminCompanyWechatPayConfig.getAppId());
        wxPayConfig.setMchId(adminCompanyWechatPayConfig.getMchId());
        wxPayConfig.setMchKey(adminCompanyWechatPayConfig.getMchKey());
        wxPayConfig.setSubAppId(adminCompanyWechatPayConfig.getAppletAppid());
        wxPayConfig.setSubMchId(adminCompanyWechatPayConfig.getSubMchId());
        wxPayConfig.setNotifyUrl(notifyUrl);
        wxPayConfig.setKeyPath(path);
        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(wxPayConfig);

        wxSubPayWebsitServices.put(adminCompanyWechatPayConfig.getId(),wxPayService);
    }




    /**
     * 初始化微信支付服务
     * @param adminCompanyWechatPayConfig
     */
    private static void initWxPayService(AdminCompanyWechatPayConfig adminCompanyWechatPayConfig,String notifyUrl){

        String path = keyPath.toLowerCase();
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setAppId(adminCompanyWechatPayConfig.getAppId());
        wxPayConfig.setMchId(adminCompanyWechatPayConfig.getMchId());
        wxPayConfig.setMchKey(adminCompanyWechatPayConfig.getMchKey());
        wxPayConfig.setSubAppId(adminCompanyWechatPayConfig.getSubAppId());
        wxPayConfig.setSubMchId(adminCompanyWechatPayConfig.getSubMchId());
        wxPayConfig.setNotifyUrl(notifyUrl);
        wxPayConfig.setKeyPath(path);
        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(wxPayConfig);

        wxPayWebsitServices.put(adminCompanyWechatPayConfig.getId(),wxPayService);
    }

    public void reloadWxConfig(List<AdminCompanyWechat> list){

        for(AdminCompanyWechat companyWechat : list){
            if(StringUtils.isBlank(companyWechat.getMchId()) || StringUtils.isBlank(companyWechat.getSubAppId()) || StringUtils.isBlank(companyWechat.getSubSecret())){
                continue;
            }
            //初始化企业微信服务
            //initCpService(companyWechat,redisUtil);
            //初始化微信支付服务
            initWxPayService(companyWechat,notifyUrl);
            initWxSubPayService(companyWechat,notifyUrl);
            //初始化微信小程序服务
            initWxMaService(companyWechat,redisUtil);
            //初始化微信公众号服务
            initWxMpService(companyWechat,redisUtil);
        }
    }

    /**
     * 初始化企业微信服务
     */
//    private static void initCpService(AdminCompanyWechat companyWechat,RedisUtil redisUtil){
//        Map<Integer,String> secretMap = new HashMap<>();
//        secretMap.put(companyWechat.getAgentId1(),companyWechat.getSecret1());
//        secretMap.put(companyWechat.getAgentId2(),companyWechat.getSecret2());
//        secretMap.put(companyWechat.getAgentId3(),companyWechat.getSecret3());
//
//        Map<Integer, WxCpService> agentMap = new HashMap<>();
//        for (Integer agentId : secretMap.keySet()) {
//            //初始化企业微信服务
//            val configStorage = new WxCpLettuceRedisConfig(redisUtil);
//            configStorage.setCorpId(companyWechat.getCorpId());
//            configStorage.setAgentId(agentId);
//            configStorage.setCorpSecret(secretMap.get(agentId));
//
//            WxCpService wxCpService = new WxCpServiceImpl();
//            wxCpService.setWxCpConfigStorage(configStorage);
//
//            agentMap.put(agentId, wxCpService);
//        }
//        cpServices.put(companyWechat.getCompanyWechatId(), agentMap);
//    }

    @Bean
    public WxPayService zfireWxPay(){

        String path = keyPath.toLowerCase();
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setAppId("wxaddd13c267e81e70");
        wxPayConfig.setMchId("1602832292");
        wxPayConfig.setNotifyUrl(notifyUrl);
        wxPayConfig.setMchKey("29234234234u2u32ur3f33t30urt4390");
        wxPayConfig.setKeyPath(path);
        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(wxPayConfig);
        return wxPayService;
    }


    /**
     * 初始化微信支付服务
     * @param companyWechat
     */
    private static void initWxPayService(AdminCompanyWechat companyWechat,String notifyUrl){

        String path = keyPath.toLowerCase();
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setAppId(companyWechat.getAppId());
        wxPayConfig.setMchId(companyWechat.getMchId());
        wxPayConfig.setMchKey(companyWechat.getMchKey());
        wxPayConfig.setSubAppId(companyWechat.getSubAppId());
        wxPayConfig.setSubMchId(companyWechat.getSubMchId());
        wxPayConfig.setNotifyUrl(notifyUrl);
        wxPayConfig.setKeyPath(path);
        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(wxPayConfig);

        wxPayServices.put(companyWechat.getCompanyWechatId(),wxPayService);
    }

    /**
     * 初始化微信小程序支付服务
     * @param companyWechat
     */
    private static void initWxSubPayService(AdminCompanyWechat companyWechat,String notifyUrl){
        if(StringUtils.isAnyBlank(companyWechat.getAppletAppid())){
            return;
        }
        String path = keyPath.toLowerCase();
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setAppId(companyWechat.getAppId());
        wxPayConfig.setMchId(companyWechat.getMchId());
        wxPayConfig.setMchKey(companyWechat.getMchKey());
        wxPayConfig.setSubAppId(companyWechat.getAppletAppid());
        wxPayConfig.setSubMchId(companyWechat.getSubMchId());
        wxPayConfig.setNotifyUrl(notifyUrl);
        wxPayConfig.setKeyPath(path);
        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(wxPayConfig);

        wxSubPayServices.put(companyWechat.getCompanyWechatId(),wxPayService);
    }

    /**
     * 初始化小程序服务
     */
    private static void initWxMaService(AdminCompanyWechat companyWechat,RedisUtil redisUtil){
        if(StringUtils.isAnyBlank(companyWechat.getAppletAppid(),companyWechat.getAppletSecret())){
            return;
        }
        WxMaDefaultConfigImpl config = new WxMaLettuceRedisConfig(redisUtil);
        // 使用上面的配置时，需要同时引入jedis-lock的依赖，否则会报类无法找到的异常
        config.setAppid(companyWechat.getAppletAppid());
        config.setSecret(companyWechat.getAppletSecret());
        WxMaService service = new WxMaServiceImpl();
        service.setWxMaConfig(config);
        wxMaService.put(companyWechat.getCompanyWechatId(),service);
        //temFhNotice.put(companyWechat.getCompanyWechatId(),companyWechat.getTemplate());
    }

    /**
     * 初始化微信公众号服务
     * @param companyWechat
     * @param redisUtil
     */
    private static void initWxMpService(AdminCompanyWechat companyWechat,RedisUtil redisUtil){
        if(StringUtils.isBlank(companyWechat.getPubAppId()) || StringUtils.isBlank(companyWechat.getPubAppSecret())){
            return;
        }
        WxMpService service = new WxMpServiceImpl();
        WxMpDefaultConfigImpl wxMpDefaultConfig = new WxMpLettuceRedisConfig(redisUtil);
        wxMpDefaultConfig.setAppId(companyWechat.getPubAppId());
        wxMpDefaultConfig.setSecret(companyWechat.getPubAppSecret());
        service.setWxMpConfigStorage(wxMpDefaultConfig);
        wxMpServices.put(companyWechat.getCompanyWechatId(),service);
    }

}
