/**
 * 
 */
package org.springblade.message.sms;

import java.util.Map;
import java.util.stream.Stream;

import org.springblade.message.model.MsgResponse;
import org.springblade.message.model.SmsInfo;
import org.springblade.message.model.SmsMsgRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.DescribeSmsTemplateListRequest;
import com.tencentcloudapi.sms.v20210111.models.DescribeSmsTemplateListResponse;
import com.tencentcloudapi.sms.v20210111.models.DescribeTemplateListStatus;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20210111.models.SendStatus;

import lombok.extern.slf4j.Slf4j;

/**
 * @author wookvn
 *
 */
@Slf4j
@Component
public class TencentSmsTemplate extends SmsMsgTemplate {
	
	/**
	 * https://cloud.tencent.com/document/product/382/55981
	 */
	@Override
	public MsgResponse sendMessage(SmsMsgRequest smsMsgRequest) {
		try {
			SmsInfo smsInfo = smsMsgRequest.getSmsInfo();
			String[] params = smsMsgRequest.getParams().entrySet().stream().sorted(Map.Entry.comparingByKey()).map(Map.Entry::getValue).toArray(String[]::new);

			Credential cred = new Credential(smsInfo.getAccessKey(), smsInfo.getSecretKey());
//			HttpProfile httpProfile = new HttpProfile();
//			/* SDK会自动指定域名。通常是不需要特地指定域名的，但是如果你访问的是金融区的服务
//             * 则必须手动指定域名，例如sms的上海金融区域名： sms.ap-shanghai-fsi.tencentcloudapi.com */
//			httpProfile.setEndpoint("sms.tencentcloudapi.com");
//			ClientProfile clientProfile = new ClientProfile();
//            clientProfile.setHttpProfile(httpProfile);

			SmsClient client = new SmsClient(cred, smsInfo.getRegionId());
			SendSmsRequest req = new SendSmsRequest();
			req.setSignName(smsInfo.getSignName());
			req.setTemplateId(smsInfo.getTemplateId());
			req.setPhoneNumberSet(StringUtils.toStringArray(smsMsgRequest.getPhones()));
			req.setTemplateParamSet(params);
			req.setSmsSdkAppId(smsInfo.getAppId());

			SendSmsResponse res = client.SendSms(req);
			log.info("腾讯云短信发送完成,res=" + SendSmsResponse.toJsonString(res));
			SendStatus[] sendStatusSet = res.getSendStatusSet();
			if (Stream.of(sendStatusSet).anyMatch(item -> "ok".equalsIgnoreCase(item.getCode()))) {
				return MsgResponse.success(200, "发送成功");
			}
			return MsgResponse.failure("发送失败");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return MsgResponse.failure(e.getMessage());
		}
	}

	/**
	 * https://cloud.tencent.com/document/product/382/52067
	 */
	@Override
	public MsgResponse queryTemplateContent(SmsInfo smsInfo) {
		try {
			Credential cred = new Credential(smsInfo.getAccessKey(), smsInfo.getSecretKey());
			// HttpProfile httpProfile = new HttpProfile();
			// /* SDK会自动指定域名。通常是不需要特地指定域名的，但是如果你访问的是金融区的服务
			// * 则必须手动指定域名，例如sms的上海金融区域名： sms.ap-shanghai-fsi.tencentcloudapi.com */
			// httpProfile.setEndpoint("sms.tencentcloudapi.com");
			// ClientProfile clientProfile = new ClientProfile();
			// clientProfile.setHttpProfile(httpProfile);

			SmsClient client = new SmsClient(cred, smsInfo.getRegionId());
			DescribeSmsTemplateListRequest request = new DescribeSmsTemplateListRequest();
			request.setTemplateIdSet(new Long[] { Long.valueOf(smsInfo.getTemplateId()) });
			request.setInternational(0L); // 0：表示国内短信。 1：表示国际/港澳台短信。

			DescribeSmsTemplateListResponse response = client.DescribeSmsTemplateList(request);
			DescribeTemplateListStatus[] describeTemplateStatusSet = response.getDescribeTemplateStatusSet();
			if (describeTemplateStatusSet != null && describeTemplateStatusSet.length == 1) {
				DescribeTemplateListStatus templateStatus = describeTemplateStatusSet[0];
				if (templateStatus.getStatusCode() == 0L) { // 0表示审核通过，1表示审核中，-1表示审核未通过或审核失败
					return MsgResponse.success(200, templateStatus.getTemplateContent());
				} else {
					return MsgResponse.failure(templateStatus.getReviewReply());
				}
			}
			return MsgResponse.failure("未查询到该模版");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return MsgResponse.failure(e.getMessage());
		}
	}
}
