package com.jeequan.jeepay.thirdparty.channel.flpay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.ResponseException;
import com.jeequan.jeepay.core.interfaces.paychannel.IRepayNoticeService;
import com.jeequan.jeepay.core.model.DBPaymentConfig;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.db.entity.AccountChangeInfo;
import com.jeequan.jeepay.service.impl.AccountChangeInfoService;
import com.jeequan.jeepay.service.impl.SysConfigService;
import com.jeequan.jeepay.thirdparty.channel.AbstractRepayNoticeService;
import com.jeequan.jeepay.thirdparty.channel.flpay.model.ReqEntity;
import com.jeequan.jeepay.thirdparty.channel.kqpay.KqpayKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.MutablePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * TODO
 *
 * @author crystal
 * @date 2024/3/27 10:43
 */
@Service
@Slf4j
public class FlpayRepayNoticeService extends AbstractRepayNoticeService {

    @Autowired private SysConfigService sysConfigService;

    @Override
    public String getIfCode() {
        return CS.IF_CODE.FLPAY;
    }

    /**
     * 参数解析
     * @param request
     * @param urlOrderId
     * @return
     */
    @Override
    public MutablePair<String, Object> parseParams(HttpServletRequest request, String urlOrderId) {
        JSONObject reqParamJSON = getReqParamJSON();
        JSONObject bizContent = reqParamJSON.getJSONObject("bizContent");
        return MutablePair.of(bizContent.getString("bizOutNo"), reqParamJSON);
    }

    /**
     *
     * @param request
     * @param urlOrderId
     * @param params
     * @return
     */
    @Override
    public ChannelRetMsg doNotice(HttpServletRequest request, String urlOrderId, Object params) {
        JSONObject respJson = (JSONObject) JSON.toJSON(params);
        boolean verifyResult = verifyParams(respJson);
        if(!verifyResult){
            throw ResponseException.buildText("sign check error");
        }
        JSONObject biz = respJson.getJSONObject("bizContent");
        String channelRemark = "【渠道备注】";
        log.info("【灵工】打款状态回调，打款流水号：{},业务参数：{}", urlOrderId, biz);
        //失败原因
        String failCause = biz.getString("failCause");
        //审核状态 审核状态 0-待审核 1-审核通过 2-人工审核拒绝
        int auditStatus = biz.getIntValue("auditStatus");
        //发放状态 发放(推送)状态 0-待发放 1-发放通过 2-发放拒绝
        int grantStatus = biz.getIntValue("grantStatus");
        //支付状态 0-未处理 1-待打款 2-打款中 3-打款成功 4-打款失败 5-退票退款
        int payStatus = biz.getIntValue("payStatus");
        //支付失败原因
        String payFailCause = biz.getString("payFailCause");
        String bizNo = biz.getString("bizNo");
        ChannelRetMsg retMsg = ChannelRetMsg.waiting();
        ResponseEntity okResponse = textResp("success");
        retMsg.setResponseEntity(okResponse);
        retMsg.setChannelOrderId(bizNo);
        retMsg.setChannelErrMsg(channelRemark + failCause);
        if(grantStatus == 2 || auditStatus == 2){
            return retMsg;
        }
        retMsg.setChannelErrMsg(channelRemark + payFailCause);
        switch (payStatus){
            case 3:
                return ChannelRetMsg.confirmSuccess(bizNo);
        }
        return retMsg;
    }

    /**
     * 校验参数
     * @param noticeData
     * @return
     */
    public boolean verifyParams(JSONObject noticeData) {
        DBPaymentConfig config = sysConfigService.getDbPaymentConfig();
        if(CS.IF_CODE.FLPAY.equals(config.getPaymentType())){
            try {
                return FlKit.checkResultNotify(noticeData.toJavaObject(ReqEntity.class),config);
            }catch (Exception e) {
                log.error("验证签名异常", e);
                return false;
            }
        }
        return true;
    }
}
