package com.jeequan.jeepay.bizcommons.manage;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.db.entity.*;
import com.jeequan.jeepay.service.impl.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 商户通道配置信息
 *
 * @author terrfly
 * @date 2022/3/30 16:27
 */
@Component
public class MchPayPassageConfigManage {

    @Autowired
    private MchPayPassageService mchPayPassageService;
    @Autowired
    private PayWayService payWayService;
    @Autowired
    private MchInfoService mchInfoService;
    @Autowired
    private MchAppService mchAppService;
    @Autowired
    private RateConfigService rateConfigService;
    @Autowired
    private PayInterfaceConfigService payInterfaceConfigService;
    @Autowired
    private PayInterfaceDefineService payInterfaceDefineService;

    /**
     * 支付方式 <--> 通道配置
     * 左侧列表（支付方式）
     **/
    public ApiRes queryPaywayList(String appId, String wayCode, String wayName, String wayType, String unionSearchId, IPage page) {

        //支付方式集合
        LambdaQueryWrapper<PayWay> wrapper = PayWay.gw();
        wrapper.eq(StrUtil.isNotBlank(wayType), PayWay::getWayType, wayType);
        wrapper.eq(StrUtil.isNotBlank(wayCode), PayWay::getWayCode, wayCode);
        wrapper.like(StrUtil.isNotBlank(wayName), PayWay::getWayName, wayName);

        // app模糊搜索
        if (StringUtils.isNotBlank(unionSearchId)) {
            wrapper.and(i -> {
                i.like(PayWay::getWayCode, unionSearchId)
                        .or().like(PayWay::getWayName, unionSearchId);
            });
        }

        // 查询分页数据
        IPage<PayWay> result = payWayService.page(page, wrapper);

        // 无数据
        if (result.getRecords().isEmpty()) {
            return ApiRes.page(result);
        }

        // 全部的支付方式
        Set<String> paywayCodeList = new HashSet<>();
        result.getRecords().stream().forEach(r -> paywayCodeList.add(r.getWayCode()));

        // 查询所有的支付方式， 当前已开通的
        Map<String, Byte> paywayCodeStateMap = new HashMap<>();

        // 查询当前商户已经开通的数据
        mchPayPassageService.list(MchPayPassage.gw()
                .select(MchPayPassage::getWayCode, MchPayPassage::getState)
                .eq(MchPayPassage::getAppId, appId)
                .eq(MchPayPassage::getState, CS.YES)
                .in(MchPayPassage::getWayCode, paywayCodeList)).stream().forEach(r -> {
            paywayCodeStateMap.put(r.getWayCode(), CS.YES);
        });

        result.getRecords().stream().forEach(r -> {
            // 是否已经配置
            r.addExt("isConfig", paywayCodeStateMap.get(r.getWayCode()) != null ? CS.YES : CS.NO);
        });

        return ApiRes.page(result);
    }


    /**
     * 支付方式 <--> 通道配置
     * 右侧列表（可用的支付接口）
     **/
    public ApiRes availablePayInterface(String appId, String wayCode) {

        MchAppEntity mchAppEntity = mchAppService.getById(appId);
        if (mchAppEntity == null || mchAppEntity.getState() != CS.YES) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
        }

        MchInfo mchInfo = mchInfoService.getById(mchAppEntity.getMchNo());
        if (mchInfo == null || mchInfo.getState() != CS.YES) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SEARCH);
        }

        Set<String> ifCodes = new HashSet<>();

        // 查询出 商户配置过费率的支付接口
        Map<String, RateConfig> rateConfigMap = new HashMap<>();
        rateConfigService.list(
                RateConfig.gw()
                        .eq(RateConfig::getInfoId, RateConfig.appendInfoByMchApp(appId))
                        .eq(RateConfig::getInfoType, CS.SYS_ROLE_TYPE.MCH_APP)
                        .eq(RateConfig::getWayCode, wayCode)
        ).stream().forEach(r -> {
            rateConfigMap.put(r.getIfCode(), r);
            ifCodes.add(r.getIfCode());
        });

        if (rateConfigMap.isEmpty()) {
            return ApiRes.page(new Page());
        }

        // 查询出 商户配置过 支付接口参数的  列表
        Map<String, PayInterfaceConfig> payInterfaceConfigMap = new HashMap<>();

        payInterfaceConfigService.list(PayInterfaceConfig.gw().eq(PayInterfaceConfig::getInfoId, appId).eq(PayInterfaceConfig::getInfoType, CS.SYS_ROLE_TYPE.MCH_APP)
                .in(PayInterfaceConfig::getIfCode, ifCodes)
                .eq(PayInterfaceConfig::getState, CS.YES)
        ).stream().forEach(r -> payInterfaceConfigMap.put(r.getIfCode(), r));

        if (payInterfaceConfigMap.isEmpty()) {
            return ApiRes.page(new Page());
        }

        // 查询当前开启的配置
        MchPayPassage mchPayPassage = mchPayPassageService.findMchPayPassage(mchInfo.getMchNo(), appId, wayCode);
        String currentOpenIfCode = mchPayPassage != null ? mchPayPassage.getIfCode() : "";

        // 查询支付接口
        List<PayInterfaceDefine> result = payInterfaceDefineService.list(PayInterfaceDefine.gw().in(PayInterfaceDefine::getIfCode, ifCodes).eq(PayInterfaceDefine::getState, CS.YES));
        result.stream().forEach(r -> {

            r.addExt("configState", currentOpenIfCode.equals(r.getIfCode()) ? CS.YES : CS.NO);
            r.addExt("paywayFee", rateConfigMap.get(r.getIfCode()).getPaywayFeeDetail());

        });

        return ApiRes.page(new Page().setRecords(result).setTotal(result.size()));
    }

}
