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.PayOrder;
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.AbstractChannelNoticeService;
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 2022/4/15 10:23
 */
@Service
@Slf4j
public class KqpayChannelNoticeService extends AbstractChannelNoticeService {

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

    @Override
    public MutablePair<String, Object> parseParams(HttpServletRequest request, String urlOrderId, NoticeTypeEnum noticeTypeEnum) {
        JSONObject reqParamJSON = getReqParamJSON();
        JSONObject notifyHead = reqParamJSON.getJSONObject("head");
        return MutablePair.of(notifyHead.getString("externalRefNumber"), reqParamJSON);
    }



    @Override
    public ChannelRetMsg doNotice(HttpServletRequest request, Object params, PayOrder payOrder, MchAppConfigContext mchAppConfigContext, NoticeTypeEnum noticeTypeEnum) {
        JSONObject respJson = (JSONObject) JSON.toJSON(params);
        log.info("快钱回调参数：{}",respJson);
        boolean verifyResult = verifyParams(respJson, mchAppConfigContext);
        log.info("快前参数解密结果：{}",respJson);
        // 验证参数失败
        if(!verifyResult){
            throw ResponseException.buildText("签名校验失败");
        }
        //验签成功后判断上游订单状态
        ResponseEntity okResponse = textResp(KqpayKit.resSuccess(respJson));
        ChannelRetMsg result = new ChannelRetMsg();
        result.setResponseEntity(okResponse);
        result.setChannelBizData(respJson);
        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"));
        JSONObject equityInfo = requestBody.getJSONObject("equityInfo");
        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;
        }
        return result;
    }


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