package com.ruoyi.sms.utils;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @Author: micro cloud fly
 * @Description: 短信API的调用示例
 * @Date: Created in 1:45 下午 2020/10/9
 */
public class SmsCodeUtils {
    //可选模板列表
    public static final String URL_ALPHA = "http://v.juhe.cn/vercodesms/optionTpl.php?key=%s";

    //提交短信模板
    public static final String URL_BETA = "http://v.juhe.cn/vercodesms/submitTpl.php?key=%s&signature=%s&tplcode=%d";

    //我的模板列表
    public static final String URL_GAMMA = "http://v.juhe.cn/vercodesms/myTpl.php?key=%s";

    //发送短信
    public static final String URL_DELTA = "http://v.juhe.cn/vercodesms/send.php?key=%s&tplId=%d&tplValue=%s&mobile=%s";


    //申请接口的请求key
    // TODO: 您需要改为自己的请求key
    public static final String KEY = "0901df7db9a4f49f42e7aecd4640d5ff";


    public static final int tplId = 67225;


    private static void main(String[] args) throws UnsupportedEncodingException {
        //可选模版列表
        printA();
//        System.out.println("-------------------------------------分割线-------------------------------------");
        //提交短信模板
//        String signature = "金陵艺术";
//        short tplcode = 1002;
//        printB(signature,tplcode);
        System.out.println("-------------------------------------分割线-------------------------------------");
//        我的模板
//        printC();
        System.out.println("-------------------------------------分割线-------------------------------------");
        //发送短信
        String tplValue = "#code#=12345";
        String mobile = "18256057064";
        printD(tplValue, mobile);
    }

    /**
     * 可选模版列表
     */
    public static void printA() {
        //发送http请求的url
        String url = String.format(URL_ALPHA, KEY);
        final String response = doGet(url);
        System.out.println("接口返回：" + response);
        try {
            JSONObject jsonObject = JSONObject.fromObject(response);
            int error_code = jsonObject.getInt("error_code");
            if (error_code == 0) {
                System.out.println("调用接口成功");
                JSONArray result = jsonObject.getJSONArray("result");
                result.stream().map(JSONObject::fromObject).forEach(hour -> {
                    System.out.println("可供选择的模板id：" + ((JSONObject) hour).getString("tplcode"));
                    System.out.println("模板内容示例：" + ((JSONObject) hour).getString("sms_tpl"));
                    System.out.println("模板规范说明：" + ((JSONObject) hour).getString("des"));
                });

            } else {
                System.out.println("调用接口失败：" + jsonObject.getString("reason"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 提交短信模板
     */
    public static void printB(String signature, short tplcode) {
        //发送http请求的url
        String url = String.format(URL_BETA, KEY, signature, tplcode);
        final String response = doGet(url);
        System.out.println("接口返回：" + response);
        try {
            JSONObject jsonObject = JSONObject.fromObject(response);
            int error_code = jsonObject.getInt("error_code");
            if (error_code == 0) {
                System.out.println("调用接口成功");
                JSONObject result = jsonObject.getJSONObject("result");
                System.out.println("模板id：" + result.getInt("tplId"));
            } else {
                System.out.println("调用接口失败：" + jsonObject.getString("reason"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 我的模板列表
     */
    public static void printC() {
        //发送http请求的url
        String url = String.format(URL_GAMMA, KEY);
        final String response = doGet(url);
        System.out.println("接口返回：" + response);
        try {
            JSONObject jsonObject = JSONObject.fromObject(response);
            int error_code = jsonObject.getInt("error_code");
            if (error_code == 0) {
                System.out.println("调用接口成功");
                JSONArray result = jsonObject.getJSONArray("result");

                result.stream().map(JSONObject::fromObject).forEach(hour -> {
                    System.out.println("模板ID：" + ((JSONObject) hour).getString("tplId"));
                    System.out.println("模板签名：" + ((JSONObject) hour).getString("signature"));
                    System.out.println("模板发送内容：" + ((JSONObject) hour).getString("sms_tpl"));
                    System.out.println("模板规审核状态范说明：" + ((JSONObject) hour).getString("tpl_state"));
                    System.out.println("是否有效：" + ((JSONObject) hour).getString("status"));
                    System.out.println("模板规范说明：" + ((JSONObject) hour).getString("des"));
                });

            } else {
                System.out.println("调用接口失败：" + jsonObject.getString("reason"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static String printD(String tplValue, String mobile) throws UnsupportedEncodingException {
        //发送http请求的url
        String url = String.format(URL_DELTA, KEY, tplId, URLEncoder.encode(tplValue, "UTF-8"), mobile);
        final String response = doGet(url);
        System.out.println("接口返回：" + response);
        try {
            JSONObject jsonObject = JSONObject.fromObject(response);
            int error_code = jsonObject.getInt("error_code");
            if (error_code == 0) {
                System.out.println("调用接口成功");
                JSONObject result = jsonObject.getJSONObject("result");
                System.out.println("短信唯一标识：" + result.getString("sid"));

            } else {
                System.out.println("调用接口失败：" + jsonObject.getString("reason"));
                return com.alibaba.fastjson.JSONObject.toJSONString(jsonObject);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }

    /**
     * get方式的http请求
     *
     * @param httpUrl 请求地址
     * @return 返回结果
     */
    public static String doGet(String httpUrl) {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        String result = null;// 返回结果字符串
        try {
            // 创建远程url连接对象
            URL url = new URL(httpUrl);
            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式：get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(60000);
            // 发送请求
            connection.connect();
            // 通过connection连接，获取输入流
            if (connection.getResponseCode() == 200) {
                inputStream = connection.getInputStream();
                // 封装输入流，并指定字符集
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                // 存放数据
                StringBuilder sbf = new StringBuilder();
                String temp;
                while ((temp = bufferedReader.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append(System.getProperty("line.separator"));
                }
                result = sbf.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != bufferedReader) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();// 关闭远程连接
            }
        }
        return result;
    }


    /**
     * post方式的http请求
     *
     * @param httpUrl 请求地址
     * @param param   请求参数
     * @return 返回结果
     */
    public static String doPost(String httpUrl, String param) {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        BufferedReader bufferedReader = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接请求方式
            connection.setRequestMethod("POST");
            // 设置连接主机服务器超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取主机服务器返回数据超时时间：60000毫秒
            connection.setReadTimeout(60000);
            // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
            connection.setDoOutput(true);
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 通过连接对象获取一个输出流
            outputStream = connection.getOutputStream();
            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
            outputStream.write(param.getBytes());
            // 通过连接对象获取一个输入流，向远程读取
            if (connection.getResponseCode() == 200) {
                inputStream = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                StringBuilder sbf = new StringBuilder();
                String temp;
                // 循环遍历一行一行读取数据
                while ((temp = bufferedReader.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append(System.getProperty("line.separator"));
                }
                result = sbf.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != bufferedReader) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != outputStream) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
        return result;
    }
}
