package cn.quant.baa.pay.config;

import cn.quant.baa.pay.acquirer.AcquirerPropertiesSource;
import cn.quant.baa.pay.acquirer.AcquirerPropertiesBuilder;
import cn.quant.baa.pay.acquirer.AcquirerProperties;
import cn.quant.baa.pay.acquirer.MerchantAcquirer;
import cn.quant.baa.pay.acquirer.alipay.AlipayMerchantAcquirer;
import cn.quant.baa.pay.acquirer.weixin.WeiXinMerchantAcquirer;
import cn.quant.baa.pay.jpa.entity.*;
import cn.quant.baa.pay.jpa.repository.*;
import cn.quant.baa.pay.model.DictionaryItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Collection;
import java.util.List;

/**
 * Created by Administrator on 2021/8/22 0022.
 */
@Configuration
public class AcquirerConfiguration {

    @Autowired
    private PayAccountRepository payAccountRepository;

    @Autowired
    private PayAppRepository payAppRepository;

    @Autowired
    private PayFeatureRepository payFeatureRepository;

    @Autowired
    private MchChannelRepository mchChannelRepository;

    public AcquirerPropertiesBuilder getBuilder() {
        List<PayAccountEntity> accounts = payAccountRepository.findAll();
        List<PayFeatureEntity> features = payFeatureRepository.findAll();
        List<PayAppEntity> apps = payAppRepository.findAll();

        AcquirerPropertiesBuilder builder = new AcquirerPropertiesBuilder();
        builder.accounts(accounts)
                .features(features)
                .apps(apps);

        accounts.clear();
        features.clear();
        apps.clear();
        return builder;
    }

    @Bean
    public AcquirerPropertiesSource acquirerPropertiesSource() {
        AcquirerPropertiesBuilder builder = getBuilder();
        List<MchChannelEntity> entities = mchChannelRepository.findAll();
        AcquirerPropertiesSource source = builder.build(entities);
        builder.release();
        entities.clear();
        return source;
    }

    @Bean
    public MerchantAcquirer acquirer(AcquirerPropertiesSource acquirerPropertiesSource) throws Exception {
        MerchantAcquirer merchantAcquirer = MerchantAcquirer.getInstance();
        Collection<AcquirerProperties> properties = acquirerPropertiesSource.getAll();
        for (AcquirerProperties property : properties) {
            if("WXP".equals(property.getPayChanCode())){
                WeiXinMerchantAcquirer acquirer = new WeiXinMerchantAcquirer();
                acquirer.init(property);
                merchantAcquirer.register(acquirer);
            } else if ("ALIP".equals(property.getPayChanCode())) {
                AlipayMerchantAcquirer acquirer = new AlipayMerchantAcquirer();
                acquirer.init(property);
                merchantAcquirer.register(acquirer);
            }
        }
        return merchantAcquirer;
    }



}
