package com.trade.service.message.impl;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponseBody;
import com.trade.common.utils.LoggerUtil;
import com.trade.service.message.SmsTemplate;
import darabonba.core.client.ClientOverrideConfiguration;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

/**
 * @description: 阿里云短发送功能
 * @Author: wanglang
 * @Date: 2024/3/30 15:15
 * @Version: 1.0
 */
@Component
public class AliyunSmsSend extends SmsTemplate {

    private static final Logger log = LoggerUtil.logger(LoggerUtil.LogFileNameEnum.SERVICES_LOG);;
    // 产品名称:云通信短信API产品,开发者无需替换
    private static final String product = "Dysmsapi";
    // 产品域名,开发者无需替换
    private static final String domain = "dysmsapi.aliyuncs.com";
    // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找) 目前用电理通的
    private static final String accessKeyId = "LTAItCqmNOZlYyVO";
    private static final String accessKeySecret = "jsfO0hJWC1pJoCFTbk3jZWPejUe3Xq";
    private static final String signName = "长安银科商业保理有限公司";

    @Override
    protected boolean manufacturer(String mobile, String templateCode, String randomCode) {
        AsyncClient client = null;
        try {
            // todo 未完善 accessKeyId accessKeySecret
            StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                    // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and
                    // ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
                    // .accessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                    .accessKeyId(accessKeyId)
                    // .accessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
                    .accessKeySecret(accessKeySecret)
                    // .securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token
                    .build());
            // Configure the Client
            client = AsyncClient.builder()
                    // .httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient
                    // (Apache HttpClient)
                    .credentialsProvider(provider)
                    // .serviceConfiguration(Configuration.create()) // Service-level configuration
                    // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                    .overrideConfiguration(ClientOverrideConfiguration.create().setEndpointOverride(domain)
                    // .setConnectTimeout(Duration.ofSeconds(30))
                    ).build();
            // Parameter settings for API request
            // todo 未完善 需要模板等 模板 目前用电理通的后期修改
            SendSmsRequest sendSmsRequest = SendSmsRequest.builder().phoneNumbers(mobile).signName(signName)
                    // Request-level configuration rewrite, can set Http request parameters, etc.
                    // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                    .templateCode(templateCode).templateParam("{\"code\":\"" + randomCode + "\"}").build();
            // Asynchronously get the return value of the API request
            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
            // Synchronously get the return value of the API request
            SendSmsResponse resp = response.get();
            SendSmsResponseBody responseBody = resp.getBody();
            if (responseBody != null && null != responseBody.getCode() && responseBody.getCode().equals("OK")) {
                // 判断验证码短信是否发送成功，成功则返回生成的验证码
                return true;
            } else {
                log.info("发送短信验证码失败=", responseBody.getMessage());
                return false;
            }
        } catch (Exception e) {
            log.error("发送短信验证码失败=", e);
        } finally {
            if (client != null) {
                client.close();
            }
        }
        return false;
    }
}
