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 com.ywt.alipaympapi.models.Constants;
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);
        }
    }

    /**
     * 构造 AlipayClient，调用 AlipaySDK。有些业务场景（如“智能”消息）下用 EasySDK 调不通，只能使用普通 SDK
     * @param appId 小程序 appId
     * FIXME: 后续扩展多医院需要将 pk & apk 配置化
     */
    public AlipayClient getAlipayClient(String appId) {
        String pk = Constants.MERCHANT_PRIVATE_KEY;
        String apk = Constants.ALIPAY_PUBLIC_KEY;
        //实例化客户端
        return new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appId, pk, "json", "UTF-8", apk, "RSA2");
    }
}