package org.jeecg.modules.system.util;

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

import org.springframework.beans.factory.annotation.Value;

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.extern.slf4j.Slf4j;

@Slf4j
public class SendSmsUtil {

	@Value(value = "${aliyun.accessKey}")
	private static String ALIBABA_CLOUD_ACCESS_KEY_ID;
	@Value(value = "${aliyun.accessKeySecret}")
	private static String ALIBABA_CLOUD_ACCESS_KEY_SECRET;

	private static AsyncClient client;

	static {
		StaticCredentialProvider provider = StaticCredentialProvider
				.create(Credential.builder().accessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
						.accessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")).build());
		client = AsyncClient.builder().region("cn-hangzhou").credentialsProvider(provider).overrideConfiguration(
				ClientOverrideConfiguration.create().setEndpointOverride("dysmsapi.aliyuncs.com")).build();
	}

	/**
	 * 发送短信
	 * @param signName 
	 * @param phone
	 * @param templateCode
	 * @param templateParam
	 */
	public String sendSms(String signName, String phone, String templateCode, String templateParam) {
		SendSmsRequest sendSmsRequest = SendSmsRequest.builder().signName(signName).templateCode(templateCode)
				.phoneNumbers(phone).templateParam(templateParam).build();
		CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
		SendSmsResponse resp;
		try {
			resp = response.get();
			log.info(phone+"--------短信发送结果----------->"+new Gson().toJson(resp));
			return new Gson().toJson(resp);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			client.close();
		}
		return null;
	}

}
