package com.yonge.cooleshow.biz.dal.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.microsvc.toolkit.middleware.payment.common.api.PaymentServiceContext;
import com.microsvc.toolkit.middleware.payment.impl.AdapayPaymentServicePlugin;
import com.microsvc.toolkit.middleware.payment.impl.AliPaymentServicePlugin;
import com.microsvc.toolkit.middleware.payment.impl.WxPaymentServicePlugin;
import com.microsvc.toolkit.middleware.payment.impl.YeepayPaymentServicePlugin;
import com.microsvc.toolkit.middleware.payment.properties.PayConfigProperties;
import com.yonge.cooleshow.common.enums.EPayerType;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import com.yonge.cooleshow.biz.dal.entity.PaymentMerchantConfig;
import com.yonge.cooleshow.biz.dal.wrapper.PaymentMerchantConfigWrapper;
import com.yonge.cooleshow.biz.dal.mapper.PaymentMerchantConfigMapper;
import com.yonge.cooleshow.biz.dal.service.PaymentMerchantConfigService;

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

/**
 * 支付三方账户配置
 * 2023-07-28 16:53:51
 */
@Slf4j
@Service
public class PaymentMerchantConfigServiceImpl extends ServiceImpl<PaymentMerchantConfigMapper, PaymentMerchantConfig> implements PaymentMerchantConfigService {


    @Autowired
    private PayConfigProperties properties;

    @PostConstruct
    public void init(){
        List<PaymentMerchantConfig> list = this.list();

        if(CollectionUtils.isEmpty(list)) {
            return;
        }

        List<String> pluginNames = Lists.newArrayList();
        for (PaymentMerchantConfig config : list) {
            if (config.getPayerType() == null) {
                log.error("数据错误 {}", config);
            } else if (config.getPayerType().equals(EPayerType.ADAPAY)) {

                PayConfigProperties.AdapayPayConfig adapayPayConfig = new PayConfigProperties.AdapayPayConfig();
                adapayPayConfig.setEnable(true);
                adapayPayConfig.setAppId(config.getAppId());
                adapayPayConfig.setPayType(config.getPaymentVendor());
                adapayPayConfig.setMerchantKey(config.getMerKey());
                adapayPayConfig.setMerchantId(config.getApiKey());
                adapayPayConfig.setPayNotifyUrl(properties.getPayNotifyUrl());
                adapayPayConfig.setRefundNotifyUrl(properties.getRefundNotifyUrl());
                adapayPayConfig.setKeyPublic(config.getRsaPublicKey());
                adapayPayConfig.setKeyPrivate(config.getRsaPrivateKey());
                adapayPayConfig.setWxAppId(config.getWxAppId());
                adapayPayConfig.setWxAppSecret(config.getWxAppSecret());
                adapayPayConfig.setSupportCreditCards(properties.getSupportCreditCards());
                try {
                    AdapayPaymentServicePlugin plugin = new AdapayPaymentServicePlugin(config.getPaymentVendor(), adapayPayConfig, false);
                    PaymentServiceContext.addPlugin(plugin);

                    pluginNames.add(plugin.venderName());
                } catch (Exception e) {
                    log.error("初始[汇付]化支付插件失败", e);
                }
            } else if (config.getPayerType().equals(EPayerType.YEEPAY)){
                PayConfigProperties.YeepayPayConfig yeepayPayConfig = new PayConfigProperties.YeepayPayConfig();
                yeepayPayConfig.setEnable(true);
                yeepayPayConfig.setAppId(config.getAppId());
                yeepayPayConfig.setPayType(config.getPaymentVendor());
                yeepayPayConfig.setMerchantId(config.getMerKey());
                yeepayPayConfig.setPayNotifyUrl(properties.getPayNotifyUrl());
                yeepayPayConfig.setRefundNotifyUrl(properties.getRefundNotifyUrl());
                yeepayPayConfig.setKeyPublic(config.getRsaPublicKey());
                yeepayPayConfig.setKeyPrivate(config.getRsaPrivateKey());
                yeepayPayConfig.setWxAppId(config.getWxAppId());
                yeepayPayConfig.setWxAppSecret(config.getWxAppSecret());
                yeepayPayConfig.setSupportCreditCards(properties.getSupportCreditCards());
                yeepayPayConfig.setAlipayAppId(config.getAlipayAppId());
                yeepayPayConfig.setAlipayPrivateKey(config.getAlipayPrivateKey());
                yeepayPayConfig.setAlipayPublicKey(config.getAlipayPublicKey());
                yeepayPayConfig.setMiniAppId(config.getMiniAppId());
                yeepayPayConfig.setMiniAppSecret(config.getMiniAppSerret());
                try {
                    YeepayPaymentServicePlugin plugin = new YeepayPaymentServicePlugin(config.getPaymentVendor(), yeepayPayConfig, false);
                    PaymentServiceContext.addPlugin(plugin);

                    pluginNames.add(plugin.venderName());
                } catch (Exception e) {
                    log.error("初始化[易宝]支付插件失败", e);
                }
            } else if (config.getPayerType().equals(EPayerType.ORIGINAL)) {

                // 原生微信支付
                if (config.getPaymentVendor().startsWith("wxpay")) {
                    PayConfigProperties.WxPayConfig wxPayConfig = new PayConfigProperties.WxPayConfig();
                    wxPayConfig.setEnable(true);
                    wxPayConfig.setWxAppId(config.getWxAppId());
                    wxPayConfig.setWxAppSecret(config.getWxAppSecret());
                    wxPayConfig.setMerchantId(config.getWxMerchantId());
                    wxPayConfig.setMerchantPrivateKey(config.getWxMerchantPrivateKey());
                    wxPayConfig.setMerchantSerialNumber(config.getWxMerchantSerialNumber());
                    wxPayConfig.setApiV3Key(config.getWxApiV3Key());
                    wxPayConfig.setPrivateCertPath(config.getWxPrivateCertPath());
                    wxPayConfig.setPrivateKeyPath(config.getWxPrivateKeyPath());
                    wxPayConfig.setPayType(config.getPaymentVendor());
                    wxPayConfig.setPayNotifyUrl(properties.getPayNotifyUrl());
                    wxPayConfig.setRefundNotifyUrl(properties.getRefundNotifyUrl());
                    if (Objects.nonNull(properties.getWxpay())) {
                        wxPayConfig.setFeeRate(properties.getWxpay().getFeeRate());
                    }

                    try {
                        // 初始化微信支付插件
                        WxPaymentServicePlugin plugin = new WxPaymentServicePlugin(config.getPaymentVendor(), wxPayConfig, false);
                        PaymentServiceContext.addPlugin(plugin);

                        pluginNames.add(plugin.venderName());
                    } catch (Exception e) {
                        log.error("初始化[微信]支付插件失败", e);
                    }
                }

                // 原生支付宝支付
                if (config.getPaymentVendor().startsWith("alipay")) {
                    PayConfigProperties.AliPayConfig aliPayConfig = new PayConfigProperties.AliPayConfig();
                    aliPayConfig.setEnable(true);
                    aliPayConfig.setAppId(config.getAlipayAppId());
                    aliPayConfig.setPrivateKey(config.getAlipayPrivateKey());
                    aliPayConfig.setPublicKey(config.getAlipayPublicKey());
                    aliPayConfig.setSignType(config.getAliPaySignType());
                    aliPayConfig.setEncryptType(config.getAlipayContentSignType());
                    aliPayConfig.setEncryptKey(config.getAliPayContentSignKey());
                    aliPayConfig.setUseCert(false);
                    aliPayConfig.setPayType(config.getPaymentVendor());
                    aliPayConfig.setPayNotifyUrl(properties.getPayNotifyUrl());
                    aliPayConfig.setRefundNotifyUrl(properties.getRefundNotifyUrl());
                    if (Objects.nonNull(properties.getAlipay())) {
                        aliPayConfig.setFeeRate(properties.getAlipay().getFeeRate());
                    }

                    try {
                        // 初始化支付宝支付插件
                        AliPaymentServicePlugin plugin = new AliPaymentServicePlugin(config.getPaymentVendor(), aliPayConfig, false);
                        PaymentServiceContext.addPlugin(plugin);

                        pluginNames.add(plugin.venderName());
                    } catch (Exception e) {
                        log.error("初始化[支付宝]支付插件失败", e);
                    }
                }
            } else {
                log.error("数据错误 {}", config);
            }

        }
        log.info("初始化支付插件完成, plugins={}", pluginNames);
    }

    /**
     * 查询详情
     * @param id 详情ID
     * @return PaymentMerchantConfig
     */
    @Override
    public PaymentMerchantConfig detail(Long id) {
        
        return baseMapper.selectById(id);
    }

    
    /**
     * 分页查询
     * @param page IPage<PaymentMerchantConfig>
     * @param query PaymentMerchantConfigWrapper.PaymentMerchantConfigQuery
     * @return IPage<PaymentMerchantConfig>
     */
    @Override
    public IPage<PaymentMerchantConfig> selectPage(IPage<PaymentMerchantConfig> page, PaymentMerchantConfigWrapper.PaymentMerchantConfigQuery query) {
        
        return page.setRecords(baseMapper.selectPage(page, query));
    }

    /**
     * 添加
     * @param paymentMerchantConfig PaymentMerchantConfigWrapper.PaymentMerchantConfig
     * @return Boolean
     */
    @Override
    public Boolean add(PaymentMerchantConfigWrapper.PaymentMerchantConfig paymentMerchantConfig) {

        return this.save(JSON.parseObject(paymentMerchantConfig.jsonString(), PaymentMerchantConfig.class));
    }

    /**
     * 更新
     * @param paymentMerchantConfig PaymentMerchantConfigWrapper.PaymentMerchantConfig
     * @return Boolean
     */
    @Override
    public Boolean update(PaymentMerchantConfigWrapper.PaymentMerchantConfig paymentMerchantConfig){

        return this.updateById(JSON.parseObject(paymentMerchantConfig.jsonString(), PaymentMerchantConfig.class));       
    }


    @Override
    public PaymentMerchantConfig getByPaymentVendor(String paymentVendor) {
        return this.lambdaQuery()
                .eq(PaymentMerchantConfig::getPaymentVendor, paymentVendor)
                .last("limit 1")
                .one();
    }
}