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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.RefundOrder;
import com.jeequan.jeepay.core.exception.ResponseException;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.thirdparty.channel.AbstractChannelRefundNoticeService;
import com.jeequan.jeepay.thirdparty.channel.kqpay.model.KqpayOrderStatus;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.MutablePair;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * 拉卡拉退款回调接口实现类
 *
 * @author xiaoyu
 *
 * @date 2021/12/24 11:31
 */
@Service
@Slf4j
public class KqpayChannelRefundNoticeService extends AbstractChannelRefundNoticeService {

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

    @Override
    public MutablePair<String, Object> parseParams(HttpServletRequest request, String urlOrderId, NoticeTypeEnum noticeTypeEnum) {
        try {
            JSONObject reqParamJSON = getReqParamJSON();
            JSONObject notifyHead = reqParamJSON.getJSONObject("head");
            return MutablePair.of(notifyHead.getString("externalRefNumber"), reqParamJSON);
        } catch (Exception e) {
            log.error("error", e);
            throw ResponseException.buildText("ERROR");
        }
    }

    @Override
    public ChannelRetMsg doNotice(HttpServletRequest request, Object params, RefundOrder refundOrder, MchAppConfigContext mchAppConfigContext, NoticeTypeEnum noticeTypeEnum) {
        String logPrefix = "【处理快钱退款回调】";
        try {
            JSONObject respJson = (JSONObject) JSON.toJSON(params);
            log.info("快钱回调参数：{}",respJson);
            boolean verifyResult = verifyParams(respJson, mchAppConfigContext);
            // 验证参数失败
            if(!verifyResult){
                throw ResponseException.buildText("签名校验失败");
            }
            log.info("快前参数解密结果：{}",respJson);
            //验签成功后判断上游订单状态
            ResponseEntity okResponse = textResp(KqpayKit.resSuccess(respJson));
            ChannelRetMsg result = new ChannelRetMsg();
            //验签成功后判断上游订单状态
            result.setResponseEntity(okResponse);
            JSONObject requestBody = respJson.getJSONObject("requestBody");
            KqpayOrderStatus orderStatus = KqpayOrderStatus.getVal(requestBody.getString("orderStatus"));
            result.setChannelOrderId(requestBody.getString("idOrderCtrl"));
            result.setPlatformMchOrderNo(requestBody.getString("idTxnCtrl"));
            result.setChannelErrCode(requestBody.getString("bizResponseCode"));
            result.setChannelErrMsg(requestBody.getString("bizResponseMessage"));
            result.setPlatformOrderNo(requestBody.getString("channelTradeNo"));
            result.setChannelUserId(requestBody.getString("thirdPartyBuyerId"));
            switch (orderStatus){
                case SUCCESS:
                    result.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_SUCCESS);
                    break;
                case FAIL:
                    result.setChannelState(ChannelRetMsg.ChannelState.CONFIRM_FAIL);
                    break;
                default:
                    result.setChannelState(ChannelRetMsg.ChannelState.WAITING);
                    break;
            }
            return result;
        } catch (Exception e) {
            log.error("error", e);
            throw ResponseException.buildText("ERROR");
        }
    }

    /**
     * 验证快钱退款通知参数
     * @return
     */
    public boolean verifyParams(JSONObject jsonParams, MchAppConfigContext mchAppConfigContext) {
        try {
            return KqpayKit.checkResultNotify(jsonParams,mchAppConfigContext);
        }catch (Exception e) {
            log.error("验证签名异常", e);
            return false;
        }
    }
}
