package ink.wgink.module.wechat.service.pay;

import ink.wgink.common.base.DefaultBaseService;
import ink.wgink.exceptions.PropertiesException;
import ink.wgink.module.wechat.enums.PayAuthorizationTypeEnum;
import ink.wgink.module.wechat.manager.pay.v3.PayManager;
import ink.wgink.properties.wechat.pay.v3.PayProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.FileNotFoundException;
import java.security.cert.X509Certificate;

/**
 * @ClassName: BasePayService
 * @Description: 基础支付业务
 * @Author: wanggeng
 * @Date: 2021/8/24 11:02 上午
 * @Version: 1.0
 */
public class BasePayService extends DefaultBaseService {

    public static final String PAY_SANDBOXNEW = "sandboxnew";

    @Autowired
    protected PayProperties payProperties;

    /**
     * 获得证书序列号
     *
     * @return
     */
    protected String getSerialNumber() throws FileNotFoundException {
        X509Certificate x509Certificate = PayManager.getInstance().getBusinessCertificate();
        String serialNumber = x509Certificate.getSerialNumber().toString(16);
        return serialNumber;
    }

    /**
     * 认证头
     *
     * @param requestMethod
     * @param urlSuffix
     * @param payProperties
     * @param jsonBody
     * @param payAuthorizationTypeEnum
     * @return
     * @throws FileNotFoundException
     */
    public String getAuthorization(RequestMethod requestMethod, String urlSuffix, String serialNumber, PayProperties payProperties, String jsonBody, PayAuthorizationTypeEnum payAuthorizationTypeEnum) throws Exception {
        return PayManager.getInstance().getAuthorization(requestMethod, urlSuffix, serialNumber, payProperties, jsonBody, payAuthorizationTypeEnum);
    }

    protected String getPayBaseUrl() {
        if (!payProperties.getActive()) {
            throw new PropertiesException("微信支付未激活");
        }
        if (!payProperties.getProduce()) {
            // 沙河环境
            return payProperties.getApiUrl() + "/" + PAY_SANDBOXNEW;
        }
        return payProperties.getApiUrl();
    }

}
