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

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jeequan.jeepay.components.mq.vender.IMQSender;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.db.entity.*;
import com.jeequan.jeepay.mch.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.IsvUserConnService;
import com.jeequan.jeepay.service.impl.MchInfoService;
import com.jeequan.jeepay.service.impl.PayInterfaceConfigService;
import com.jeequan.jeepay.service.impl.TransferInterfaceDefineService;
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.*;
import java.util.stream.Collectors;

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

    @Autowired
    private TransferInterfaceDefineService transferInterfaceDefineService;
    @Autowired
    private MchInfoService mchInfoService;
    @Autowired
    private PayInterfaceConfigService payInterfaceConfigService;
    @Autowired
    private IMQSender mqSender;
    @Autowired
    private IsvUserConnService isvUserConnService;

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

        // 搜索条件
        String ifName = getValString("ifName");

        String infoId = getValStringRequired("infoId"); // infoId
        String configMode = getValStringRequired("configMode"); // 设置类型

        Integer range = getValInteger("range");
        String mccCode = getValString("mccCode");

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


        String infoType = CS.SYS_ROLE_TYPE.MCH_APP;

        MchInfo mchInfo = mchInfoService.getById(getCurrentMchNo());
        if (mchInfo.getType() == CS.MCH_TYPE_ISVSUB) {

            // 商户进件模式
            if (RateConfig.CONFIG_MODE_MCHAPPLYMENT.equals(configMode)) {

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

                // 获取关联的渠道信息
                List<String> isvList = isvUserConnService.lambdaQuery()
                        .eq(IsvUserConnEntity::getInfoType, CS.SYS_ROLE_TYPE.MCH)
                        .eq(IsvUserConnEntity::getStatus, CS.YES)
                        .eq(IsvUserConnEntity::getInfoId, mchInfo.getMchNo())
                        .list()
                        .stream().map(IsvUserConnEntity::getIsvNo).collect(Collectors.toList());

                if (isvList.isEmpty()) {
                    return ApiRes.ok(new ArrayList<>());
                }

                // 根据渠道号获取ifCode
                QueryWrapper<PayInterfaceConfig> query = Wrappers.query();
                // 去重
                query.select("DISTINCT")
                        .lambda()
                        .select(PayInterfaceConfig::getIfCode)
                        .eq(PayInterfaceConfig::getInfoType, CS.SYS_ROLE_TYPE.ISV)
                        .in(PayInterfaceConfig::getInfoId, isvList)
                        .eq(PayInterfaceConfig::getState, CS.YES)
                        .eq(PayInterfaceConfig::getIsOpenApplyment, CS.YES);

                payInterfaceConfigService.list(query).forEach(r -> ifCodes.add(r.getIfCode()));

                if (ifCodes.isEmpty()) {
                    return ApiRes.ok(new ArrayList<>());
                }

                lambdaQueryWrapper.in(TransferInterfaceDefineEntity::getTransIfCode, ifCodes); // 查询可用的支付接口列表

            } else {  // 特约商户无需配置

                return ApiRes.ok(new ArrayList<>());
            }
        }

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

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

        Map<String, Byte> stateMap = new HashMap<>();
        payInterfaceConfigService.lambdaQuery().select(PayInterfaceConfig::getIfCode, PayInterfaceConfig::getState)
                .eq(PayInterfaceConfig::getInfoId, infoId)
                .eq(PayInterfaceConfig::getInfoType, infoType)
                .list().forEach(r -> stateMap.put(r.getIfCode(), r.getState()));

        list.forEach(r -> {
            // 是否已配置
            if (RateConfig.CONFIG_MODE_MGRAGENT.equals(configMode)) { // 服务商查询的就是已经配置的接口，无需填入
                r.addExt("configState", stateMap.get(r.getTransIfCode()));
            } else {
                r.addExt("configState", ObjectUtil.defaultIfNull(stateMap.get(r.getTransIfCode()), 1));
            }
        });

        return ApiRes.ok(list);
    }
}
