package metabase.db.liquibase;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Base64;

/**
 * @author Jie.Feng
 * @since 2020-05-25
 */
public class DingTalk {
    private static final String DD_ROBOT_HOOK_URL = "http://127.0.0.1:5000/robot/send";
    private static final String TMPL = "{\"text\": \"%s\",\"title\": \"%s\"}";

    public static void send(String subject, String message) {
        String body = new String(Base64.getEncoder().encode(message.getBytes()));
        doPost(DD_ROBOT_HOOK_URL, String.format(TMPL, body, subject));
    }

    public static void sendToDad(String json) {
        String body = new String(Base64.getEncoder().encode(json.getBytes()));
        doPost(DD_ROBOT_HOOK_URL, String.format(TMPL, body, ""));
    }
    

    public static void doPost(String httpUrl, String param) {
        HttpURLConnection connection = null;
        OutputStream os = null;
        InputStream is = null;
        BufferedReader br = null;
        try {
            URL url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(20000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            os = connection.getOutputStream();
            os.write(param.getBytes("utf-8"));
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放数据
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                }
                System.out.println("发送成功:" +  sbf.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                }
            }
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
            connection.disconnect();
        }
    }

}