package shop.alien.storeplatform.util;

import com.alibaba.fastjson.JSONObject;
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.DatadigitalFincloudGeneralsaasTwometaCheckModel;
import com.alipay.api.request.DatadigitalFincloudGeneralsaasTwometaCheckRequest;
import com.alipay.api.response.DatadigitalFincloudGeneralsaasTwometaCheckResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import shop.alien.util.common.RandomCreateUtil;
import shop.alien.util.system.OSUtil;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 支付宝身份验证工具类
 *
 * @author ssk
 * @version 1.0
 * @since 2025-01-xx
 */
@Slf4j
@Component
public class AliApiUtil {

    /**
     * 商家端appId
     */
    @Value("${app.business.appId}")
    private String businessAppId;

    /**
     * 商家端app私钥
     */
    @Value("${app.business.appPrivateKey}")
    private String businessAppPrivateKey;

    /**
     * windows应用公钥证书文件路径
     */
    @Value("${app.business.win.appCertPath}")
    private String businessWinAppCertPath;

    /**
     * windows支付宝公钥证书文件路径
     */
    @Value("${app.business.win.alipayPublicCertPath}")
    private String businessWinAlipayPublicCertPath;

    /**
     * windows支付宝根证书文件路径
     */
    @Value("${app.business.win.alipayRootCertPath}")
    private String businessWinAlipayRootCertPath;

    /**
     * linux应用公钥证书文件路径
     */
    @Value("${app.business.linux.appCertPath}")
    private String businessLinuxAppCertPath;

    /**
     * linux支付宝公钥证书文件路径
     */
    @Value("${app.business.linux.alipayPublicCertPath}")
    private String businessLinuxAlipayPublicCertPath;

    /**
     * linux支付宝根证书文件路径
     */
    @Value("${app.business.linux.alipayRootCertPath}")
    private String businessLinuxAlipayRootCertPath;

    /**
     * 填写阿里配置
     *
     * @return AlipayConfig
     */
    private AlipayConfig setAlipayConfig() {
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
        alipayConfig.setAppId(businessAppId);
        alipayConfig.setPrivateKey(businessAppPrivateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        if ("windows".equals(OSUtil.getOsName())) {
            alipayConfig.setAppCertPath(businessWinAppCertPath);
            alipayConfig.setAlipayPublicCertPath(businessWinAlipayPublicCertPath);
            alipayConfig.setRootCertPath(businessWinAlipayRootCertPath);
        } else {
            alipayConfig.setAppCertPath(businessLinuxAppCertPath);
            alipayConfig.setAlipayPublicCertPath(businessLinuxAlipayPublicCertPath);
            alipayConfig.setRootCertPath(businessLinuxAlipayRootCertPath);
        }
        return alipayConfig;
    }

    /**
     * 身份证二要素核验
     *
     * @param name   姓名
     * @param idCard 身份证
     * @return true:验证通过，false:验证失败
     */
    public boolean verifyIdCard(String name, String idCard) {
        try {
            log.info("AliApiUtil.verifyIdCard?name={}&idCard={}", name, idCard);
            AlipayClient alipayClient = new DefaultAlipayClient(setAlipayConfig());
            // 构造请求参数以调用接口
            DatadigitalFincloudGeneralsaasTwometaCheckRequest request = new DatadigitalFincloudGeneralsaasTwometaCheckRequest();
            DatadigitalFincloudGeneralsaasTwometaCheckModel model = new DatadigitalFincloudGeneralsaasTwometaCheckModel();
            // 设置外部订单号
            model.setOuterBizNo("id_" + createOrderNo());
            // 设置姓名
            model.setCertName(name);
            // 设置证件号码
            model.setCertNo(idCard);
            // 设置证件类型
            model.setCertType("IDENTITY_CARD");
            request.setBizModel(model);
            DatadigitalFincloudGeneralsaasTwometaCheckResponse response = alipayClient.certificateExecute(request);
            JSONObject jsonObject = JSONObject.parseObject(response.getBody()).getJSONObject("datadigital_fincloud_generalsaas_twometa_check_response");
            return response.isSuccess() && "Success".equals(jsonObject.getString("msg")) && "T".equals(jsonObject.getString("match"));
        } catch (AlipayApiException e) {
            log.error("AliApiUtil.verifyIdCard ERROR Msg={}", e.getErrMsg());
            return false;
        }
    }

    /**
     * 生成订单号
     *
     * @return 订单号
     */
    private String createOrderNo() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return sdf.format(new Date()) + RandomCreateUtil.getRandomNum(4);
    }
}

