package com.ruoyi.sendSMS.controller;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


// If the JDK version is earlier than 1.8, use the third-party library to provide the Base64 class.
public class SendSms {
    /**
     * 设置不验证主机
     */
    private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    public static void main(String[] args) throws Exception {
        sendMessage("17612476018", "1231231321", "数字梨树");
    }

    public static Map<String, Object> buildRequestBody(String msisdn, String smsTemplateId,
                                                       Map<String, String> paramValues, String accout, String passward, String SMSsignature) {
        if (null == msisdn || null == smsTemplateId || null == accout || null == passward) {
            System.out.println(
                    "buildRequestBody(): mobiles, templateId or templateParas or account or password is null.");
            return null;
        }

        Map<String, Object> map = new HashMap<String, Object>();
        List<MtSmsMessage> requestLists = new ArrayList<MtSmsMessage>();
        MtSmsMessage mtSmsMessage = new MtSmsMessage();
        List<String> mobiles = new ArrayList<String>();
        mobiles.add(msisdn);
        mtSmsMessage.setMobiles(mobiles);
        mtSmsMessage.setTemplateId(smsTemplateId);
        mtSmsMessage.setTemplateParas(paramValues);
        mtSmsMessage.setSignature("【"+SMSsignature+"】");
        requestLists.add(mtSmsMessage);
        map.put("account", accout);
        map.put("password", passward);
        map.put("requestLists", requestLists);
        return map;
    }

    public static class MtSmsMessage {
        List<String> mobiles;
        String templateId;
        Map<String, String> templateParas;
        String signature;
        String messageId;
        String extCode;
        List<NamedPatameter> extendInfos;

        public List<String> getMobiles() {
            return mobiles;
        }

        public void setMobiles(List<String> mobiles) {
            this.mobiles = mobiles;
        }

        public String getTemplateId() {
            return templateId;
        }

        public void setTemplateId(String templateId) {
            this.templateId = templateId;
        }

        public Map<String, String> getTemplateParas() {
            return templateParas;
        }

        public void setTemplateParas(Map<String, String> templateParas) {
            this.templateParas = templateParas;
        }

        public String getSignature() {
            return signature;
        }

        public void setSignature(String signature) {
            this.signature = signature;
        }

        public String getMessageId() {
            return messageId;
        }

        public void setMessageId(String messageId) {
            this.messageId = messageId;
        }

        public String getExtCode() {
            return extCode;
        }

        public void setExtCode(String extCode) {
            this.extCode = extCode;
        }

        public List<NamedPatameter> getExtendInfos() {
            return extendInfos;
        }

        public void setExtendInfos(List<NamedPatameter> extendInfos) {
            this.extendInfos = extendInfos;
        }
    }

    public class NamedPatameter {
        String key;
        String value;

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }

    static void trustAllHttpsCertificates() throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        return;
                    }


                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        return;
                    }


                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                }
        };
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    public static String sendMessage(String phone, String message, String SMSsignature) {

        String url = "https://139.9.32.119:18312/common/sms/sendTemplateMessage";

        //【数字梨树】
//        String smsTemplateId = "SMS_21010400002";
        //【四平市林业局】
        String smsTemplateId = "SMS_21030400002";
        Map<String, String> templateParas = new HashMap<String, String>();
        templateParas.put("dxnr", message);
        String accout = "760395"; //实际账号
        String passward = "Mds*e&sd2D"; //实际密码
        // If the request body does not contain the signature name, set signature to null.
        Map<String, Object> body = buildRequestBody(phone, smsTemplateId, templateParas, accout, passward,SMSsignature);
        if (null == body || body.isEmpty()) {
            System.out.println("body is null.");
            return "body is null";
        }
        HttpsURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        try {
            trustAllHttpsCertificates();
            URL realUrl = new URL(url);
            connection = (HttpsURLConnection) realUrl.openConnection();
            connection.setHostnameVerifier(DO_NOT_VERIFY);
            connection.setDoInput(true); // 设置可输入
            connection.setDoOutput(true); // 设置该连接是可以输出的
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            // connection.connect();
            ObjectMapper objectMapper = new ObjectMapper();
            PrintWriter pw = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
            pw.write(objectMapper.writeValueAsString(body));
            pw.flush();
            pw.close();

            br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            int status = connection.getResponseCode();
            if (200 == status) { // 200
                is = connection.getInputStream();
            } else { // 400/401
                is = connection.getErrorStream();
            }
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line = null;
            StringBuilder result = new StringBuilder();
            while ((line = br.readLine()) != null) { // 读取数据
                result.append(line + "\n");
            }
            connection.disconnect();
            System.out.println(result.toString());
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
                if (null != br) {
                    br.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
