package com.yiqi.common.config;
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.google.common.collect.Maps;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager;
import com.wechat.pay.contrib.apache.httpclient.exception.HttpCodeException;
import com.wechat.pay.contrib.apache.httpclient.exception.NotFoundException;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.service.WxService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import me.chanjar.weixin.mp.util.WxMpConfigStorageHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Configuration
public class WxMaConfig {

    public final static String WXAPP = "wxapp";

    public final static String PUBLIC = "public";
    @Autowired
    private WxMaProperties wxMaProperties;

    @Bean
    public CompositeWxMaService compositeWxMaService() {
        Map<String, WxService> wxMaServiceMap = new HashMap<>();
        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
        config.setAppid(wxMaProperties.getAppid());
        config.setSecret(wxMaProperties.getSecret());
        WxMaService wxMaService = new WxMaServiceImpl();
        wxMaService.setWxMaConfig(config);
        wxMaServiceMap.put(WXAPP, wxMaService);

        WxMpDefaultConfigImpl publicConfig = new WxMpDefaultConfigImpl();
        publicConfig.setAppId(wxMaProperties.getPublicAppid());
        publicConfig.setSecret(wxMaProperties.getPublicSecret());
        publicConfig.setToken(wxMaProperties.getToken());
        publicConfig.setAesKey(wxMaProperties.getEncodingAESKey());
        WxMpService publicWxMaService = new WxMpServiceImpl();
        publicWxMaService.setWxMpConfigStorage(publicConfig);
        wxMaServiceMap.put(PUBLIC, publicWxMaService);

        WxMaService defaultWxMaService = (WxMaService) wxMaServiceMap.get(WXAPP);
        if(defaultWxMaService == null){
            throw new RuntimeException("默认的WxMaService不能为null, 请检查配置");
        }
        return new CompositeWxMaService(wxMaServiceMap, defaultWxMaService);
    }

}