package shop.alien.util.common;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class AlipayTradeRefund {

    /**
     * appId
     */
    @Value("${app.user.appId}")
    private String userAppId;

    /**
     * app私钥
     */
    @Value("${app.user.appPrivateKey}")
    private String userAppPrivateKey;

    /**
     * 支付宝公钥
     */
    @Value("${app.user.aliPayPublicKey}")
    private String userAliPayPublicKey;

    /**
     * 用户端配置
     *
     * @return
     */
    private AlipayConfig getAlipayConfig() {
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
        alipayConfig.setAppId(userAppId);
        alipayConfig.setPrivateKey(userAppPrivateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(userAliPayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        return alipayConfig;
    }

    public String processRefund(String outTradeNo, String refundAmount, String refundReason) {
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            AlipayTradeRefundModel model = new AlipayTradeRefundModel();
            model.setOutTradeNo(outTradeNo);
            model.setRefundAmount(refundAmount);
            model.setRefundReason(refundReason);
            request.setBizModel(model);
            AlipayTradeRefundResponse response = alipayClient.execute(request);
            String refundReslut = "";
            if (response.isSuccess()) {
                refundReslut = "调用成功";
            } else {
                refundReslut = "调用失败";
            }
            return refundReslut;
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

    }

}