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

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.agent.ctrl.CommonCtrl;
import com.jeequan.jeepay.components.mq.model.MchAuditThirdNotifyMQ;
import com.jeequan.jeepay.components.mq.vender.IMQSender;
import com.jeequan.jeepay.converter.MchInfoConverter;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.MchModifyApplyment;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.interfaces.paychannel.IYsApplymentApiService;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.utils.JeepayKit;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.db.entity.MchAppEntity;
import com.jeequan.jeepay.db.entity.MchApplyment;
import com.jeequan.jeepay.db.entity.MchModifyApplymentEntity;
import com.jeequan.jeepay.service.impl.MchAppService;
import com.jeequan.jeepay.service.impl.MchApplymentService;
import com.jeequan.jeepay.service.impl.MchModifyApplymentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/api/mchApplyments")
public class YspayMchApplymentController extends CommonCtrl {

    @Autowired private MchApplymentService mchApplymentService;
    @Autowired private MchModifyApplymentService mchModifyApplymentService;
    @Autowired private MchAppService mchAppService;
    @Autowired private MchInfoConverter mchInfoConverter;
    @Autowired private IMQSender mqSender;

    /** 银盛  上传图片 **/
    @PostMapping("/yspayUpload/{recordId}")
    public ApiRes yspayUpload(@PathVariable("recordId") String recordId) {
        JSONObject paramJSON = getReqParamJSON();
        MchApplyment dbRecord = mchApplymentService.getById(recordId);
        if (dbRecord == null || (dbRecord.getState() != MchApplyment.STATE_AUDITING && dbRecord.getState() != MchApplyment.STATE_WAIT_VERIFY &&
                dbRecord.getState() != MchApplyment.STATE_WAIT_SIGN && dbRecord.getState() != MchApplyment.STATE_FINISH_SIGN)) {
            throw new BizException("当前申请单状态错误，无法继续。");
        }
        IYsApplymentApiService ysApplymentApiService = SpringBeansUtil.getBean(JeepayKit.getIfCodeOrigin(dbRecord.getIfCode()) + "ApplymentApiService", IYsApplymentApiService.class);
        String respJSONStr = "";
        try {
            // 更新参数
            dbRecord.setApplyDetailInfo(paramJSON.toJSONString());

            // 调起接口
            com.jeequan.jeepay.core.entity.MchApplyment mchApplymentImg = ysApplymentApiService.uploadImg(mchInfoConverter.toModel(dbRecord));

            respJSONStr = mchApplymentImg.getChannelVar1();

            MchApplyment updateRecord = new MchApplyment();
            updateRecord.setApplyDetailInfo(dbRecord.getApplyDetailInfo());
            BeanUtils.copyProperties(mchApplymentImg, updateRecord);

            // 更新数据
            updateRecord.setApplyId(recordId);
            mchApplymentService.updateById(updateRecord);

        } catch (BizException e) {
            logger.info("请求异常", e);
            throw e;
        }

        return ApiRes.ok(respJSONStr);
    }

    /** 银盛  资料确认 **/
    @PostMapping("/yspayConfirm/{recordId}")
    public ApiRes yspayConfirm(@PathVariable("recordId") String recordId) {
        MchApplyment dbRecord = mchApplymentService.getById(recordId);
        if (dbRecord == null || (dbRecord.getState() != MchApplyment.STATE_AUDITING && dbRecord.getState() != MchApplyment.STATE_WAIT_VERIFY &&
                dbRecord.getState() != MchApplyment.STATE_WAIT_SIGN && dbRecord.getState() != MchApplyment.STATE_FINISH_SIGN)) {
            throw new BizException("当前申请单状态错误，无法继续。");
        }
        IYsApplymentApiService ysApplymentApiService = SpringBeansUtil.getBean(JeepayKit.getIfCodeOrigin(dbRecord.getIfCode()) + "ApplymentApiService", IYsApplymentApiService.class);
        String respJSONStr = "";
        try {

            // 提交审核
            com.jeequan.jeepay.core.entity.MchApplyment applymentResult = ysApplymentApiService.attachConfirm(mchInfoConverter.toModel(dbRecord));

            respJSONStr = applymentResult.getApplyErrorInfo();

            MchApplyment updateRecordAudit = new MchApplyment();
            BeanUtils.copyProperties(applymentResult, updateRecordAudit);

            // 更新数据
            updateRecordAudit.setApplyId(recordId);
            mchApplymentService.updateById(updateRecordAudit);

        } catch (BizException e) {
            logger.info("请求异常", e);
            throw e;
        }

        return ApiRes.ok(respJSONStr);
    }

    /** 银盛 发起合同签约 **/
    @PostMapping("/ysSignApply/{recordId}")
    public ApiRes ysSignApply(@PathVariable("recordId") String recordId) {

        MchApplyment dbRecord = mchApplymentService.getById(recordId);
        if (dbRecord == null || dbRecord.getState() != MchApplyment.STATE_WAIT_SIGN) {
            throw new BizException("请刷新当前申请单状态，该申请单当前状态无法执行该操作。");
        }

        IYsApplymentApiService ysApplymentApiService = SpringBeansUtil.getBean(JeepayKit.getIfCodeOrigin(dbRecord.getIfCode()) + "ApplymentApiService", IYsApplymentApiService.class);

        // 调起接口
        com.jeequan.jeepay.core.entity.MchApplyment applymentResult = ysApplymentApiService.signApply(getReqParamJSON(), mchInfoConverter.toModel(dbRecord));

        // 更新商户费率配置
        MchApplyment updateRecordAudit = new MchApplyment();
        BeanUtils.copyProperties(applymentResult, updateRecordAudit);

        // 更新数据
        updateRecordAudit.setApplyId(recordId);
        mchApplymentService.updateById(updateRecordAudit);

        return ApiRes.ok(applymentResult.getChannelVar2());
    }

    /** 银盛 查询合同签约状态 **/
    @PostMapping("/ysSignQuery/{recordId}")
    public ApiRes ysSignQuery(@PathVariable("recordId") String recordId) {

        MchApplyment dbRecord = mchApplymentService.getById(recordId);
        if (dbRecord == null || dbRecord.getState() != MchApplyment.STATE_WAIT_SIGN) {
            throw new BizException("请刷新当前申请单状态，该申请单当前状态无法执行该操作。");
        }

        // 获取当前进件签约信息，未发起签约时为空
        if (StringUtils.isBlank(dbRecord.getChannelVar2())) {
            return ApiRes.ok();
        }

        IYsApplymentApiService ysApplymentApiService = SpringBeansUtil.getBean(IYsApplymentApiService.class);

        // 调起接口
        com.jeequan.jeepay.core.entity.MchApplyment applymentResult = ysApplymentApiService.signQuery(mchInfoConverter.toModel(dbRecord));

        // 更新商户费率配置
        MchApplyment updateRecordAudit = mchInfoConverter.toDbEntity(applymentResult);

        // 更新数据
        updateRecordAudit.setApplyId(recordId);
        mchApplymentService.updateById(updateRecordAudit);

        if (updateRecordAudit.getState() == MchApplyment.STATE_SUCCESS) {
            mchApplymentService.onApplymentSuccess(updateRecordAudit.getApplyId());
            mqSender.send(MchAuditThirdNotifyMQ.build(recordId, MchAuditThirdNotifyMQ.TYPE_AUDIT));
        }

        return ApiRes.ok(applymentResult.getChannelVar2());
    }

    /** 银盛 签约重发 **/
    @PostMapping("/ysSignSendAgain/{recordId}")
    public ApiRes ysSignSendAgain(@PathVariable("recordId") String recordId) {

        MchApplyment dbRecord = mchApplymentService.getById(recordId);

        if (dbRecord == null) {
            MchModifyApplymentEntity modifyApplyment = mchModifyApplymentService.getById(recordId);

            if (modifyApplyment == null || modifyApplyment.getState() != MchApplyment.STATE_WAIT_SIGN) {
                throw new BizException("请刷新当前申请单状态，该申请单当前状态无法执行该操作。");
            }

            IYsApplymentApiService ysApplymentApiService = SpringBeansUtil.getBean(CS.IF_CODE.YSPAY + "ApplymentApiService", IYsApplymentApiService.class);

            // 调起接口
            MchModifyApplyment applymentResult = ysApplymentApiService.signSendAgain(getReqParamJSON(), mchInfoConverter.toModel(modifyApplyment));

            // 更新数据
            if (!StrUtil.isEmpty(applymentResult.getChannelVar1())) {
                MchModifyApplymentEntity updateRecordAudit = new MchModifyApplymentEntity();
                updateRecordAudit.setApplyId(recordId);
                updateRecordAudit.setChannelVar1(applymentResult.getChannelVar1());
                mchModifyApplymentService.updateById(updateRecordAudit);
            }

            return ApiRes.ok(applymentResult.getChannelVar1());
        } else {
            if (dbRecord.getState() != MchApplyment.STATE_WAIT_SIGN) {
                throw new BizException("请刷新当前申请单状态，该申请单当前状态无法执行该操作。");
            }

            IYsApplymentApiService ysApplymentApiService = SpringBeansUtil.getBean(CS.IF_CODE.YSPAY + "ApplymentApiService", IYsApplymentApiService.class);

            // 调起接口
            com.jeequan.jeepay.core.entity.MchApplyment applymentResult = ysApplymentApiService.signSendAgain(getReqParamJSON(), mchInfoConverter.toModel(dbRecord));

            // 更新数据
            if (!StrUtil.isEmpty(applymentResult.getChannelVar2())) {
                MchApplyment updateRecordAudit = new MchApplyment();
                updateRecordAudit.setApplyId(recordId);
                updateRecordAudit.setChannelVar2(applymentResult.getChannelVar2());
                mchApplymentService.updateById(updateRecordAudit);
            }

            return ApiRes.ok(applymentResult.getChannelVar2());
        }
    }

    /** 银盛费率配置 **/
    @PostMapping("/ysPayRateConfig/{recordId}")
    public ApiRes ysPayRateConfig(@PathVariable("recordId") String recordId) {

        JSONObject reqParamJSON = getReqParamJSON();

        MchApplyment dbRecord = mchApplymentService.getById(recordId);
        if (dbRecord == null || (dbRecord.getState() != MchApplyment.STATE_AUDITING && dbRecord.getState() != MchApplyment.STATE_REJECT_WAIT_MODIFY
                && dbRecord.getState() != MchApplyment.STATE_WAIT_SIGN)) {
            throw new BizException("请刷新当前申请单状态，该申请单当前状态无法执行该操作。");
        }

        IYsApplymentApiService ysApplymentApiService = SpringBeansUtil.getBean(JeepayKit.getIfCodeOrigin(dbRecord.getIfCode()) + "ApplymentApiService", IYsApplymentApiService.class);

        // 调起接口
        com.jeequan.jeepay.core.entity.MchApplyment applymentResult = ysApplymentApiService.payRateConfig(reqParamJSON, mchInfoConverter.toModel(dbRecord));

        // 更新商户费率配置
        MchApplyment updateRecordAudit = new MchApplyment();
        // 配置成功更新费率
        if (applymentResult.getState() != null && applymentResult.getState() == MchApplyment.STATE_SUCCESS) {
            BeanUtils.copyProperties(applymentResult, updateRecordAudit);
        } else {
            applymentResult.setApplyDetailInfo(null);
            applymentResult.setState(MchApplyment.STATE_AUDITING);
            BeanUtils.copyProperties(applymentResult, updateRecordAudit);
        }

        // 更新数据
        updateRecordAudit.setApplyId(recordId);
        mchApplymentService.updateById(updateRecordAudit);

        return ApiRes.ok(applymentResult.getChannelVar1());

    }

    /** 银盛 配置相关信息 **/
    @PostMapping("/yspayInterfaceConfig/{applyId}/{mchAppId}")
    public ApiRes yspayInterfaceConfig(@PathVariable("applyId") String applyId, @PathVariable("mchAppId") String mchAppId) {

        String configType = getValStringRequired("configType"); // PAY_BASE_URL,  BIND_APP_ID,  SUBSCRIBE_APP_ID, QUERY
        String configVal = getValStringRequired("configVal");

        MchApplyment tbMchApplyment = mchApplymentService.getById(applyId);
        MchAppEntity mchAppEntity = mchAppService.getById(mchAppId);

        IYsApplymentApiService applymentApiService = SpringBeansUtil.getBean(JeepayKit.getIfCodeOrigin(tbMchApplyment.getIfCode()) + "ApplymentApiService", IYsApplymentApiService.class);

        if ("PAY_BASE_URL".equals(configType)) {

            return ApiRes.ok(applymentApiService.configPayBaseUrl(configVal, mchAppEntity.getAppId(), mchInfoConverter.toModel(tbMchApplyment)));

        } else if ("BIND_APP_ID".equals(configType)) {

            return ApiRes.ok(applymentApiService.configBindAppId(configVal, mchAppEntity.getAppId(), mchInfoConverter.toModel(tbMchApplyment)));

        } else if ("SUBSCRIBE_APP_ID".equals(configType)) {

            return ApiRes.ok(applymentApiService.configSubscribeAppId(configVal, mchAppEntity.getAppId(), mchInfoConverter.toModel(tbMchApplyment)));

        }

        return ApiRes.customFail("没有[" + configType + "]配置");
    }
}
