package com.jd.lightapplication.utils;


import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

/**
 *
 * @Title:  SmsUtil.java
 * @Package com.jd.sz.utils
 * @Description:
 * @author: leihy
 * @date:   2021年2月1日 下午2:11:22
 * @version V1.0
 */
public class SmsUtil {

    /**
     * 已HTTP形式请求短信发送接口
     * @param url
     * @param ecName
     * @param apId
     * @param secretKey
     * @param mobiles
     * @param content
     * @param sign
     * @param addSerial
     * @return
     */
    public static String sendHttpSms(String url, String ecName, String apId, String secretKey, String mobiles, String content,
                                     String sign, String addSerial) {
        // 判断参数
        if (StrUtil.isEmpty(url)) {
            return null;
        }
        if (StrUtil.isEmpty(ecName)) {
            return null;
        }
        if (StrUtil.isEmpty(apId)) {
            return null;
        }
        if (StrUtil.isEmpty(secretKey)) {
            return null;
        }
        if (StrUtil.isEmpty(mobiles)) {
            return null;
        }
        if (StrUtil.isEmpty(content)) {
            return null;
        }
        if (StrUtil.isEmpty(sign)) {
            return null;
        }
        if (StrUtil.isEmpty(addSerial)) {
            addSerial = "";
        }
        JSONObject json = new JSONObject();
        json.put("ecName", ecName);
        json.put("apId", apId);
        json.put("secretKey", secretKey);
        json.put("mobiles", mobiles);
        json.put("content", content);
        json.put("sign", sign);
        json.put("addSerial", addSerial);

        try {
            String mac = SmsUtil.getMac(ecName, apId, secretKey, mobiles, content, sign, addSerial);
            json.put("mac", mac);

            String param = JSONUtil.toJsonStr(json);
            System.err.println(param);

            String encode = Base64.getEncoder().encodeToString(param.getBytes("UTF-8"));

            // 使用hutool5.0.6以上，旧版本有问题
//		String post = HttpRequest.post(url).body(encode).execute().body();
            //hutool低版本重写http请求
            String post = HttpRequest(url,encode);
            System.err.println(post);
            JSONObject resultMap = JSONUtil.parseObj(post);
            Boolean success =resultMap.getBool("success",false);
            if(success) {
                return "";
            }
            return resultMap.get("rspcod").toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    public static String HttpRequest(String http, String base64Str) {
        StringBuffer sb = new StringBuffer("");
        HttpURLConnection connection = null;
        DataOutputStream out = null;
        BufferedReader reader = null;
        try {
            URL url = new URL(http);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.connect();
            // POST请求
            out = new DataOutputStream(connection.getOutputStream());

            out.writeUTF(base64Str);
            out.flush();
            // 返回
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sb.append(lines);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(connection != null) {
                connection.disconnect();
            }
        }
        return sb.toString();
    }

    /**
     * 获取加密字符串
     * @param mobile
     * @param content
     * @return
     */
    private static String getMac(String ecName, String apId, String secretKey, String mobile, String content, String sign, String addSerial) {
        if (StrUtil.isEmpty(mobile) || StrUtil.isEmpty(content)) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        sb.append(ecName).append(apId).append(secretKey).append(mobile).append(content).append(sign).append(addSerial);
        // 生成MD5
        String md5 = SecureUtil.md5(sb.toString()).toLowerCase();
        return md5;
    }


}
