package com.sqx.modules.app.service.impl;

import com.aliyun.dytnsapi20200217.Client;
import com.aliyun.dytnsapi20200217.models.CertNoTwoElementVerificationRequest;
import com.aliyun.dytnsapi20200217.models.CertNoTwoElementVerificationResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import com.sqx.common.exception.SqxException;
import com.sqx.modules.app.service.AliService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Service
@Slf4j
public class AliServiceImpl implements AliService {
    private final CommonInfoService commonInfoService;
    private Client client;

    public AliServiceImpl(CommonInfoService commonInfoService) {
        this.commonInfoService = commonInfoService;
    }

    @PostConstruct
    public void init() throws Exception {
        CommonInfo keyIdInfo = commonInfoService.findOne(85);
        CommonInfo securityInfo = commonInfoService.findOne(86);

        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(keyIdInfo.getValue())
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(securityInfo.getValue());
        config.endpoint = "dytnsapi.aliyuncs.com";
        this.client = new Client(config);
    }


    @Override
    public void authCertNo(String name, String idCard) {
        log.info("阿里云二要素认证请求参数: {} {}", name, idCard);
        CertNoTwoElementVerificationRequest certNoTwoElementVerificationRequest = new com.aliyun.dytnsapi20200217.models.CertNoTwoElementVerificationRequest()
                .setAuthCode("t92K8i9ae6")
                .setCertName(name)
                .setCertNo(idCard);
        RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            CertNoTwoElementVerificationResponse resp = client.certNoTwoElementVerificationWithOptions(certNoTwoElementVerificationRequest, runtime);
            log.info("阿里云二要素认证响应参数: {}", resp);
            if (resp.getStatusCode() != 200) {
                throw new SqxException("请求失败");
            }

            if (!"OK".equals(resp.getBody().getCode())) {
                throw new SqxException(resp.getBody().getMessage());
            }

            if (!"1".equals(resp.getBody().getData().getIsConsistent())) {
                throw new SqxException("身份证信息不匹配，认证失败");
            }
        } catch (Exception e) {
            throw new SqxException(e.getMessage());
        }
    }
}
