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

import cn.hutool.core.util.ObjUtil;
import com.jeequan.jeepay.core.ctrls.AbstractCtrl;
import com.jeequan.jeepay.core.entity.TransferOrder;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.exception.ResponseException;
import com.jeequan.jeepay.core.interfaces.paychannel.ITransferNoticeService;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
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.pay.service.PayMchNotifyService;
import com.jeequan.jeepay.service.impl.OrderProfitSettRecordService;
import com.jeequan.jeepay.service.impl.PayOrderService;
import com.jeequan.jeepay.service.impl.TransferOrderService;
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;

/**
 * 转账异步通知入口Controller
 *
 * @author zx
 * @since 2022/12/30 10:26
 */
@Slf4j
@Controller
public class TransferNoticeController extends AbstractCtrl {

    @Autowired
    private TransferOrderService transferOrderService;
    @Autowired
    private PayMchNotifyService payMchNotifyService;
    @Autowired
    private OrderProfitSettRecordService orderProfitSettRecordService;
    @Autowired
    private PayOrderService payOrderService;

    /**
     * 异步回调入口
     **/
    @ResponseBody
    @RequestMapping(value = {"/api/transfer/notify/{ifCode}", "/api/transfer/notify/{ifCode}/{transferId}"})
    public ResponseEntity doNotify(HttpServletRequest request, @PathVariable("ifCode") String ifCode, @PathVariable(value = "transferId", required = false) String urlOrderId) {

        String transferId = null;
        String logPrefix = "进入[" + ifCode + "]转账回调：urlOrderId：[" + StringUtils.defaultIfEmpty(urlOrderId, "") + "] ";
        log.info("===== {} =====", logPrefix);

        try {

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

            //查询转账接口是否存在
            ITransferNoticeService transferNotifyService = SpringBeansUtil.getBean(ifCode + "TransferNoticeService", ITransferNoticeService.class);

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

            // 解析转账单号 和 请求参数
            MutablePair<String, Object> mutablePair = transferNotifyService.parseParams(request, urlOrderId);
            if (mutablePair == null) { // 解析数据失败， 响应已处理
                log.error("{}, mutablePair is null ", logPrefix);
                throw new BizException("解析数据异常！"); //需要实现类自行抛出ResponseException, 不应该在这抛此异常。
            }

            // 解析到转账单号
            transferId = mutablePair.left;
            if (ObjUtil.isEmpty(transferId)) {
                log.error("解析回调数据转账单号为空, 转账单不存在");
                return ResponseEntity.ok(transferNotifyService.retOk(null));
            }
            log.info("{}, 解析数据为：transferId:{}, params:{}", logPrefix, transferId, mutablePair.getRight());

            // 获取转账单号 和 转账单数据
            TransferOrderEntity transferOrder = transferOrderService.getById(transferId);

            // 转账单不存在
            if (transferOrder == null) {
                log.error("{}, 转账单不存在. transferId={} ", logPrefix, transferId);
                return ResponseEntity.ok(transferNotifyService.retOk(null));
            }

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

            //调起接口的回调判断
            ChannelRetMsg notifyResult = transferNotifyService.doNotice(request, mutablePair.getRight(), transferOrder);

            // 返回null 表明出现异常， 无需处理通知下游等操作。
            if (notifyResult == null || notifyResult.getChannelState() == null || notifyResult.getResponseEntity() == null) {
                log.error("{}, 处理回调事件异常  notifyResult data error, notifyResult ={} ", logPrefix, notifyResult);

                return ResponseEntity.ok(transferNotifyService.retOk(null));
            }

            // 转账单是 【转账中状态】
            if (transferOrder.getState() == TransferOrder.STATE_ING) {
                if (notifyResult.getChannelState() == ChannelRetMsg.ChannelState.CONFIRM_SUCCESS) {
                    // 转账成功
                    boolean isUpdateSuccess = transferOrderService.updateIng2Success(transferId, notifyResult.getChannelOrderId());

                    if (isUpdateSuccess) {


                        //更新营销活动补贴金额
                        payOrderService.updateMarketAmt(transferOrder.getFlowNo(), transferOrder.getAmount());

                        // 计算订单的分润记录 ( 若异常 不影响订单后续逻辑，  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 (notifyResult.getChannelState() == ChannelRetMsg.ChannelState.CONFIRM_FAIL) {
                    // 转账失败
                    transferOrderService.updateIng2Fail(transferId, notifyResult.getChannelOrderId(), notifyResult.getChannelUserId(), notifyResult.getChannelErrCode());
                    payMchNotifyService.transferOrderNotify(transferOrderService.getById(transferId));
                }
            }

            log.info("===== {}, 转账单通知完成。 transferId={}, parseState = {} =====", logPrefix, transferId, notifyResult.getChannelState());

            return notifyResult.getResponseEntity();

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

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

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

}
