package com.njyunzhi.pet_identity.common;

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.constant.WxPayConstants;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.njyunzhi.pet_identity.config.WeixinConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class WxUtils {
    //
    private final WeixinConfig config;
    //
    private static WxMaService maService;
    // 微信支付
    private static WxPayService payService;

    @Autowired
    public WxUtils(WeixinConfig config) {
        this.config = config;
        this.maService = initMaService(config);
        this.payService = initPayService(config);
    }

    public WxMaService getMaService() {
        return maService;
    }

    private WxMaService initMaService(WeixinConfig config) {
        WxMaDefaultConfigImpl conf = new WxMaDefaultConfigImpl();
        WeixinConfig.Miniapp miniapp = config.getMiniapp();
        conf.setAppid(miniapp.getAppid());
        conf.setSecret(miniapp.getSecret());
        conf.setToken(miniapp.getToken());
        conf.setAesKey(miniapp.getAesKey());
        conf.setMsgDataFormat("JSON");

        WxMaService service = new WxMaServiceImpl();
        service.setWxMaConfig(conf);
        return service;
    }

    public WxPayService getPayService() {
        return payService;
    }

    private WxPayService initPayService(WeixinConfig config) {
        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(config.getPay().getAppId());
        payConfig.setMchId(config.getPay().getMchId());
        payConfig.setMchKey(config.getPay().getMchKey());
        payConfig.setSubAppId(config.getPay().getSubAppId());
        payConfig.setSubMchId(config.getPay().getSubMchId());
        payConfig.setKeyPath(config.getPay().getKeyPath());
        payConfig.setApiV3Key(config.getPay().getApiV3Key());
        payConfig.setPrivateKeyPath(config.getPay().getPrivateKeyPath());
        payConfig.setPrivateCertPath(config.getPay().getPrivateCertPath());
        // 固定小程序支付
        payConfig.setTradeType(WxPayConstants.TradeType.JSAPI);
        // 可以指定是否使用沙箱环境
        payConfig.setUseSandboxEnv(false);

        WxPayService service = new WxPayServiceImpl();
        service.setConfig(payConfig);
        return service;
    }
}
