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

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.params.sandpay.SandpayConfig;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.thirdparty.channel.AbstractChannelNoticeService;
import com.jeequan.jeepay.thirdparty.channel.sandpay.kits.CertUtil;
import com.jeequan.jeepay.thirdparty.channel.sandpay.kits.CryptoUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
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/16 11:30
 */
@Service
@Slf4j
public class SandpayChannelNoticeService extends AbstractChannelNoticeService {

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

    @Override
    public MutablePair<String, Object> parseParams(HttpServletRequest request, String urlOrderId, NoticeTypeEnum noticeTypeEnum) {

        try {

            JSONObject params = getReqParamJSON();
            // 接收返回参数
            JSONObject dataJson = params.getJSONObject("data");
            JSONObject bodyJson = dataJson.getJSONObject("body");
            // 获取订单号
            String payOrderId = bodyJson.getString("orderCode");
            return MutablePair.of(payOrderId, params);

        } catch (Exception e) {
            log.error("error", e);
            throw ResponseException.buildText("ERROR");
        }
    }

    @Override
    public ChannelRetMsg doNotice(HttpServletRequest request, Object params, PayOrder payOrder, MchAppConfigContext mchAppConfigContext, NoticeTypeEnum noticeTypeEnum) {
        try {

            ChannelRetMsg result = ChannelRetMsg.confirmSuccess(null);

            String logPrefix = "【处理杉德支付回调】";

            // 获取请求参数
            JSONObject jsonParams = (JSONObject) params;
            log.info("{} 回调参数, jsonParams：{}", logPrefix, jsonParams);

            // 校验支付回调
            boolean verifyResult = verifyParams(jsonParams, mchAppConfigContext);
            // 验证参数失败
            if(!verifyResult){
                throw ResponseException.buildText("ERROR");
            }
            log.info("{}验证支付通知数据及签名通过", logPrefix);

            //验签成功后判断上游订单状态
            ResponseEntity okResponse = textResp(SandpayConfig.SUCCESS);
            result.setResponseEntity(okResponse);
            result.setChannelBizData(jsonParams);
            result.setChannelOrderId(jsonParams.getString("transIndex"));
            return result;

        } catch (Exception e) {
            log.error("error", e);
            throw ResponseException.buildText("ERROR");
        }
    }

    /**
     * 验证杉德支付通知参数
     * @return
     */
    public boolean verifyParams(JSONObject jsonParams, MchAppConfigContext mchAppConfigContext) {
        try {
            // 返回数据 [返回data参数 验签使用String类型]
            String dataStr = jsonParams.getString("data");
            JSONObject dataJson = JSONObject.parseObject(dataStr);

            JSONObject bodyObj = dataJson.getJSONObject("body");
            String sign = jsonParams.getString("sign");
            String status = bodyObj.getString("orderStatus");

            if (StringUtils.isEmpty(status) || !SandpayConfig.NOTIFY_SUCCESS.equals(status)) {
                log.info("订单状态未支付成功 [data]={}", status);
                return false;
            }
            if (StringUtils.isEmpty(sign)) {
                log.info("验签参数为空 [sign] :{}", sign);
                return false;
            }

            // 加载证书
            SandPayKit.initCert(mchAppConfigContext);
            boolean valid = CryptoUtil.verifyDigitalSign(dataStr.getBytes(SandPayKit.encoding), Base64.decodeBase64(sign),
                    CertUtil.getPublicKey(mchAppConfigContext.getAppId()), "SHA1WithRSA");
            // 验签失败
            if(!valid) {
                log.info("【杉德回调】 验签失败！ 回调参数：parameter = {}", jsonParams);
                return false;
            }
            return true;
        }catch (Exception e) {
            log.error("error", e);
            throw ResponseException.buildText("ERROR");
        }
    }

}
