package com.ywt.alipaympapi.face.impl;

import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayRequest;
import com.alipay.api.AlipayResponse;
import com.alipay.api.DefaultAlipayClient;
import com.ywt.alipaympapi.face.IAlipayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 支付宝服务实现
 */
@Component
@Slf4j
public class AlipayService implements IAlipayService {
    private static final String TERMINAL_TYPE = "ptc_publish_system_20200918";

    /**
     * 执行
     *
     * @param request
     * @return
     */
    @Override
    public <T extends AlipayResponse> T execute(String appId, AlipayRequest<T> request) {
        T response;
        try {
            AlipayClient alipayClient = getAlipayClient(appId);
            long start = System.currentTimeMillis();
            request.setTerminalType(TERMINAL_TYPE);
            response = alipayClient.execute(request, null, null);
            long end = System.currentTimeMillis();
            log.info("API名称:{}, 耗时:{} ms", request.getApiMethodName(), (end - start));

            if (response.isSuccess()) {
                log.info(response.getBody());

            } else {
                log.error("response body:{}", response.getBody(), null);
                throw new RuntimeException("调用支付宝服务异常, subCode:" + response.getSubCode() + ",subMsg:" + response.getSubMsg());
            }

            return response;
        } catch (Exception e) {
            throw new RuntimeException(String.format("调用支付宝服务异常，request:%s", request), e);
        }
    }

    private AlipayClient getAlipayClient(String appId) {
        //实例化客户端
        return new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", "", "", "json", "UTF-8", "", "RSA2");
    }
}