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

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.agent.ctrl.CommonCtrl;
import com.jeequan.jeepay.bizcommons.manage.MchPayPassageConfigManage;
import com.jeequan.jeepay.components.mq.vender.IMQSender;
import com.jeequan.jeepay.core.aop.MethodLog;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.model.applyment.ApplymentBasicInfo;
import com.jeequan.jeepay.core.model.applyment.PaywayFee;
import com.jeequan.jeepay.core.utils.JsonKit;
import com.jeequan.jeepay.db.entity.MchApplyment;
import com.jeequan.jeepay.db.entity.MchPayPassage;
import com.jeequan.jeepay.service.impl.MchApplymentService;
import com.jeequan.jeepay.service.impl.MchPayPassageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/****
* 新版商户支付通道配置ctrl
*
* @author terrfly
*
* @date 2022/3/30 16:37
*/
@RestController
@RequestMapping("/api/mch/payPassages")
public class MchPayPassageConfigController extends CommonCtrl {

    @Autowired private MchPayPassageService mchPayPassageService;
    @Autowired private MchPayPassageConfigManage mchPayPassageConfigManage;
    @Autowired
    private MchApplymentService mchApplymentService;
    @Autowired
    private IMQSender mqSender;

    /**
     * 支付方式 <--> 通道配置
     * 左侧列表（支付方式）
     *
     * **/
    @GetMapping
    public ApiRes list() {

        String appId = getValStringRequired("appId");
        String wayCode = getValString("wayCode");
        String wayName = getValString("wayName");
        String unionSearchId = getValString("unionSearchId");

        return mchPayPassageConfigManage.queryPaywayList(appId, wayCode, wayName, null, unionSearchId, getIPage());
    }


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

        return mchPayPassageConfigManage.availablePayInterface(appId, wayCode);
    }


    /**
     * 更新商户使用的通道信息
     */
    @PostMapping("/mchPassage")
    @MethodLog(remark = "更新商户支付通道")
    public ApiRes updatePassage() {

        String appId = getValStringRequired("appId");
        String ifCode = getValStringRequired("ifCode");
        String wayCode = getValStringRequired("wayCode");
        Byte state = getValByteRequired("state");

        mchPayPassageService.updateMchPassageState(appId, wayCode, ifCode, state);
        return ApiRes.ok();

    }

    /**
     * 查询商户应用支付通道是否配置
     * 用于进件成功一键配置到应用，点击按钮时检查进件记录中包含的支付方式是否在该应用下已配置其他渠道
     */
    @GetMapping("/exist/{applyId}/{appId}")
    public ApiRes exist(@PathVariable("applyId") String applyId, @PathVariable("appId") String appId) {

        MchApplyment tbMchApplyment = mchApplymentService.getById(applyId);
        if (tbMchApplyment == null || tbMchApplyment.getState() != MchApplyment.STATE_SUCCESS) {
            return ApiRes.customFail("进件记录不存在或进件状态未成功");
        }

        // 获取当前进件记录费率配置
        ApplymentBasicInfo applymentBasicInfo = JSONObject.parseObject(tbMchApplyment.getApplyDetailInfo(), ApplymentBasicInfo.class);
        // 费率
        List<PaywayFee> paywayFeeList = applymentBasicInfo.getPaywayFeeList();

        // 费率为空，进件成功一键配置到应用将不执行配置费率和通道，可直接返回
        if (CollUtil.isEmpty(paywayFeeList)) {
            return ApiRes.ok();
        }

        // 获取费率配置的支付方式
        List<String> wayCodeList = new ArrayList<>();
        paywayFeeList.forEach(paywayFee -> {
            wayCodeList.add(paywayFee.getWayCode());
        });

        // 支付方式已配置其他渠道
        List<MchPayPassage> payPassages = mchPayPassageService.list(MchPayPassage.gw()
                .eq(MchPayPassage::getAppId, appId)
                .ne(MchPayPassage::getIfCode, tbMchApplyment.getIfCode())
                .in(MchPayPassage::getWayCode, wayCodeList));

        if (CollUtil.isNotEmpty(payPassages)) {
            return ApiRes.ok(JsonKit.newJson("existMchPayPassage", CS.YES));
        }

        return ApiRes.ok();
    }

    /**
     * 进件成功一键配置到应用，更新商户支付通道
     */
    @MethodLog(remark = "进件成功，一键配置商户支付信息")
    @PostMapping("/applyment/{applyId}/{appId}")
    public ApiRes updateMchPayPassageByApplyment(@PathVariable("applyId") String applyId, @PathVariable("appId") String appId) {

//        AutoConfigMchAppPayInfoResult result = mchApplymentService.autoConfigMchAppPayInfo(applyId, appId, getValByteRequired("isOverWrite") == CS.YES);
//
//        if (StringUtils.isNotBlank(result.getErrMsg())) {
//            return ApiRes.customFail(result.getErrMsg());
//        }

        return ApiRes.ok();
    }

}
