package com.jeequan.jeepay.core.model.params.alipay;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import com.jeequan.jeepay.core.annotate.ChannelMchId;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.constants.ChannelMchIdTypeEnum;
import com.jeequan.jeepay.core.model.params.IsvParams;
import com.jeequan.jeepay.core.utils.StringKit;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

/*
* 支付宝 isv参数定义
*
* @author terrfly
*
* @date 2021/6/8 16:34
*/
@Data
public class AlipayIsvParams extends IsvParams {

    /** 是否沙箱环境 */
    private Byte sandbox;

    /** pid */
    @ChannelMchId(type = ChannelMchIdTypeEnum.ISV_NO)
    private String pid;

    /** appId */
    private String appId;

    /** privateKey */
    private String privateKey;

    /** alipayPublicKey */
    private String alipayPublicKey;

    /** 签名方式 **/
    private String signType;

    /** 是否使用证书方式 **/
    private Byte useCert;

    /** app 证书 **/
    private String appPublicCert;

    /** 支付宝公钥证书（.crt格式） **/
    private String alipayPublicCert;

    /** 支付宝根证书 **/
    private String alipayRootCert;

    /** 授权token */
    private String appAuthToken;


    @Override
    public String deSenData() {

        AlipayIsvParams isvParams = this;
        if (StringUtils.isNotBlank(isvParams.privateKey)) {
            isvParams.setPrivateKey(StringKit.str2Star(isvParams.privateKey, 4, 4, 6));
        }
        if (StringUtils.isNotBlank(isvParams.alipayPublicKey)) {
            isvParams.setAlipayPublicKey(StringKit.str2Star(isvParams.alipayPublicKey, 6, 6, 6));
        }

        return JSONObject.toJSONString(isvParams);
    }

    @JSONField(serialize = false)
    public com.alipay.api.AlipayConfig getConfig() {
        com.alipay.api.AlipayConfig alipayConfig = new com.alipay.api.AlipayConfig();
        alipayConfig.setServerUrl(AlipayConfig.PROD_SERVER_URL);
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setAppId(appId);
        alipayConfig.setCharset(AlipayConfig.CHARSET);
        alipayConfig.setFormat(AlipayConfig.FORMAT);
        alipayConfig.setSignType(signType);

        if (useCert == CS.YES) {
            alipayConfig.setAppCertPath(appPublicCert);
            alipayConfig.setAlipayPublicCertPath(alipayPublicCert);
            alipayConfig.setRootCertPath(alipayRootCert);
        } else {
            alipayConfig.setAlipayPublicKey(alipayPublicKey);
        }

        return alipayConfig;
    }
}
