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

import com.jeequan.jeepay.core.ctrls.AbstractCtrl;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.exception.ResponseException;
import com.jeequan.jeepay.core.interfaces.paychannel.IRepayNoticeService;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.db.entity.AccountChangeInfo;
import com.jeequan.jeepay.db.entity.AccountFundInfo;
import com.jeequan.jeepay.service.impl.AccountChangeInfoService;
import com.jeequan.jeepay.service.impl.AccountFundInfoService;
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;

/**
 * TODO
 *
 * @author crystal
 * @date 2024/3/27 10:22
 */
@Controller
@Slf4j
public class ChannelRepayNoticeController extends AbstractCtrl {

    @Autowired private AccountFundInfoService accountFundInfoService;

    @ResponseBody
    @RequestMapping(value= {"/api/channel/payment/notify/{ifCode}", "/api/channel/payment/notify/{ifCode}/{rid}"})
    public ResponseEntity doNotify(HttpServletRequest request, @PathVariable("ifCode") String ifCode, @PathVariable(value = "rid", required = false) String urlRid){
        String rid = null;
        String logPrefix = "进入[" +ifCode+ "]打款回调：urlRid：["+ StringUtils.defaultIfEmpty(urlRid, "") + "] ";
        log.info("打款回调：{}" , logPrefix);
        try {
            // 参数有误
            if(StringUtils.isEmpty(ifCode)){
                return ResponseEntity.badRequest().body("ifCode is empty");
            }
            //查询通知接口是否存在
            IRepayNoticeService noticeService = SpringBeansUtil.getBean(ifCode + "RepayNoticeService", IRepayNoticeService.class);
            // 提现通知接口实现不存在
            if(noticeService == null){
                log.error("{}, interface not exists ", logPrefix);
                return ResponseEntity.badRequest().body("[" + ifCode + "] interface not exists");
            }
            // 解析提现单号 和 请求参数
            MutablePair<String, Object> mutablePair = noticeService.parseParams(request, urlRid);
            if(mutablePair == null){
                log.error("{}, mutablePair is null ", logPrefix);
                throw new BizException("解析数据异常！");
            }
            rid = mutablePair.left;
            AccountFundInfo fundInfo = accountFundInfoService.getById(rid);
            if(fundInfo == null){
                log.error("{}, 数据不存在. rid={} ", logPrefix, rid);
                return ResponseEntity.badRequest().body("data record not exists");
            }
            //解析到提现单号
            log.info("{}, 解析数据为：rid:{}, params:{}", logPrefix, rid, mutablePair.getRight());
            //调起接口的回调判断
            ChannelRetMsg retMsg = noticeService.doNotice(request,mutablePair.left, mutablePair.getRight());
            // 返回null 表明出现异常， 无需处理通知下游等操作。
            if(retMsg == null || retMsg.getChannelState() == null || retMsg.getResponseEntity() == null){
                log.error("{}, 处理回调事件异常  notifyResult data error, notifyResult ={} ",logPrefix, retMsg);
                //需要实现类自行抛出ResponseException, 不应该在这抛此异常。
                throw new BizException("处理回调事件异常！");
            }

            boolean updateSuccess = true; //默认更新成功
            // 提现单是 【提现中状态】
            if(fundInfo.getState() == AccountFundInfo.PAYMENT) {
                // 渠道提现单号
                fundInfo.setChannelOrderId(retMsg.getChannelOrderId());
                // 明确成功
                if(ChannelRetMsg.ChannelState.CONFIRM_SUCCESS == retMsg.getChannelState()) {
                    updateSuccess = accountFundInfoService.updateIng2Success(rid, retMsg.getChannelOrderId());
                    //明确失败
                }else if(ChannelRetMsg.ChannelState.CONFIRM_FAIL == retMsg.getChannelState()) {
                    updateSuccess = accountFundInfoService.updateIng2Fail(rid, retMsg.getChannelErrMsg());
                }
                else if(ChannelRetMsg.ChannelState.WAITING == retMsg.getChannelState()) {
                    updateSuccess = accountFundInfoService.updateChannelRemark(rid, retMsg.getChannelErrMsg());
                }
            }
            // 更新提现单 异常
            if(!updateSuccess){
                log.error("{}, updateOrderSuccess = {} ",logPrefix, updateSuccess);
                return ResponseEntity.badRequest().body("update error");
            }
            log.info("{}, 打款通知完成。 rid={}, parseState = {} =====", logPrefix, rid, retMsg.getChannelState());
            return retMsg.getResponseEntity();
        } catch (BizException e) {
            log.error("{}, rid={}, BizException", logPrefix, rid, e);
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (ResponseException e) {
            log.error("{}, rid={}, ResponseException", logPrefix, rid, e);
            return e.getResponseEntity();
        } catch (Exception e) {
            log.error("{}, rid={}, 系统异常", logPrefix, rid, e);
            return ResponseEntity.badRequest().body("error");
        }
    }


}
