package com.jeequan.jeepay.pay.ctrl.channel.alipay.model.response;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/*
* 支付宝SPI  接口返回对象
*
* @author zx
*
* @date 2023/3/7 10:35
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Slf4j
public class AlipaySpiRes {

    /** response **/
    private SpiBaseResponse response;

    /** 签名值 **/
    private String sign;

    /** 业务处理成功 **/
    public static AlipaySpiRes okWithSign(String logPrefix, SpiBaseResponse response, String privateKey) throws AlipayApiException {
        SpiBaseResponse.ok(response);
        AlipaySpiRes alipaySpiRes = new AlipaySpiRes(response, AlipaySignature.rsaSign(JSON.toJSONString(response), privateKey, "UTF-8", "RSA2"));
        log.info("{}处理成功，响应：{}", logPrefix, JSON.toJSONString(alipaySpiRes));
        return alipaySpiRes;
    }

    /** 明确失败，需要重新扫码支付 **/
    public static AlipaySpiRes failWithSign(String logPrefix, String privateKey, String errCode, String errMsg) {
        try {
            AlipaySpiRes alipaySpiRes = new AlipaySpiRes();
            alipaySpiRes.setResponse(SpiBaseResponse.fail(errCode, errMsg));
            alipaySpiRes.setSign(AlipaySignature.rsaSign(JSON.toJSONString(alipaySpiRes.getResponse()), privateKey, "UTF-8", "RSA2"));

            log.info("{}处理失败，响应：{}", logPrefix, JSON.toJSONString(alipaySpiRes));
            return alipaySpiRes;
        } catch (AlipayApiException e) {
            log.error("{}响应签名异常", logPrefix, e);
            return fail(logPrefix, errCode, errMsg);
        }
    }

    /** 明确失败，需要重新扫码支付 **/
    public static AlipaySpiRes fail(String logPrefix, String errCode, String errMsg) {

        AlipaySpiRes alipaySpiRes = new AlipaySpiRes();
        alipaySpiRes.setResponse(SpiBaseResponse.fail(errCode, errMsg));

        log.info("{}处理失败，响应：{}", logPrefix, JSON.toJSONString(alipaySpiRes));
        return alipaySpiRes;
    }

}
