package com.fzm.mall.server.admin.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.util.internal.StringUtil;
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 java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;

public class SmsUtil {

    // 无需修改,用于格式化鉴权头域,给"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\"";

    // 注册模板id
    public static String REGISTER_TEMPLATEID = "89a8aa68d2514042b2ee6c3c66e6efc2";
    // 登录模板id
    public static String LOGIN_TEMPLATEID = "2750ee3d64d24735b41949690575eba8";
    // 修改交易密码
    public static String TRANSACTION_PASSWORD_TEMPLATEID = "674a92e2616544d3a3dc7ea4bc60b6d3";
    // 提币功能的验证码
    public static String WITHDRAW_TEMPLATEID = "0cd4851e49ba4bb9ac98dffdd24ea496";
    // 转币功能的验证码
    public static String TRAN_COIN_TEMPLATEID = "0d5d2b6cd1944b3881644812720ca442";
    // 支付订单功能的验证码
    public static String PAY_ORDER = "60ffab16bbc440208e3e371ddbecbc1d";
    // 提货功能的验证码
    public static String DRAW_GOODS = "f1e0e0f8d1994a05b1dae00e7685a0ce";
    // 确认收货功能的验证码
    public static String CONFIRM_RECEIPT = "3830c80dab274a02968c88dbf7e01662";
    // 商品转卖功能的验证码
    public static String GOODS_MALL = "be22d436fbcb42cea12b17a26f19b69e";
    // 设置登录密码
    public static String SET_PASSWORD = "509954d523f84d2d8ee1baaca76f5bc2";

    // 国际注册模板id
    public static String GJ_REGISTER_TEMPLATEID = "ca91d62296134bd38fca32198f321f1c";
    // 国际登录模板id
    public static String GJ_LOGIN_TEMPLATEID = "0416b132544a4752a73c896ada946473";
    // 国际修改交易密码
    public static String GJ_TRANSACTION_PASSWORD_TEMPLATEID = "057cd2ffda184abfb47a671bdf6be294";
    // 国际提币功能的验证码
    public static String GJ_WITHDRAW_TEMPLATEID = "32dbba351d774b1296e0fa77036513d6";
    // 国际转币功能的验证码
    public static String GJ_TRAN_COIN_TEMPLATEID = "2e9aa36ee85a49e291280e4c0129d7db";
    // 国际支付订单功能的验证码
    public static String GJ_PAY_ORDER = "fd9f8d7c0a584ab2bcd70c2418432313";
    // 国际提货功能的验证码
    public static String GJ_DRAW_GOODS = "2761f3613450492ea5be808fe8ff5bf6";
    // 国际确认收货功能的验证码
    public static String GJ_CONFIRM_RECEIPT = "d9863f29f6764616b7afd88d10409f1e";
    // 国际商品转卖功能的验证码
    public static String GJ_GOODS_MALL = "7b5880efa92342c38b0de97f4423a956";
    // 国际设置登录密码
    public static String GJ_SET_PASSWORD = "d885adb6c7fc48a3880d6fe1baccc6d2";

    // 国内商户申请入驻审核失败
    public static String GN_MERCHANT_REGISTER_CHECK_FAIL = "SMS_224341725";
    // 国内商户申请入驻审核成功
    public static String GN_MERCHANT_REGISTER_CHECK_SUCCESS = "SMS_224351755";
    // 国内注册
    public static String GN_MERCHANT_REGISTER= "SMS_224341716";
    // 国内修改密码
    public static String GN_MERCHANT_repair_pwd = "SMS_224346822";

    // 国内短信签名通道号/国际
    public static String senders[] = {"8820120423076", "isms0000000231"};
    // APP_Key国内/国际
    public static String appKeys[] = {"jQ2ZVpE3Qs187ECPKOb4SrVqI18b", "SiD6A3Uhb2o0Mn73M8Y2PJM4f0Ta"}; // APP_Key
    // APP_Secret国内/国际
    public static String appSecrets[] = {"2X4nT1xA03STY75w62546iKQlCwT", "g3B1WJYGClQ0FNkG1bNyb7259ARs"};

    public static boolean sendSms(String phone, Boolean isChina, String templateId, String code) {
        // 必填,请参考"开发准备"获取如下数据,替换为实际值
        String url = "https://rtcsms.cn-north-1.myhuaweicloud.com:10743/sms/batchSendSms/v1"; // APP接入地址+接口访问URI
        // 条件必填,国内短信关注,当templateId指定的模板类型为通用模板时生效且必填,必须是已审核通过的,与模板类型一致的签名名称
        // 国际/港澳台短信不用关注该参数
        String signature = "量洒信息"; // 签名名称

        // 必填,全局号码格式(包含国家码),示例:+8615123456789,多个号码之间用英文逗号分隔
        String receiver = phone; // 短信接收人号码

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

        String appKey = "";
        String appSecret = "";
        String sender = "";
        if (isChina) {
            appKey = appKeys[0];
            appSecret = appSecrets[0];
            sender = senders[0];
        } else {
            appKey = appKeys[1];
            appSecret = appSecrets[1];
            sender = senders[1];
        }
        /**
         * 选填,使用无变量模板时请赋空值 String templateParas = "";
         * 单变量模板示例:模板内容为"您的验证码是${1}"时,templateParas可填写为"[\"369751\"]"
         * 双变量模板示例:模板内容为"您有${1}件快递请到${2}领取"时,templateParas可填写为"[\"3\",\"人民公园正门\"]"
         * 模板中的每个变量都必须赋值，且取值不能为空 查看更多模板和变量规范:产品介绍>模板和变量规范
         */
        String templateParas = "[" + "'" + code + "'" + "]"; // 模板变量，此处以单变量验证码短信为例，请客户自行生成6位验证码，并定义为字符串类型，以杜绝首位0丢失的问题（例如：002569变成了2569）。

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

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

        // 如果JDK版本低于1.8,可使用如下代码
        // 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(new DefaultHostnameVerifier()).build();

        // 如果JDK版本是1.8,可使用如下代码
        try {
            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 string = EntityUtils.toString(response.getEntity()); // 打印响应消息实体
            JSONObject parseObject = JSON.parseObject(string);
            System.out.println(string);
            String description = parseObject.getString("description");

            if (!StringUtil.isNullOrEmpty(description) && description.equals("Success")) {
                return true;
            }
            return false;
        } catch (Exception e) {
            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()) {
            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", 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()) {
            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中包含换行符,请执行如下代码进行修正
        // passwordDigestBase64Str = passwordDigestBase64Str.replaceAll("[\\s*\t\n\r]",
        // "");

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

    public static void main(String[] args) {
        boolean sms_224351755 = sendSms("18851896308", true, "SMS_224351755", "");
        System.err.println(sms_224351755);
    }

}