package com.zhgd.jeecg.common.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
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.NoopHostnameVerifier;
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.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

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

//如果JDK版本低于1.8,请使用三方库提供Base64类
//如果JDK版本是1.8,可使用原生Base64类

/**
 * 华为云短信接口工具类
 *
 * @author xw
 * @version 2019-08-01
 */
@Slf4j
@Component
public class HuaWeiMessageUtils {

    public static String appKey;
    public static String appSecret;
    public static String url = "https://api.rtc.huaweicloud.com:10443/sms/batchSendSms/v1";
    public static String sender;//国内短信签名通道号或国际/港澳台短信通道号
    public static String noticeSender;//通知签名通道号

    //接口地址
    //private static final String URL = "https://api.rtc.huaweicloud.com:10443/sms/batchSendSms/v1"; //APP接入地址+接口访问URI
    //无需修改,用于格式化鉴权头域,给"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\"";

    @Value("${sms.hw.appKey}")
    public void setAppKey(String hwappKey) {
        appKey = hwappKey;
    }

    @Value("${sms.hw.appSecret}")
    public void setAppSecret(String hwappSecret) {
        appSecret = hwappSecret;
    }

    @Value("${sms.hw.verify.signchannel}")
    public void setSender(String hwsender) {
        sender = hwsender;
    }

    @Value("${sms.hw.notice.signchannel}")
    public void setNoticeSender(String hwnoticeSender) {
        noticeSender = hwnoticeSender;
    }

    public static void sendNoticeSms(String templateId, String signature, String receiver, String templateParass) {
        try {
            HuaWeiMessageUtils.sendNoticeMessage(templateId, signature, receiver, templateParass);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送短信验证码
     *
     * @param templateId
     * @param signature
     * @param receiver
     * @param templateParass
     * @return
     * @throws Exception
     */
    public static Boolean sendMessage(String templateId, String signature, String receiver, String templateParass) throws Exception {
        return sendSms(templateId, signature, receiver, templateParass, sender);
    }

    public static Boolean sendNoticeMessage(String templateId, String signature, String receiver, String templateParass) throws Exception {
        return sendSms(templateId, signature, receiver, templateParass, noticeSender);
    }

    /**
     * 发送短信
     * 您的验证码为：${NUM_8} (30分钟有效).为保证账户安全，请勿向任何人提供此验证码。
     *
     * @param
     * @param templateId     模板ID
     * @param signature      签名名称
     * @param receiver       短信接收人号码，多个号码用逗号隔开号码格式用+86开头(+8618229254507,+8613575286706,+8615935721136)
     * @param templateParass 模板变量，多个变量中间用逗号(,)隔开
     * @throws Exception
     */
    public static Boolean sendSms(String templateId, String signature, String receiver, String templateParass, String tempsender) throws Exception {

        //选填,短信状态报告接收地址,推荐使用域名,为空或者不填表示不接收状态报告
        String statusCallBack = "";

        /**
         * 选填,使用无变量模板时请赋空值 String templateParas = "";
         * 单变量模板示例:模板内容为"您的验证码是${NUM_6}"时,templateParas可填写为"[\"369751\"]"
         * 双变量模板示例:模板内容为"您有${NUM_2}件快递请到${TXT_32}领取"时,templateParas可填写为"[\"3\",\"人民公园正门\"]"
         * 查看更多模板格式规范:常见问题>业务规则>短信模板内容审核标准
         */
        String[] strs = templateParass.split(",");
        StringBuffer sb = new StringBuffer("[");
        for (String s : strs) {
            if (s.length() > 0) {
                sb.append("\"" + s + "\",");
            }
        }
        String templateParas = sb.substring(0, sb.length() - 1) + "]";//模板变量
//            String templateParas = "[\"369751\"]"; //模板变量

        //请求Body,不携带签名名称时,signature请填null
        String body = buildRequestBody(tempsender, receiver, templateId, templateParas, statusCallBack, signature);
        if (null == body || body.isEmpty()) {
            log.info("body is null.");
            return false;
        }

        //请求Headers中的X-WSSE参数值
        String wsseHeader = buildWsseHeader(appKey, appSecret);
        if (null == wsseHeader || wsseHeader.isEmpty()) {
            log.info("wsse header is null.");
            return false;
        }

        //如果JDK版本低于1.8,可使用如下代码
        //为防止因HTTPS证书认证失败造成API调用失败,需要先忽略证书信任问题
        //CloseableHttpClient client = HttpClients.custom()
        //        .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        //            @Override
        //            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        //                return true;
        //            }
        //        }).build()).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();

        //如果JDK版本是1.8,可使用如下代码
        //为防止因HTTPS证书认证失败造成API调用失败,需要先忽略证书信任问题
        CloseableHttpClient client = HttpClients.custom()
                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null,
                        (x509CertChain, authType) -> true).build())
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .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());

        log.info(response.toString()); //打印响应头域信息
        HttpEntity he = response.getEntity();
        String resultStr = EntityUtils.toString(he, "UTF-8");
        log.info(resultStr);//打印响应消息实体
        if (resultStr != null && resultStr != "") {
            JSONObject resultJson = JSONObject.parseObject(resultStr);
            if (resultJson != null && "000000".equals(resultJson.getString("code"))) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 构造请求Body体
     *
     * @param sender
     * @param receiver
     * @param templateId
     * @param templateParas
     * @param statusCallbackUrl
     * @param signature         | 签名名称,使用国内短信通用模板时填写
     * @return
     */
    static String buildRequestBody(String sender, String receiver, String templateId, String templateParas,
                                   String statusCallbackUrl, String signature) {
        if (null == sender || null == receiver || null == templateId || sender.isEmpty() || receiver.isEmpty()
                || templateId.isEmpty()) {
            log.info("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", receiver));
        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()) {
            log.info("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中包含换行符,请执行如下代码进行修正
        //passwordDigestBase64Str = passwordDigestBase64Str.replaceAll("[\\s*\t\n\r]", "");

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

    public static void main(String[] args) {

        //String templateId = "a2b78440de8d49f0ba5f384aaab26ac7";
        String templateId = "02e8854e38fe499fb5b228b40e11885e";
        String signature = "华为云短信测试";
        String receiver = "+8613083970498";
        String templateParass = "2020-07,老华东分公司项目,26";
        String tempsender = "8820050914426";
        try {
            sendNoticeMessage(templateId, signature, receiver, templateParass);

//            log.info(random);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
