package com.imdroid.beidou.service;

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.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.Data;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class SmsService {
    static final String signName = "英卓科技";
    static final String templateCode = "SMS_465145810";
    static final String ACCESS_KEY = "LTAI5tGyoSky5ZG14qYTv2Fv";
    static final String ACCESS_KEY_SECRET ="jzfEqr9WV7ltSjO7BXV0WxozyFrvZu";

    @Data
    static class TemplateData{
        String time;
        String name;
        String content;
    }
    static public void send(String deviceIds, String content, String msgTime,
                            List<String> phoneList) throws ExecutionException, InterruptedException {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(ACCESS_KEY)
                .accessKeySecret(ACCESS_KEY_SECRET)
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-beijing") // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();

        // Parameter settings for API request
        TemplateData smsData = new TemplateData();
        smsData.setTime(msgTime);
        smsData.setName(deviceIds);
        smsData.setContent(content);
        for(String phoneNum : phoneList) {
            SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                    .phoneNumbers(phoneNum)
                    .signName(signName)
                    .templateCode(templateCode)
                    .templateParam(new Gson().toJson(smsData))
                    .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();
            System.out.println(new Gson().toJson(resp));
        }

        // Finally, close the client
        client.close();
    }
}
