package com.jeequan.jeepay.pay.service;

import com.jeequan.jeepay.core.entity.TransferOrder;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.interfaces.IConfigContextQueryService;
import com.jeequan.jeepay.core.interfaces.paychannel.ITransferService;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.core.utils.JeepayKit;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.db.entity.OrderProfitSettRecord;
import com.jeequan.jeepay.db.entity.TransferOrderEntity;
import com.jeequan.jeepay.service.impl.OrderProfitSettRecordService;
import com.jeequan.jeepay.service.impl.TransferOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/*
 * 转账补单服务实现类
 *
 * @author zx
 *
 * @date 2022/12/29 17:47
 */

@Service
@Slf4j
public class TransferOrderReissueService {

    @Autowired
    private IConfigContextQueryService configContextQueryService;
    @Autowired
    private TransferOrderService transferOrderService;
    @Autowired
    private PayMchNotifyService payMchNotifyService;
    @Autowired
    private OrderProfitSettRecordService orderProfitSettRecordService;


    /**
     * 处理转账订单
     **/
    public ChannelRetMsg processOrder(TransferOrderEntity transferOrder) {

        try {

            String transferId = transferOrder.getTransferId();

            // 查询转账接口是否存在
            ITransferService transferService = SpringBeansUtil.getBean(JeepayKit.getIfCodeOrigin(transferOrder.getIfCode()) + "TransferService", ITransferService.class);

            // 支付通道转账接口实现不存在
            if (transferService == null) {
                log.error("{} interface not exists!", transferOrder.getIfCode());
                return null;
            }

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

            ChannelRetMsg channelRetMsg = transferService.query(transferOrder, mchAppConfigContext);
            if (channelRetMsg == null) {
                log.error("channelRetMsg is null");
                return null;
            }

            log.info("补单[{}]查询结果为：{}", transferId, channelRetMsg);

            // 查询成功
            if (channelRetMsg.getChannelState() == ChannelRetMsg.ChannelState.CONFIRM_SUCCESS) {
                // 转账成功
                boolean isUpdateSuccess = transferOrderService.updateIng2Success(transferId, channelRetMsg.getChannelOrderId());

                if (isUpdateSuccess) {

                    // 计算订单的分润记录 ( 若异常 不影响订单后续逻辑，  service内的事务)
                    try {
                        boolean isRunTask = orderProfitSettRecordService.insertProfitByPayOrder(transferOrder.getTransferId(), OrderProfitSettRecord.CAL_TYPE_TRANS_ORDER);
                        if (isRunTask) { // 实时结算
                            orderProfitSettRecordService.profit2BalanceAmount(transferOrder.getTransferId(), OrderProfitSettRecord.CAL_TYPE_TRANS_ORDER);
                        }
                    } catch (Exception e) {
                        log.error("计算转账分润错误, transferId={}", transferOrder.getTransferId(), e);
                    }

                    payMchNotifyService.transferOrderNotify(transferOrderService.getById(transferId));
                }


            } else if (channelRetMsg.getChannelState() == ChannelRetMsg.ChannelState.CONFIRM_FAIL) {
                // 转账失败
                transferOrderService.updateIng2Fail(transferId, channelRetMsg.getChannelOrderId(), channelRetMsg.getChannelUserId(), channelRetMsg.getChannelErrCode());
                payMchNotifyService.transferOrderNotify(transferOrderService.getById(transferId));
            }

            return channelRetMsg;

        } catch (Exception e) {  //继续下一次迭代查询
            log.error("error transferId = {}", transferOrder.getTransferId(), e);
            return null;
        }

    }


    /**
     * 处理返回的渠道信息，并更新订单状态
     * TransferOrder将对部分信息进行 赋值操作。
     **/
    public void processChannelMsg(ChannelRetMsg channelRetMsg, TransferOrderEntity transferOrder) {

        //对象为空 || 上游返回状态为空， 则无需操作
        if (channelRetMsg == null || channelRetMsg.getChannelState() == null) {
            return;
        }

        //明确成功
        if (ChannelRetMsg.ChannelState.CONFIRM_SUCCESS == channelRetMsg.getChannelState()) {

            this.updateInitOrderStateThrowException(TransferOrder.STATE_SUCCESS, transferOrder, channelRetMsg);

            // 计算订单的分润记录 ( 若异常 不影响订单后续逻辑，  service内的事务)
            try {
                boolean isRunTask = orderProfitSettRecordService.insertProfitByPayOrder(transferOrder.getTransferId(), OrderProfitSettRecord.CAL_TYPE_TRANS_ORDER);
                if (isRunTask) { // 实时结算
                    orderProfitSettRecordService.profit2BalanceAmount(transferOrder.getTransferId(), OrderProfitSettRecord.CAL_TYPE_TRANS_ORDER);
                }
            } catch (Exception e) {
                log.error("计算转账分润错误, transferId={}", transferOrder.getTransferId(), e);
            }

            payMchNotifyService.transferOrderNotify(transferOrderService.getById(transferOrder.getTransferId()));

            //明确失败
        } else if (ChannelRetMsg.ChannelState.CONFIRM_FAIL == channelRetMsg.getChannelState()) {

            this.updateInitOrderStateThrowException(TransferOrder.STATE_FAIL, transferOrder, channelRetMsg);
            payMchNotifyService.transferOrderNotify(transferOrderService.getById(transferOrder.getTransferId()));

            // 上游处理中 || 未知 || 上游接口返回异常  订单为支付中状态
        } else if (ChannelRetMsg.ChannelState.WAITING == channelRetMsg.getChannelState() ||
                ChannelRetMsg.ChannelState.UNKNOWN == channelRetMsg.getChannelState() ||
                ChannelRetMsg.ChannelState.API_RET_ERROR == channelRetMsg.getChannelState()

        ) {
            this.updateInitOrderStateThrowException(TransferOrder.STATE_ING, transferOrder, channelRetMsg);

            // 系统异常：  订单不再处理。  为： 生成状态
        } else if (ChannelRetMsg.ChannelState.SYS_ERROR == channelRetMsg.getChannelState()) {

        } else {

            throw new BizException("ChannelState 返回异常！");
        }

    }


    /**
     * 更新转账单状态 --》 转账单生成--》 其他状态  (向外抛出异常)
     **/
    private void updateInitOrderStateThrowException(byte orderState, TransferOrder transferOrder, ChannelRetMsg channelRetMsg) {

        transferOrder.setState(orderState);
        transferOrder.setChannelOrderNo(channelRetMsg.getChannelOrderId());
        transferOrder.setErrCode(channelRetMsg.getChannelErrCode());
        transferOrder.setErrMsg(channelRetMsg.getChannelErrMsg());

        boolean isSuccess = transferOrderService.updateInit2Ing(transferOrder.getTransferId());
        if (!isSuccess) {
            throw new BizException("更新转账单异常!");
        }

        isSuccess = transferOrderService.updateIng2SuccessOrFail(transferOrder.getTransferId(), transferOrder.getState(),
                channelRetMsg.getChannelOrderId(), channelRetMsg.getChannelErrCode(), channelRetMsg.getChannelErrMsg());
        if (!isSuccess) {
            throw new BizException("更新转账订单异常!");
        }
    }
}
