package com.jeequan.jeepay.agent.ctrl.payconfig;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jeequan.jeepay.agent.ctrl.CommonCtrl;
import com.jeequan.jeepay.core.aop.MethodLog;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
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.core.model.params.IsvParams;
import com.jeequan.jeepay.core.model.params.NormalMchParams;
import com.jeequan.jeepay.core.utils.StringKit;
import com.jeequan.jeepay.db.entity.*;
import com.jeequan.jeepay.service.impl.IsvInfoService;
import com.jeequan.jeepay.service.impl.MchAppService;
import com.jeequan.jeepay.service.impl.PayInterfaceConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/***
 * 支付配置
 *
 * @author terrfly
 *
 * @date 2022/3/21 0:13
 */
@RestController
@RequestMapping("/api/payConfig")
public class PayConfigController extends CommonCtrl {

    @Autowired
    private MchAppService mchAppService;
    @Autowired
    private PayInterfaceConfigService payInterfaceConfigService;
    @Autowired
    private IsvInfoService isvInfoService;

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

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

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

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

        lambdaQueryWrapper.like(StringUtils.isNotEmpty(ifName), PayInterfaceDefine::getIfName, ifName);

        AgentInfo agentInfo = agentInfoService.getById(getCurrentAgentNo());

        Map<String, IsvUserConn> ifCodeMap = new HashMap<>();

        // 服务商 配置 商户费率 | 下级服务商费率 | 自己配置信息 【显示  当前服务商所有接口】
        if (RateConfig.CONFIG_MODE_AGENTEMCH.equals(configMode) ||
                RateConfig.CONFIG_MODE_AGENTSUBAGENT.equals(configMode) ||
                RateConfig.CONFIG_MODE_AGENTSELF.equals(configMode)
        ) {

            ifCodeMap = isvInfoService.getIsvUserConn(CS.SYS_ROLE_TYPE.AGENT, agentInfo.getAgentNo(), CS.YES);
            List<String> ifCodeList = new ArrayList<>(ifCodeMap.keySet());

            if (ifCodeList.isEmpty()) { // 没有可用的接口
                return ApiRes.ok(ifCodeList);
            }
            lambdaQueryWrapper.in(PayInterfaceDefine::getIfCode, ifCodeList);

        } else if (RateConfig.CONFIG_MODE_AGENTAPPLYMENT.equals(configMode)) { // 服务商进件
            // 查询 当前服务商 开通的
            ifCodeMap = isvInfoService.getIsvUserConn(CS.SYS_ROLE_TYPE.AGENT, agentInfo.getAgentNo(), null);

            if (ifCodeMap.isEmpty()) { // 没有可用的接口
                return ApiRes.ok(Collections.emptyList());
            }

            lambdaQueryWrapper.in(PayInterfaceDefine::getIfCode, ifCodeMap.keySet());
            lambdaQueryWrapper.eq(PayInterfaceDefine::getIsSupportApplyment, CS.YES); // 查询支持进件的接口
        }


        final List<PayInterfaceDefine> list = new ArrayList<>();
        lambdaQueryWrapper.orderByAsc(PayInterfaceDefine::getCreatedAt);
        final Map<String, IsvUserConn> finalMap = ifCodeMap;
        payInterfaceDefineService.list(lambdaQueryWrapper).forEach(item -> {
            // 如果服务商上级配置的开启进件为关闭，那么最终展示的列表中显示的是否开启进件也为关闭
            IsvUserConn ifCodeInfo = finalMap.get(item.getIfCode());
            boolean isEnabled = ifCodeInfo.getStatus() == CS.YES && ifCodeInfo.getConfigStatus() == CS.YES;
            item.addExt("configState", ifCodeInfo.getStatus());

            item.setState(isEnabled ? CS.YES : CS.NO);
            list.add(item);
        });

        return ApiRes.ok(list);
    }


    /**
     * 查询已经配置的参数信息
     **/
    @PreAuthorize("hasAuthority('ENT_MCH_APP_PAY_CONFIG')")
    @GetMapping(value = "/interfaceSavedConfigs")
    public ApiRes interfaceSavedConfigs() {

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

        PayInterfaceDefine payInterfaceDefine = payInterfaceDefineService.getById(ifCode);

        String infoType = null;
        JSONArray ifDefineArray = null;

        Byte mchType = null; // 商户类型
        Byte isvIsOpenApplyment = 0; // 服务商是否开启进件

        // 服务商 配置商户应用信息
        if (RateConfig.CONFIG_MODE_AGENTEMCH.equals(configMode)) {
            infoType = CS.SYS_ROLE_TYPE.MCH_APP;

            MchInfo mchInfo = mchInfoService.getById(mchAppService.getById(infoId).getMchNo());
            mchType = mchInfo.getType();

            if (mchType == CS.MCH_TYPE_NORMAL) {
                ifDefineArray = JSON.parseArray(payInterfaceDefine.getNormalMchParams());
            } else {
                ifDefineArray = JSON.parseArray(payInterfaceDefine.getIsvsubMchParams());
            }
        }
        // 服务商 配置下级服务商信息
        else if (RateConfig.CONFIG_MODE_AGENTSUBAGENT.equals(configMode) || RateConfig.CONFIG_MODE_AGENTSELF.equals(configMode)) {
            infoType = CS.SYS_ROLE_TYPE.AGENT;

            if ("CURRENTAGENT".equals(infoId)) {
                infoId = getCurrentAgentNo();
            }
            AgentInfo agentInfo = agentInfoService.getById(infoId);
            if (agentInfo != null && StringUtils.isNotBlank(agentInfo.getIsvNo())) {
                PayInterfaceConfig isvIfConfig = payInterfaceConfigService.getByInfoIdAndIfCode(CS.SYS_ROLE_TYPE.ISV, agentInfo.getIsvNo(), ifCode);
                isvIsOpenApplyment = isvIfConfig != null ? isvIfConfig.getIsOpenApplyment() : 0;
            }
        }

        // 查询已经配置的信息
        PayInterfaceConfig payInterfaceConfig = payInterfaceConfigService.getByInfoIdAndIfCode(infoType, infoId, ifCode);

        if (payInterfaceConfig == null) {
            payInterfaceConfig = new PayInterfaceConfig();
        }

        // 处理脱敏数据
        if (StringUtils.isNotEmpty(payInterfaceConfig.getIfParams())) {

            if (RateConfig.CONFIG_MODE_MGRISV.equals(configMode)) {
                IsvParams isvParams = IsvParams.factory(ifCode, payInterfaceConfig.getIfParams());
                if (isvParams != null) {
                    payInterfaceConfig.setIfParams(isvParams.deSenData());
                }
            } else if (RateConfig.CONFIG_MODE_MGRMCH.equals(configMode)) {
                if (mchType == CS.MCH_TYPE_NORMAL) {
                    NormalMchParams isvParams = NormalMchParams.factory(ifCode, payInterfaceConfig.getIfParams());
                    if (isvParams != null) {
                        payInterfaceConfig.setIfParams(isvParams.deSenData());
                    }
                } else {
                }
            }
        }

        payInterfaceConfig.addExt("ifDefineArray", ifDefineArray);
        payInterfaceConfig.addExt("mchType", mchType);
        payInterfaceConfig.addExt("configPageType", payInterfaceDefine.getConfigPageType());
        payInterfaceConfig.addExt("isSupportApplyment", payInterfaceDefine.getIsSupportApplyment()); // 支付接口是否支持进件
        payInterfaceConfig.addExt("isvIsOpenApplyment", isvIsOpenApplyment); // 上级服务商是否开启进件
        return ApiRes.ok(payInterfaceConfig);
    }


    /**
     * 更新支付参数
     **/
    @PreAuthorize("hasAuthority('ENT_MCH_APP_PAY_CONFIG')")
    @PostMapping("/interfaceParams")
    @MethodLog(remark = "更新支付参数")
    public ApiRes saveOrUpdate() {

        PayInterfaceConfig payInterfaceConfig = getObject(PayInterfaceConfig.class);

        String configMode = payInterfaceConfig.extv().getString("configMode");  // 设置类型

        String infoType = null;


        if (RateConfig.CONFIG_MODE_AGENTEMCH.equals(configMode)) {
            infoType = CS.SYS_ROLE_TYPE.MCH_APP;
        }
        // 服务商 配置下级服务商
        else if (RateConfig.CONFIG_MODE_AGENTSUBAGENT.equals(configMode) || RateConfig.CONFIG_MODE_AGENTSELF.equals(configMode)) {
            infoType = CS.SYS_ROLE_TYPE.AGENT;

            if ("CURRENTAGENT".equals(payInterfaceConfig.getInfoId())) {
                payInterfaceConfig.setInfoId(getCurrentAgentNo());
            }
        }

        payInterfaceConfig.setInfoType(infoType);

        //添加更新者信息
        Long userId = getCurrentUser().getSysUser().getSysUserId();
        String realName = getCurrentUser().getSysUser().getRealname();
        payInterfaceConfig.setUpdatedUid(userId);
        payInterfaceConfig.setUpdatedBy(realName);

        //根据 服务商号、接口类型 获取商户参数配置
        PayInterfaceConfig dbRecoed = payInterfaceConfigService.getByInfoIdAndIfCode(payInterfaceConfig.getInfoType(), payInterfaceConfig.getInfoId(), payInterfaceConfig.getIfCode());
        //若配置存在，为saveOrUpdate添加ID，第一次配置添加创建者
        if (dbRecoed != null) {
            payInterfaceConfig.setId(dbRecoed.getId());

            // 合并支付参数
            payInterfaceConfig.setIfParams(StringKit.marge(dbRecoed.getIfParams(), payInterfaceConfig.getIfParams(), dbRecoed.getIfCode()));
        } else {
            payInterfaceConfig.setCreatedUid(userId);
            payInterfaceConfig.setCreatedBy(realName);
        }

        boolean result = payInterfaceConfigService.saveOrUpdate(payInterfaceConfig);
        if (!result) {
            return ApiRes.fail(ApiCodeEnum.SYSTEM_ERROR, "配置失败");
        }

        return ApiRes.ok();
    }

    /**
     * 查询商户应用支付参数、费率是否配置
     * 用于发起进件  自动配置到应用时的提示
     */
    @GetMapping("/existPayParams/{appId}/{ifCode}")
    public ApiRes existPayParams(@PathVariable("appId") String appId, @PathVariable("ifCode") String ifCode) {

//        Integer range = getValInteger("range");
//        String mccCode = getValString("mccCode");
//        String isvNo = getValString("isvNo");
//
//        // 应用参数配置
//        PayInterfaceConfig interfaceConfig = payInterfaceConfigService.getByInfoIdAndIfCode(CS.SYS_ROLE_TYPE.MCH_APP, appId, ifCode);
//        if (interfaceConfig == null) {
//            return ApiRes.ok();
//        }
//
//        if (StringUtils.isNotBlank(interfaceConfig.getIfParams()) && !interfaceConfig.getIfParams().equals("{}")) {
//            return ApiRes.ok(JsonKit.newJson("existMchParams", CS.YES));
//        }
//
//        // 费率配置
//        Map<String, PaywayFee> paywayFeeMap = rateConfigService.queryPaywayFeeMap(appId + "_" + RateConfig.MCHRATE, CS.SYS_ROLE_TYPE.MCH_APP, ifCode, range, mccCode, isvNo);
//        if (paywayFeeMap != null && StringUtils.isNotBlank(interfaceConfig.getIfParams()) && !interfaceConfig.getIfParams().equals("{}")) {
//            return ApiRes.ok(JsonKit.newJson("existMchParams", CS.YES));
//        }

        return ApiRes.ok();
    }

}
