package com.jeequan.jeepay.mgr.ctrl.transfer;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.IsvUserConn;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.db.entity.AgentInfo;
import com.jeequan.jeepay.db.entity.MchInfo;
import com.jeequan.jeepay.db.entity.RateConfig;
import com.jeequan.jeepay.db.entity.TransferInterfaceDefineEntity;
import com.jeequan.jeepay.mgr.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.IsvInfoService;
import com.jeequan.jeepay.service.impl.TransferInterfaceDefineService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * TODO
 *
 * @author deng
 * @since 2024/4/25
 */
@RestController
@RequestMapping("api/transferConfig")
public class TransferConfigController extends CommonCtrl {

    @Autowired
    private TransferInterfaceDefineService transferInterfaceDefineService;

    @Autowired
    private IsvInfoService isvInfoService;

    /**
     * 查询可用的支付接口
     * <p>
     * 使用功能项目：  参数及费率的填写
     * 服务商查询全部支付接口
     * 服务商查询服务商开启的支付接口
     **/
    @GetMapping("/ifCodes")
    public ApiRes ifCodes() {

        // 搜索条件
        String ifName = getValString("ifName");
        // infoId    运营平台 发起 商户进件， 此时infoId是商户的所属 商户ID
        String infoId = getValStringRequired("infoId");
        // 设置类型
        String configMode = getValStringRequired("configMode");

        // 支付接口列表
        LambdaQueryWrapper<TransferInterfaceDefineEntity> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(TransferInterfaceDefineEntity::getState, CS.YES); // 查询可用的支付接口列表

        lambdaQueryWrapper.like(ObjUtil.isNotEmpty(ifName), TransferInterfaceDefineEntity::getTransIfName, ifName);


        String infoType = null;

        // 配置服务商 支付参数
        if (RateConfig.CONFIG_MODE_MGRISV.equals(configMode)) {
            infoType = CS.SYS_ROLE_TYPE.ISV;
        } else if (RateConfig.CONFIG_MODE_MGRAGENT.equals(configMode)) {
            infoType = CS.SYS_ROLE_TYPE.AGENT;
        }

        final List<String> ifCodes = new ArrayList<>();

        // 进件 支付参数
        if (RateConfig.CONFIG_MODE_MGRAPPLYMENT.equals(configMode)) {
            MchInfo mchInfo = mchInfoService.getById(infoId);

            // CURRENT 查询将返回空
            if (mchInfo == null || StringUtils.isEmpty(mchInfo.getAgentNo())) {
                return ApiRes.ok();
            }

            // 根据渠道号获取ifCode
            Map<String, IsvUserConn> ifCodeMap = isvInfoService.getTransIsvUserConn(CS.SYS_ROLE_TYPE.MCH, mchInfo.getMchNo(), CS.YES);

            ifCodes.addAll(ifCodeMap.keySet());

        }

        // 运营平台 配置 服务商费率 【显示  服务商的所有接口】
        if (RateConfig.CONFIG_MODE_MGRAGENT.equals(configMode)) {
            // 查询当前服务商
            AgentInfo agentInfo = agentInfoService.getById(infoId);

            Map<String, IsvUserConn> ifCodeMap = isvInfoService.getTransIsvUserConn(CS.SYS_ROLE_TYPE.AGENT, agentInfo.getAgentNo(), null);
            ifCodes.addAll(ifCodeMap.keySet());
        }

        // 是否是新建发起方和接收方
        boolean isProcessApplyment = RateConfig.CONFIG_MODE_MGRAPPLYMENT.equals(configMode)
                || RateConfig.CONFIG_MODE_AGENTAPPLYMENT.equals(configMode)
                || RateConfig.CONFIG_MODE_MCHAPPLYMENT.equals(configMode);

        // 运营平台 配置 商户费率 【显示  服务商的所有接口】
        if (RateConfig.CONFIG_MODE_MGRMCH.equals(configMode)) {
            infoType = CS.SYS_ROLE_TYPE.MCH;
        }

        // 进件操作，只显示关联的通道信息
        if (isProcessApplyment) {
            infoType = CS.SYS_ROLE_TYPE.MCH;
            Map<String, IsvUserConn> ifCodeStateMap = isvInfoService.getTransIsvUserConn(infoType, infoId, CS.YES);
            if (!ifCodeStateMap.isEmpty()) {
                lambdaQueryWrapper.in(TransferInterfaceDefineEntity::getTransIfCode, ifCodes);
            }
        }

        lambdaQueryWrapper.orderByAsc(TransferInterfaceDefineEntity::getId);
        List<TransferInterfaceDefineEntity> list = transferInterfaceDefineService.list(lambdaQueryWrapper);

        if (list.isEmpty()) {
            return ApiRes.ok(list);
        }


        Map<String, IsvUserConn> ifCodeStateMap = isvInfoService.getTransIsvUserConn(infoType, infoId, null);
        if (CollUtil.isEmpty(ifCodeStateMap)) {
            return ApiRes.ok(list);
        }

        // 是否已配置
        list.forEach(r -> {
            String ifCode = r.getTransIfCode();
            Optional.ofNullable(ifCodeStateMap.get(ifCode)).ifPresent(it -> {
                r.addExt("configState", CS.YES);
            });
        });

        return ApiRes.ok(list);
    }
}
