package com.jeequan.jeepay.pay.ctrl.payorder;

import cn.hutool.core.date.DateUtil;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.ctrls.AbstractCtrl;
import com.jeequan.jeepay.core.entity.MchInfo;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.exception.ResponseException;
import com.jeequan.jeepay.core.interfaces.IConfigContextQueryService;
import com.jeequan.jeepay.core.interfaces.paychannel.IChannelOrderAcceptService;
import com.jeequan.jeepay.core.interfaces.paychannel.IDivisionService;
import com.jeequan.jeepay.core.model.applyment.PaywayFee;
import com.jeequan.jeepay.core.model.autopos.ChannelOrderAcceptParams;
import com.jeequan.jeepay.core.model.autopos.ChannelOrderAcceptRetMsg;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.mchconfig.MchDivisionConfig;
import com.jeequan.jeepay.core.model.params.IsvParams;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.core.utils.JeepayKit;
import com.jeequan.jeepay.core.utils.SeqKit;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.db.entity.*;
import com.jeequan.jeepay.pay.service.PayOrderDivisionRefundOrderCommonService;
import com.jeequan.jeepay.pay.service.PayOrderProcessService;
import com.jeequan.jeepay.pay.service.RefundOrderProcessService;
import com.jeequan.jeepay.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.MutablePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 *
 * *  渠道订单接收 ctrl
 * * 渠道  --> 我方系统
 * * 作用： 将渠道订单信息同步到我方系统中
 * * 目前支持的有：  立码收
 *
*   智能POS交易通知  POS直接收款，交易结果通知接口
*
* @author zx
*
* @date 2021/6/8 17:26
*/
@Slf4j
@Controller
public class ChannelOrderAcceptController extends AbstractCtrl {

    @Autowired private PayOrderService payOrderService;
    @Autowired private RefundOrderService refundOrderService;
    @Autowired private IConfigContextQueryService configContextQueryService;
    @Autowired private PayOrderProcessService payOrderProcessService;
    @Autowired private RefundOrderProcessService refundOrderProcessService;
    @Autowired private MchStoreService mchStoreService;
    @Autowired private RateConfigService rateConfigService;
    @Autowired private MchConfigService mchConfigService;
    @Autowired private MchStoreDeviceService mchStoreDeviceService;
    @Autowired private PayOrderDivisionRefundOrderCommonService payOrderDivisionRefundOrderCommonService;


    /** 通知入口 **/
    @ResponseBody

    // 联调 地址
    // @RequestMapping("/api/orderPush/{ifCode}")

    // 正式 URL
   @RequestMapping(value= {
           "/api/pay/posNotify/{ifCode}", // 存量配置  （ 智能pos 订单推送模式（兼容历史数据） ）
           "/api/channelOrderAccept/{ifCode}",  //  channelOrderAccept 新通用命名  不加密
           "/api/channelOrderAccept/{ifCode}/{isvNo}"  //  channelOrderAccept 新通用命名  加密数据
   })
    public ResponseEntity channelOrderAccept(HttpServletRequest request, @PathVariable("ifCode") String ifCode,
                                             @PathVariable(value = "isvNo", required = false) String isvNo){

        String logPrefix = "[" +ifCode+ "]【接收订单推送】，isvNo=" + StringUtils.defaultIfBlank(isvNo, "");
        log.info("===== 进入{} =====" , logPrefix);
        String channelOrderNo = "";

        try {
            // 参数有误
            if(StringUtils.isEmpty(ifCode)){
                return ResponseEntity.badRequest().body("ifCode is empty");
            }

            //查询支付接口是否存在
            IChannelOrderAcceptService orderAcceptService= SpringBeansUtil.getBean(JeepayKit.getIfCodeOrigin(ifCode) + "ChannelOrderAcceptService", IChannelOrderAcceptService.class);

            // 支付通道接口实现不存在
            if(orderAcceptService == null){
                log.error("{}, interface not exists", logPrefix);
                return ResponseEntity.badRequest().body("[" + ifCode + "] interface not exists");
            }

            // 服务商号不为空，查询服务商参数，一般用于通知数据加密时，需要服务商参数解密
            IsvParams isvParams = null;
            if (StringUtils.isNotBlank(isvNo)) {
                isvParams = configContextQueryService.queryIsvParams(isvNo, ifCode);
                if (isvParams == null) {
                    log.error("{}, 服务商参数未配置", logPrefix);
                    return ResponseEntity.badRequest().body("[" + ifCode + "] system error");
                }
            }

            // 解析请求参数
            ChannelOrderAcceptParams acceptParams = orderAcceptService.parseParams(request, isvParams);
            if(acceptParams == null || acceptParams.getDeviceType() == null || StringUtils.isBlank(acceptParams.getDeviceNo())){ // 解析数据失败， 响应已处理
                log.error("{}, acceptParams is null ", logPrefix);
                return ResponseEntity.accepted().body("[" + ifCode + "] data parse error");
            }

            // 解析商户号、应用、门店
            MchStoreDevice mchStoreDevice = getDeviceByIfCodeAndDeviceNo(ifCode, acceptParams.getDeviceType(), acceptParams.getDeviceNo(), logPrefix);

            // 查询出商户应用的配置信息
            MchAppConfigContext mchAppConfigContext = configContextQueryService.queryMchInfoAndAppInfo(mchStoreDevice.getMchNo(), mchStoreDevice.getAppId());

            // 接口处理订单数据
            ChannelOrderAcceptRetMsg acceptRetMsg;
            if (ChannelOrderAcceptParams.TRADE_TYPE_PAYMENT.equals(acceptParams.getTradeType())) {
                acceptRetMsg = orderAcceptService.payNotice(request, acceptParams.getAcceptData(), mchAppConfigContext, ifCode);
            } else if (ChannelOrderAcceptParams.TRADE_TYPE_REFUND.equals(acceptParams.getTradeType())) {
                acceptRetMsg = orderAcceptService.refundNotice(request, acceptParams.getAcceptData(), mchAppConfigContext, ifCode);
            } else {
                throw new BizException("订单类型错误！");
            }

            // 返回null 表明出现异常。
            if(acceptRetMsg == null || acceptRetMsg.getChannelState() == null || acceptRetMsg.getResponseEntity() == null
                    || StringUtils.isBlank(acceptRetMsg.getChannelOrderId()) || acceptRetMsg.getChannelAmount() == null){
                log.error("{}, 处理回调事件异常  acceptRetMsg data error, acceptRetMsg ={} ",logPrefix, acceptRetMsg);
                throw new BizException("处理回调事件异常！");
            }
            channelOrderNo = acceptRetMsg.getChannelOrderId();

            // 非支付成功状态，直接返回
            if (acceptRetMsg.getChannelState() != ChannelRetMsg.ChannelState.CONFIRM_SUCCESS) {
                return acceptRetMsg.getResponseEntity();
            }

            if (ChannelOrderAcceptParams.TRADE_TYPE_PAYMENT.equals(acceptParams.getTradeType())) {

                processPayOrder(acceptRetMsg, mchAppConfigContext, mchStoreDevice, ifCode, logPrefix);

            } else if (ChannelOrderAcceptParams.TRADE_TYPE_REFUND.equals(acceptParams.getTradeType())) {

                processRefundOrder(acceptRetMsg, mchAppConfigContext, ifCode, logPrefix);

            }

            log.info("===== {}, 订单通知完成。 channelOrderNo={}, parseState = {} =====", logPrefix, channelOrderNo, acceptRetMsg.getChannelState());

            return acceptRetMsg.getResponseEntity();

        } catch (BizException e) {
            log.error("{}, channelOrderNo={}, BizException", logPrefix, channelOrderNo, e);
            return ResponseEntity.badRequest().body(e.getMessage());

        } catch (ResponseException e) {
            log.error("{}, channelOrderNo={}, ResponseException", logPrefix, channelOrderNo, e);
            return e.getResponseEntity();

        } catch (Exception e) {
            log.error("{}, channelOrderNo={}, 系统异常", logPrefix, channelOrderNo, e);
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    // 处理订单
    private void processPayOrder(ChannelOrderAcceptRetMsg channelResult, MchAppConfigContext mchAppConfigContext,
                                 MchStoreDevice mchStoreDevice, String ifCode, String logPrefix) {

        // 根据通道返回的支付订单号查询订单，存在则更新状态，不存在插入新订单
        if (StringUtils.isNotBlank(channelResult.getBizOrderId())) {
            PayOrder dbPayOrder = payOrderService.getById(channelResult.getBizOrderId());
            if (dbPayOrder != null) {
                payOrderProcessService.handlePayOrder4Channel(channelResult, dbPayOrder, mchAppConfigContext);
                return;
            }
        }

        // 查询当前支付接口  订单是否已创建
        long count = payOrderService.count(PayOrder.gw()
                .eq(PayOrder::getChannelOrderNo, channelResult.getChannelOrderId())
                .eq(PayOrder::getIfCode, ifCode)
        );
        if (count > 0) {
            log.error("{}, 当前订单已创建，渠道订单号：{}，", logPrefix, channelResult.getChannelOrderId());
            throw new ResponseException(channelResult.getResponseEntity());
        }

        PayOrder payOrder = genPayOrder(channelResult, mchAppConfigContext, mchStoreDevice, ifCode);
        boolean saveResult = payOrderService.save(payOrder);
        if (!saveResult) {
            log.error("{}, 数据库更新异常", logPrefix);
            throw new BizException("数据库更新异常！");
        }

        // 订单支付成功 其他业务逻辑
        payOrderProcessService.confirmSuccess(payOrder, mchAppConfigContext);
    }

    private void processRefundOrder(ChannelOrderAcceptRetMsg channelResult, MchAppConfigContext mchAppConfigContext, String ifCode, String logPrefix) {

        // 支付订单，根据退款通知中的 原渠道订单号（订单表的渠道订单号）查询
        PayOrder payOrder = payOrderService.getOneByChannelOrderId(ifCode, channelResult.getChannelPayOrderId());
        if (payOrder == null) {
            throw new BizException("支付订单不存在");
        }

        if(payOrder.getRefundState() == PayOrder.REFUND_STATE_ALL || payOrder.getRefundAmount() >= payOrder.getAmount()){
            throw new BizException("订单已全额退款");
        }

        if(payOrder.getState() != PayOrder.STATE_SUCCESS){
            throw new BizException("仅支付成功状态的订单才可发起退款");
        }

        Long refundAmount = channelResult.getChannelAmount();
        if(payOrder.getRefundAmount() + refundAmount > payOrder.getAmount()){
            throw new BizException("退款金额超过订单可退款金额！");
        }

        // 全部退款金额 （退款订单表）
        Long sumSuccessRefundAmount = refundOrderService.getBaseMapper().sumSuccessRefundAmount(payOrder.getPayOrderId());
        if(sumSuccessRefundAmount >= payOrder.getAmount()){
            throw new BizException("退款单已完成全部订单退款，本次申请失败");
        }

        if(sumSuccessRefundAmount + refundAmount > payOrder.getAmount()){
            throw new BizException("申请金额超出订单可退款余额，请检查退款金额");
        }

        // 根据通道处理后  返回的退款订单号查询订单，存在则更新状态，不存在插入新订单
        RefundOrder dbRefundOrder = refundOrderService.getById(channelResult.getBizOrderId());
        if (dbRefundOrder != null) {
            // 更新退款订单为成功状态  &&  处理退分
            updateRefundStateSuccessAndRefundDivision(true, channelResult, dbRefundOrder, mchAppConfigContext, logPrefix);
            return;
        }

        // 查询当前支付接口  退款订单是否已创建
        long count = refundOrderService.count(RefundOrder.gw()
                .eq(RefundOrder::getChannelOrderNo, channelResult.getChannelOrderId())
                .eq(RefundOrder::getIfCode, ifCode)
        );
        if (count > 0) {
            log.error("{}, 当前退款订单已创建，渠道退款订单号：{}，", logPrefix, channelResult.getChannelOrderId());
            throw new ResponseException(channelResult.getResponseEntity());
        }

        RefundOrder refundOrder = genRefundOrder(channelResult, payOrder, mchAppConfigContext);
        boolean saveResult = refundOrderService.save(refundOrder);
        if (!saveResult) {
            log.error("{}, 数据库更新异常", logPrefix);
            throw new BizException("数据库更新异常！");
        }

        // 更新退款订单为成功状态  &&  处理退分
        updateRefundStateSuccessAndRefundDivision(false, channelResult, refundOrder, mchAppConfigContext, logPrefix);

    }

    private MchStoreDevice getDeviceByIfCodeAndDeviceNo(String ifCode, Byte deviceType, String deviceNo, String logPrefix) {

        MchStoreDevice mchStoreDevice = mchStoreDeviceService.getOne(MchStoreDevice.gw()
                .eq(MchStoreDevice::getProvider, ifCode)
                .eq(MchStoreDevice::getDeviceType, deviceType)
                .eq(MchStoreDevice::getDeviceNo, deviceNo)
                .eq(MchStoreDevice::getBindState, CS.YES)
                .eq(MchStoreDevice::getState, CS.YES)
        );

        if (mchStoreDevice == null) {
            log.error("{}, 设备不存在，deviceNo={} ", logPrefix, deviceNo);
            throw new BizException("解析数据异常！");
        }

        return mchStoreDevice;
    }


    private PayOrder genPayOrder(ChannelOrderAcceptRetMsg channelResult, MchAppConfigContext mchAppConfigContext, MchStoreDevice mchStoreDevice, String ifCode){

        MchInfo mchInfo = mchAppConfigContext.getMchInfo();
        com.jeequan.jeepay.core.entity.MchApp mchApp = mchAppConfigContext.getMchApp();

        // 商户退款回调地址
        MchConfig payNotifyConfig = mchConfigService.getByMchNoAndConfigKey(mchInfo.getMchNo(), "mchPayNotifyUrl");
        if (payNotifyConfig == null || StringUtils.isBlank(payNotifyConfig.getConfigVal())) {
            log.error("商户支付回调地址未配置，商户号mchNo：{}", mchInfo.getMchNo());
        }

        PayOrder payOrder = new PayOrder();
        payOrder.setPayOrderId(SeqKit.genPayOrderId()); //生成订单ID
        payOrder.setMchNo(mchInfo.getMchNo()); //商户号
//        payOrder.setIsvNo(mchInfo.getIsvNo()); //服务商号
        payOrder.setAgentNo(mchInfo.getAgentNo());  // 服务商ID
        payOrder.setTopAgentNo(mchInfo.getTopAgentNo());    // 上级服务商ID
        payOrder.setAppId(mchApp.getAppId()); //商户应用appId
        payOrder.setMchName(mchInfo.getMchShortName()); //商户名称（简称）
        payOrder.setMchType(mchInfo.getType()); //商户类型
        payOrder.setEpUserId(mchInfo.getCreatedUid()); // 商户拓展员
        payOrder.setMchOrderNo(SeqKit.genMhoOrderId()); //商户订单号
        payOrder.setIfCode(ifCode); //接口代码
        payOrder.setWayCode(channelResult.getChannelWayCode()); //支付方式
        payOrder.setWayCodeType(StringUtils.defaultString(channelResult.getChannelWayCodeType(), CS.PAY_WAY_CODE_TYPE.OTHER)); // 渠道返回的支付方式类型

        payOrder.setAmount(channelResult.getChannelAmount()); //订单金额

        MchStore mchStore;
        String storeId = mchStoreDevice.getStoreId();
        if (storeId != null) {
            mchStore = mchStoreService.getById(storeId);
        }else {
            mchStore = mchStoreService.queryDefaultStore(mchInfo.getMchNo());  //查询默认门店
        }
        payOrder.setStoreId(mchStore.getStoreId());         // 门店ID
        payOrder.setStoreName(mchStore.getStoreName());     // 门店名称
        payOrder.setLng(mchStore.getLng());                 // 经度
        payOrder.setLat(mchStore.getLat());                 // 纬度
        payOrder.setAddress(mchStore.getAddress());         // 详细地址

        payOrder.setDeviceType((String) MchStoreDevice.covertDeviceType(mchStoreDevice.getDeviceType())); // 设备类型
        payOrder.setDeviceNo(mchStoreDevice.getDeviceNo()); // 设备号
        payOrder.setDeviceProvider(mchStoreDevice.getProvider()); // 设备厂商


        // 查询费率
        if (!CS.PAY_WAY_CODE.OUT_TRADE.equals(channelResult.getChannelWayCode())) {
            PaywayFee paywayFee = rateConfigService.queryCreateOrderPaywayFee(mchAppConfigContext.getMchApplyment().getApplyId(), mchAppConfigContext.getMchApplyment().getIsvNo(), mchAppConfigContext.getMchApplyment().getAutoConfigMchAppId(), ifCode, channelResult.getChannelWayCode());
            if(paywayFee == null){
                log.error("[{}]接收订单推送, 商户费率未配置", ifCode);
                throw new BizException("商户费率未配置！");
            }
            MutablePair<String, Long> feeAndSnapshot = paywayFee.calFeeAndSnapshot(payOrder.getAmount());
            payOrder.setMchFeeRate(feeAndSnapshot.left);
            payOrder.setMchFeeAmount(feeAndSnapshot.right); //商户手续费,单位分
            payOrder.setMchOrderFeeAmount(feeAndSnapshot.right); //商户手续费,单位分
        }else if (channelResult.getChannelFee() != null) {
            payOrder.setMchFeeAmount(channelResult.getChannelFee()); //商户手续费,单位分
            payOrder.setMchOrderFeeAmount(channelResult.getChannelFee()); //商户手续费,单位分
        }else {
            payOrder.setMchFeeAmount(0L); // 默认无手续费
            payOrder.setMchOrderFeeAmount(0L); // 默认无手续费
        }


        Date nowTime = new Date();
        payOrder.setCurrency("cny"); //币种
        payOrder.setState(PayOrder.STATE_SUCCESS); // 仅保存支付成功订单
        payOrder.setSuccessTime(nowTime);
        payOrder.setSubject("[" + mchStore.getStoreName() + "]收款"); //商品标题
        payOrder.setBody("[" + mchStore.getStoreName() + "]收款"); //商品描述信息
        payOrder.setChannelOrderNo(channelResult.getChannelOrderId()); // 渠道订单号
        payOrder.setChannelUser(channelResult.getChannelUserId()); //渠道用户标志

        payOrder.setPlatformOrderNo(channelResult.getPlatformOrderNo());
        payOrder.setPlatformMchOrderNo(channelResult.getPlatformMchOrderNo());

        // 渠道特殊参数，渠道自处理数据
        if (channelResult.getChannelBizData() != null) {
            payOrder.setChannelBizData(channelResult.getChannelBizData().toJSONString());
        }

        if (payNotifyConfig != null && StringUtils.isNotBlank(payNotifyConfig.getConfigVal())) {
            payOrder.setNotifyUrl(payNotifyConfig.getConfigVal()); // 支付通知地址
        }

        // 分账模式
        if (channelResult.getChannelDivisionMode() != null) {
            payOrder.setDivisionMode(channelResult.getChannelDivisionMode());
        } else {
            payOrder.setDivisionMode(PayOrder.DIVISION_MODE_FORBID); // 默认不分账

            // 当前商户配置模式为： 全局自动分账 && 金额满足
            MchDivisionConfig mchDivisionConfig = mchConfigService.queryMchDivisionConfigByDefault(payOrder.getMchNo());
            if(mchDivisionConfig.getOverrideAutoFlag() == CS.YES && payOrder.getAmount() >= mchDivisionConfig.getAutoDivisionRules().getAmountLimit()){
                payOrder.setDivisionMode(PayOrder.DIVISION_MODE_AUTO);
            }
        }

        payOrder.setCreatedAt(nowTime);
        return payOrder;
    }

    private RefundOrder genRefundOrder(ChannelOrderAcceptRetMsg channelResult, PayOrder payOrder, MchAppConfigContext mchAppConfigContext){

        MchInfo mchInfo = mchAppConfigContext.getMchInfo();
        com.jeequan.jeepay.core.entity.MchApp mchApp = mchAppConfigContext.getMchApp();

        // 商户退款回调地址
        MchConfig refundNotifyConfig = mchConfigService.getByMchNoAndConfigKey(mchInfo.getMchNo(), "mchRefundNotifyUrl");
        if (refundNotifyConfig == null || StringUtils.isBlank(refundNotifyConfig.getConfigVal())) {
            log.error("商户退款回调地址未配置，商户号mchNo：{}", mchInfo.getMchNo());
        }

        RefundOrder refundOrder = new RefundOrder();
        refundOrder.setRefundOrderId(SeqKit.genRefundOrderId()); //退款订单号
        refundOrder.setPayOrderId(payOrder.getPayOrderId()); //支付订单号
        refundOrder.setChannelPayOrderNo(payOrder.getChannelOrderNo()); //渠道支付单号
        refundOrder.setMchNo(mchInfo.getMchNo()); //商户号
        refundOrder.setAgentNo(mchInfo.getAgentNo());   // 服务商号
        refundOrder.setTopAgentNo(mchInfo.getTopAgentNo());   // 上级服务商号
//        refundOrder.setIsvNo(mchInfo.getIsvNo()); //服务商号
        refundOrder.setAppId(mchApp.getAppId()); //商户应用ID
        refundOrder.setMchName(mchInfo.getMchShortName()); //商户名称
        refundOrder.setStoreId(payOrder.getStoreId());  // 门店ID
        refundOrder.setStoreName(payOrder.getStoreName());  // 门店名称
        refundOrder.setMchType(mchInfo.getType()); //商户类型
        refundOrder.setMchRefundNo(SeqKit.genMhoRefundOrderId()); //商户退款单号
        refundOrder.setWayCode(payOrder.getWayCode()); //支付方式代码
        refundOrder.setWayCodeType(payOrder.getWayCodeType());  // 支付方式代码分类
        refundOrder.setIfCode(payOrder.getIfCode()); //支付接口代码
        refundOrder.setPayAmount(payOrder.getAmount()); //支付金额,单位分
        refundOrder.setRefundAmount(channelResult.getChannelAmount()); //退款金额,单位分
        refundOrder.setCurrency(payOrder.getCurrency()); //三位货币代码,人民币:cny
        refundOrder.setState(RefundOrder.STATE_ING); // 插入退款中订单，再更新成退款成功
        refundOrder.setClientIp(StringUtils.defaultIfEmpty(payOrder.getClientIp(), getClientIp())); //客户端IP
        refundOrder.setRefundReason("退款"); //退款原因
        refundOrder.setChannelOrderNo(channelResult.getChannelOrderId()); //渠道订单号
        refundOrder.setErrCode(channelResult.getChannelErrCode()); //渠道错误码
        refundOrder.setErrMsg(channelResult.getChannelErrMsg()); //渠道错误描述
        refundOrder.setRefundFeeAmount(0L); // 退还手续费，默认0 ， 退款成功，再更新。

        if (refundNotifyConfig != null && StringUtils.isNotBlank(refundNotifyConfig.getConfigVal())) {
            refundOrder.setNotifyUrl(refundNotifyConfig.getConfigVal()); // 退款通知地址
        }


        // 退款，不进行补单操作，超过7天 订单失效。
        Date nowTime = new Date();
        refundOrder.setExpiredTime(DateUtil.offsetDay(nowTime, 7)); // 订单超时关闭时间 默认7天
        refundOrder.setSuccessTime(nowTime); //订单退款成功时间
        refundOrder.setCreatedAt(nowTime); //创建时间

        return refundOrder;
    }

    // 更新退款订单为成功状态  &&  处理退分
    private void updateRefundStateSuccessAndRefundDivision(boolean isUpdateRefundOrder, ChannelOrderAcceptRetMsg channelResult, RefundOrder refundOrder,
                                                           MchAppConfigContext mchAppConfigContext, String logPrefix) {

        IDivisionService divisionService = getDivisionService(refundOrder.getIfCode());

        // 渠道是否自动退分账，true-自动退，无需系统调用
        boolean channelDivisionRefundMode = channelResult.getChannelDivisionRefundMode() != null &&
                        channelResult.getChannelDivisionRefundMode() == 1;

        // 退款业务发生事前 分账。
        // 直接更新
        if(!channelDivisionRefundMode && !isUpdateRefundOrder && divisionService != null && !divisionService.divisionRefundIsOrderRefundAfterProc()){
            // 处理分账回退逻辑
            payOrderDivisionRefundOrderCommonService.processDivisionRefund(refundOrder, mchAppConfigContext);
        }

        // 处理退款订单
        boolean updateOrderSuccess = refundOrderProcessService.handleRefundOrder4Channel(channelResult, refundOrder);
        if(!updateOrderSuccess){
            log.error("{}, updateOrderSuccess = {} ",logPrefix, updateOrderSuccess);
            throw ResponseException.buildText("update status error");
        }

    }

    private IDivisionService getDivisionService(String ifCode){
        IDivisionService divisionService = SpringBeansUtil.getBean(JeepayKit.getIfCodeOrigin(ifCode) + "DivisionService", IDivisionService.class);
        return divisionService;
    }

}
