package org.springblade.app.util;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 * 阿里云短信发送
 * Created on 17/6/7.
 * 短信API产品的DEMO程序,工程中包含了一个SmsDemo类，直接通过
 * 执行main函数即可体验短信产品API功能(只需要将AK替换成开通了云通信-短信产品功能的AK即可)
 * 工程依赖了2个jar包(存放在工程的libs目录下)
 * 1:aliyun-java-sdk-core.jar
 * 2:aliyun-java-sdk-dysmsapi.jar
 *
 */
public class SendSms {



    //无需修改,用于格式化鉴权头域,给"X-WSSE"参数赋值
    private static final String WSSE_HEADER_FORMAT = "UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"";
    //无需修改,用于格式化鉴权头域,给"Authorization"参数赋值
    private static final String AUTH_HEADER_VALUE = "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\"";

    //APP接入地址+接口访问URI
    private	static final String URL = "https://rtcsms.cn-north-1.myhuaweicloud.com:10743/sms/batchSendSms/v1";

    //APP_Key
    private static final String APPKEY="2KOvL5SD35814lKm40JTa703mpgU";

    //APP_Secret
    private static final String APPSECKET="0i892VhpPX3Ip4vT7zF55R59w8Hi";

    //国内短信签名通道号或国际/港澳台短信通道号
    private static final String SENDER="8820122914677";

    //模板ID
    private static final String TEMPLATEID="ff45bca40a29496b800e2d5ac8223701";


    //签名
    private static final String SIGNATURE="新邻园区";

    public static SendSmsResponse sendSms(String tel,String code){
        try{

            String templateParas = "[\""+code+"\"]"; //模板变量，此处以单变量验证码短信为例，请客户自行生成6位验证码，并定义为字符串类型，以杜绝首位0丢失的问题（例如：002569变成了2569）。

            //请求Body,不携带签名名称时,signature请填null
            String body = buildRequestBody(SENDER, tel, TEMPLATEID, templateParas,"", SIGNATURE);
            if (null == body || body.isEmpty()) {
                System.out.println("body is null.");
                SendSmsResponse sendSmsResponse = new SendSmsResponse();
                sendSmsResponse.setCode("FAIL");
                sendSmsResponse.setMessage("获取验证码失败");
                return sendSmsResponse;
            }

            //请求Headers中的X-WSSE参数值
            String wsseHeader = buildWsseHeader(APPKEY, APPSECKET);
            if (null == wsseHeader || wsseHeader.isEmpty()) {
                System.out.println("wsse header is null.");
                SendSmsResponse sendSmsResponse = new SendSmsResponse();
                sendSmsResponse.setCode("FAIL");
                sendSmsResponse.setMessage("获取验证码失败");
                return sendSmsResponse;
            }

            CloseableHttpClient client = HttpClients.custom()
                    .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null,
                            (x509CertChain, authType) -> true).build())
                    .setSSLHostnameVerifier(new DefaultHostnameVerifier())
                    .build();

            HttpResponse response = client.execute(RequestBuilder.create("POST")//请求方法POST
                    .setUri(URL)
                    .addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
                    .addHeader(HttpHeaders.AUTHORIZATION, AUTH_HEADER_VALUE)
                    .addHeader("X-WSSE", wsseHeader)
                    .setEntity(new StringEntity(body)).build());


            System.out.println(response.toString()); //打印响应头域信息
            String resultEntity = EntityUtils.toString(response.getEntity());
            System.out.println(resultEntity); //打印响应消息实体
            JSONObject jsonObject = new JSONObject(resultEntity);
            if(jsonObject.get("code")!=null){
                String resultCode = jsonObject.get("code").toString();
                if(resultCode.equals("000000")){

                    SendSmsResponse sendSmsResponse = new SendSmsResponse();
                    sendSmsResponse.setCode("OK");
                    sendSmsResponse.setMessage("获取验证码成功");
                    return sendSmsResponse;
                }
            }

        }catch (Exception e){
            SendSmsResponse sendSmsResponse = new SendSmsResponse();
            sendSmsResponse.setCode("FAIL");
            sendSmsResponse.setMessage("获取验证码失败");
            return sendSmsResponse;
        }

        SendSmsResponse sendSmsResponse = new SendSmsResponse();
        sendSmsResponse.setCode("FAIL");
        sendSmsResponse.setMessage("获取验证码失败");
        return sendSmsResponse;
    }

    /**
     * 构造请求Body体
     * @param sender
     * @param phone
     * @param templateId
     * @param templateParas
     * @param statusCallbackUrl
     * @param signature | 签名名称,使用国内短信通用模板时填写
     * @return
     */
    static String buildRequestBody(String sender, String phone, String templateId, String templateParas,
                                   String statusCallbackUrl, String signature) {
        if (null == sender || null == phone || null == templateId || sender.isEmpty() || phone.isEmpty()
                || templateId.isEmpty()) {
            System.out.println("buildRequestBody(): sender, receiver or templateId is null.");
            return null;
        }
        List<NameValuePair> keyValues = new ArrayList<NameValuePair>();

        keyValues.add(new BasicNameValuePair("from", sender));
        keyValues.add(new BasicNameValuePair("to", phone));
        keyValues.add(new BasicNameValuePair("templateId", templateId));
        if (null != templateParas && !templateParas.isEmpty()) {
            keyValues.add(new BasicNameValuePair("templateParas", templateParas));
        }
        if (null != statusCallbackUrl && !statusCallbackUrl.isEmpty()) {
            keyValues.add(new BasicNameValuePair("statusCallback", statusCallbackUrl));
        }
        if (null != signature && !signature.isEmpty()) {
            keyValues.add(new BasicNameValuePair("signature", signature));
        }

        return URLEncodedUtils.format(keyValues, Charset.forName("UTF-8"));
    }

    /**
     * 构造X-WSSE参数值
     * @param appKey
     * @param appSecret
     * @return
     */
    static String buildWsseHeader(String appKey, String appSecret) {
        if (null == appKey || null == appSecret || appKey.isEmpty() || appSecret.isEmpty()) {
            System.out.println("buildWsseHeader(): appKey or appSecret is null.");
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        String time = sdf.format(new Date()); //Created
        String nonce = UUID.randomUUID().toString().replace("-", ""); //Nonce

        byte[] passwordDigest = DigestUtils.sha256(nonce + time + appSecret);
        String hexDigest = Hex.encodeHexString(passwordDigest);

        //如果JDK版本是1.8,请加载原生Base64类,并使用如下代码
        String passwordDigestBase64Str = Base64.getEncoder().encodeToString(hexDigest.getBytes()); //PasswordDigest
        //如果JDK版本低于1.8,请加载三方库提供Base64类,并使用如下代码
        //String passwordDigestBase64Str = Base64.encodeBase64String(hexDigest.getBytes(Charset.forName("utf-8"))); //PasswordDigest
        //若passwordDigestBase64Str中包含换行符,请执行如下代码进行修正

        return String.format(WSSE_HEADER_FORMAT, appKey, passwordDigestBase64Str, nonce, time);
    }

//    /**
//     * 产品名称:云通信短信API产品,开发者无需替换
//     */
//    static final String product = "Dysmsapi";
//    /**
//     * 产品域名,开发者无需替换
//     */
//    static final String domain = "dysmsapi.aliyuncs.com";
//
//
//   // static final String accessKeyId = "LTAIhMrUkmeVbPt3";
//   // static final String accessKeySecret = "2Xi5j0K2SSfy2aFjhIegrkdVfLJQjo";
//    static final String accessKeyId = "LTAImJx3npeozjx1";
//    static final String accessKeySecret = "o2O26v9BYVscN1v50FQKNfK4HlMHRm";
//    /**
//     * 功能描述:发送短信
//     * @param  tel 手机号码
//     * @return code 短信
//     *
//     *
//     */
//
//
//        //可自助调整超时时间
//        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
//        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//
//        //初始化acsClient,暂不支持region化
//        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(tel);
//        //必填:短信签名-可在短信控制台中找到--签名
//        request.setSignName("智慧园区");
//        //必填:短信模板-可在短信控制台中找到
//        //request.setTemplateCode("SMS_150760014");
//        request.setTemplateCode("SMS_129755420"); //注册验证码
//        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
//        request.setTemplateParam("{\"code\":\""+code+"\"}");
//        //hint 此处可能会抛出异常，注意catch
//        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
//
//        return sendSmsResponse;
//    }


}
