package com.nantian.sc.cloud.admin.utils;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class PhoneCodeUtil {

    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";

    // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
    static final String accessKeyId = "LTAI5tPH5KfH9mwGK4zR8FeE";//yourAccessKeyId
    static final String accessKeySecret = "apyRbrdyEXCkEmP7Irj3peitsWCtNR";//yourAccessKeySecret

    //模板ID 可去阿里云自行申请短信模板会生成自定义模板ID
//    static final String template_code = "SMS_250795102"; //真实ID
    static final String template_code = "SMS_154950909"; //测试ID

    // 必填:短信签名-可在短信控制台中找到
    final static String SignName = "阿里云短信测试";// 阿里云配置你自己的短信签名填入

    // 设置超时时间-可自行调整
    final static String defaultConnectTimeout  = "sun.net.client.defaultConnectTimeout";
    final static String defaultReadTimeout = "sun.net.client.defaultReadTimeout";
    final static String Timeout = "10000";

    public SendSmsResponse sendVerificationCode(String phone, String code) throws ClientException {

        SendSmsResponse sendSmsResponse = null;

        System.setProperty(defaultConnectTimeout, "10000");
        System.setProperty(defaultReadTimeout, "10000");

        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(phone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(SignName);
        //可选:模板中的变量替换JSON串,如模板内容为尊敬的${name},请您尽快处理！
        Map<String, String> map = new HashMap<>();
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(template_code);
        map.put("code", code);
        request.setTemplateParam(JSON.toJSONString(map));
        //hint 此处可能会抛出异常，注意catch
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
            log.info("==========短信发送====返回码==>" + sendSmsResponse.getCode() + "返回信息==>" + sendSmsResponse.getMessage());
        } catch (ClientException e) {
            e.printStackTrace();
            log.info("============>短信发送失败" + e.getMessage());
        } finally {
            return sendSmsResponse;
        }
    }
}
