package com.qnfhq.modules.authentication.util;

import cn.hutool.json.JSONUtil;
import com.aliyun.cloudauth_intl20220809.Client;
import com.aliyun.cloudauth_intl20220809.models.CheckResultRequest;
import com.aliyun.cloudauth_intl20220809.models.CheckResultResponse;
import com.aliyun.cloudauth_intl20220809.models.InitializeRequest;
import com.aliyun.cloudauth_intl20220809.models.InitializeResponse;
import com.aliyun.teaopenapi.models.Config;

import com.qnfhq.modules.authentication.entity.AikycRequest;
import com.qnfhq.modules.authentication.entity.ExtFaceInfo;
import com.qnfhq.modules.authentication.entity.ExtIdInfo;
import org.springframework.beans.factory.annotation.Value;

/**
 * 阿里云 eKYC 国际化版实名认证服务接口封装
 */
public class AliyunEkycUtil {

    /**
     * 代表认证流程不同安全水位的模式，可选值：
     * 01：普通模式，仅适用低风险且对设备信息采集限制的场景
     * 02：安全模式，相对严格的模式(默认)。
     */
    @Value("${aliyun.initialize.securityLevel}")
    private String securityLevel;
    /**
     * 自定义OCR质量检测阀值模式：
     * 0：标准模式
     * 1：严格模式
     * 2:宽松模式
     * 3（默认）：关闭质量检测
     */
    @Value("${aliyun.initialize.idThreshold}")
    private String idThreshold;
    /**
     * 要接入的产品方案。取值：
     * eKYC：使用eKYC产品方案，您的用户需要完成证件识别和活体认证整个流程。
     */
    @Value("${aliyun.initialize.productCode}")
    private String productCode;

    /**
     * merchantBizId
     */
    @Value("${aliyun.initialize.merchantBizId}")
    private String merchantBizId;

    /**
     * 回调地址
     */
    @Value("${aliyun.initialize.callbackUrl}")
    private String callbackUrl;


    //是否返回图片（"N"/"Y"）
    private final String isReturnImage="Y";

    private final Client client;

    /**
     * 构造认证服务客户端
     *
     * @param accessKeyId     阿里云 AccessKey ID
     * @param accessKeySecret 阿里云 AccessKey Secret
     * @param regionId        区域ID（如 cn-hongkong）
     * @param endpoint        服务端点（如 cloudauth-intl.cn-hongkong.aliyuncs.com）
     * @throws Exception 初始化客户端异常
     */
    public AliyunEkycUtil(String accessKeyId, String accessKeySecret, String regionId, String endpoint) throws Exception {
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret)
                .setRegionId(regionId)
                .setEndpoint(endpoint);
        this.client = new Client(config);
    }

    /**
     * 初始化实名认证流程
     *
     * @param aikycRequest 官方请求需要的所有参数
     * @return 初始化响应结果
     * @throws Exception API调用异常
     */
    public InitializeResponse initialize(AikycRequest aikycRequest) throws Exception {
        InitializeRequest request = new InitializeRequest()
                .setProductCode(productCode)
                .setMerchantBizId(merchantBizId)
                .setMerchantUserId(aikycRequest.getMerchantUserId())
                .setDocType(aikycRequest.getDocType())
                .setMetaInfo(aikycRequest.getMetaInfo())
                .setSecurityLevel(securityLevel)
                .setIdThreshold(idThreshold)
                .setReturnUrl(aikycRequest.getReturnUrl())
                .setCallbackUrl(callbackUrl)
                .setAuthorize(aikycRequest.getAuthorize());

        return client.initialize(request);
    }

    /**
     * 检查认证结果
     * @param transactionId 事务ID（初始化返回的 transactionId）
     * @return 认证结果
     * @throws Exception API调用异常
     */
    public CheckResultResponse checkResult(String transactionId) throws Exception {
        CheckResultRequest request = new CheckResultRequest()
                .setMerchantBizId(merchantBizId)
                .setTransactionId(transactionId)
                .setIsReturnImage(isReturnImage);

        return client.checkResult(request);
    }

    public static void main(String[] args) throws Exception {
        Config config = new Config()
                .setAccessKeyId("LTAI5tLViGeNkcYAwiw3pccS")
                .setAccessKeySecret("I5XkvAUpoRgqpm77QPBXgkQbjg47K0")
                .setRegionId("cn-hongkong")
                .setEndpoint("cloudauth-intl.cn-hongkong.aliyuncs.com");
        Client client = new Client(config);
        CheckResultRequest request = new CheckResultRequest()
                .setMerchantBizId("qiniufuhuaqi")
                .setTransactionId("hksd93c76aabbe6ec2d029e6c4725e51")
                .setIsReturnImage("Y");
        CheckResultResponse checkResultResponse = client.checkResult(request);
        String extFaceInfo = checkResultResponse.getBody().getResult().getExtFaceInfo();
        String extIdInfo = checkResultResponse.getBody().getResult().getExtIdInfo();
        ExtFaceInfo bean = JSONUtil.toBean(extFaceInfo, ExtFaceInfo.class);
        ExtIdInfo bean2 = JSONUtil.toBean(extIdInfo, ExtIdInfo.class);
        ExtIdInfo.OcrIdEditInfo ocrIdInfo = bean2.getOcrIdInfo();
        System.out.println(bean);
        System.out.println(bean2);
    }
}