package com.yutou.nas.utils;

import com.alibaba.fastjson2.JSONObject;
import com.yutou.nas.interfaces.DownloadInterface;

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;

public class HttpTools {
    public static final String serverKey = "zIrsh9TUZP2lfRW753PannG49E7VJvor";
    private static final int HttpRequestIndex = 3;

    public static String get(String url) {
        return https_get(url, false, null);
    }

    public static String https_get(String url, Map<String, String> header) {
        return https_get(url, false, header);
    }

    public static String post(final String url, final byte[] body) {
        return http_post(url, body, 0, null);
    }

    public static File syncDownload(final String url, final String saveName) {
        return new HttpTools().http_syncDownload(url, saveName);
    }

    public static String https_get(String url, boolean isProxy, Map<String, String> header) {
        try {
            URLConnection connection;
            Proxy proxy = null;
            if (isProxy) {
                proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ConfigTools.load(ConfigTools.CONFIG,"proxy.address",String.class),
                        ConfigTools.load(ConfigTools.CONFIG,"proxy.port",Integer.class)));
            }
            if (proxy == null) {
                connection = new URL(url).openConnection();
            } else {
                connection = new URL(url).openConnection(proxy);
            }
            connection.setRequestProperty("User-Agent", getUa());
            if (header != null) {
                for (String key : header.keySet()) {
                    connection.addRequestProperty(key, header.get(key));
                }
            }

            connection.connect();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder str = new StringBuilder();
            String tmp;
            while ((tmp = reader.readLine()) != null) {
                str.append(tmp);
            }
            reader.close();
            return str.toString();
        } catch (Exception e) {
            System.err.println("error url = " + url);
            e.printStackTrace();
        }
        return null;
    }

    public static String http_post(String url, byte[] body, int index, Map<String, String> headers) {
        String tmp;
        StringBuilder str = new StringBuilder();
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("POST");
            if (headers != null) {
                for (String key : headers.keySet()) {
                    connection.addRequestProperty(key, headers.get(key));
                }
            }
            if (body == null) {
                body = "".getBytes();
            }
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.addRequestProperty("User-Agent", getUa());
            connection.setConnectTimeout(5 * 1000);
            connection.setReadTimeout(10 * 1000);
            //connection.addRequestProperty("Connection", "keep-alive");
            //connection.addRequestProperty("User-Agent", getExtUa());
            connection.addRequestProperty("content-type", "application/json");
            connection.addRequestProperty("charset", "UTF-8");
            OutputStream outputStream = connection.getOutputStream();
            //System.out.println(new String(body));
            outputStream.write(body);
            outputStream.flush();
            outputStream.close();
            connection.connect();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            while ((tmp = reader.readLine()) != null) {
                str.append(tmp);
            }
            String finalStr = str.toString();

            connection.disconnect();
            reader.close();
            return finalStr;
        } catch (Exception e) {
            if (index < HttpRequestIndex) {
                return http_post(url, body, index + 1, headers);
            } else {
                e.printStackTrace();
                return null;
            }
        }
    }

    public static String http_post_form(String url, byte[] body, int index, Map<String, String> headers) {
        String tmp;
        StringBuilder str = new StringBuilder();
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("POST");
            if (headers != null) {
                for (String key : headers.keySet()) {
                    connection.addRequestProperty(key, headers.get(key));
                }
            }
            if (body == null) {
                body = "".getBytes();
            }
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.addRequestProperty("User-Agent", getUa());
            connection.setConnectTimeout(5 * 1000);
            connection.setReadTimeout(10 * 1000);
            connection.setRequestProperty("Content-Type", "multipart/form-data;");
            connection.setRequestProperty("charset", "utf-8");
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");

            //connection.addRequestProperty("Connection", "keep-alive");
            //connection.addRequestProperty("User-Agent", getExtUa());
            //connection.addRequestProperty("content-type", "application/json");
            OutputStream outputStream = connection.getOutputStream();
            //System.out.println(new String(body));
            outputStream.write(body);
            outputStream.flush();
            outputStream.close();
            connection.connect();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            while ((tmp = reader.readLine()) != null) {
                str.append(tmp);
            }
            String finalStr = str.toString();

            connection.disconnect();
            reader.close();
            return finalStr;
        } catch (Exception e) {
            if (index < HttpRequestIndex) {
                return http_post(url, body, index + 1, headers);
            } else {
                e.printStackTrace();
                return null;
            }
        }
    }

    public static String getUa() {
        return "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36";
    }

    private static String getKuKuUA() {
        return "/KUKU_APP(Android/#/cn.kuku.sdk/ttsdk17228/29401/A-2.9.4.01.KUSDK/868139039134314/fcddf839c8c135fa/F4:60:E2:AB:25:1A/460019406520644/+8618569400341/#/9/Redmi 6 Pro/xiaomi/1736/76fda4d6-cd6b-485f-987b-8d347b007f24/#/KUKU/Native/92972ea9651fbd2e)";
    }

    public String toUrlParams(JSONObject json) {
        StringBuilder string = new StringBuilder();
        Set<String> keys = json.keySet();
        for (String key : keys) {
            try {
                string.append("&").append(key).append("=").append(URLEncoder.encode(json.getString(key), "UTF-8"));
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    string.append("&").append(URLEncoder.encode(key, "UTF-8")).append("=");
                    //    string += "&" + key + "=";
                } catch (Exception e1) {
                    string.append("&").append(key).append("=");
                }
            }
        }

        string = new StringBuilder(string.substring(1, string.length()).replaceAll(" ", ""));
        return string.toString();
    }

    public static void main(String[] args) {
        JSONObject json = new JSONObject();
        json.put("pid", "102");
        json.put("gid", "100584");
        json.put("message", "0gha58u1c9FjZkeAsEmYIzTvp");
        // json.put("access_token", "659c-S1gV0DwMXdYjPDlSrSLNYOvA8qUoCSvmdFEHvZugKgNX4Z2BCwF18A7W2gRdG7WiWfKsbZgF6YssZHhaozksI9RBn2QQFTXzmAHtbMd4ginEEtwdKmPCM4JbJGg1ollqoNE0PcGENpa4F3e7EdSOa_JFyE6XyUQN1iurJU3F8MZfLlTIcTR9USYoHX15vsAkCht_0mrapZblkeY1_8HFrmK8rlenbZLxccy7PrMz5eZ9uPPDJL5OYiEahyrtLENB8SVmlGofJfQw8wUjN8_XVZSfLMujdwz24");
        String url = "http://127.0.0.1:8002/qq/send.do";
        String data = "data=abc&codd=1";
        data = json.toString();
        http_post(url, data.getBytes(StandardCharsets.UTF_8), 0, null);
      /*  ExecutorService service= Executors.newCachedThreadPool();
        for (int i = 0; i < 3000; i++) {
            service.submit(new Runnable() {
                @Override
                public void run() {
                    get(url);
                }
            });
        }*/
        com.yutou.nas.utils.Log.i(url);
        //String str=get(url);
    }

    private static String donwloadPath = "tmp" + File.separator;

    public synchronized static void download(final String url, final String saveName, final DownloadInterface downloadInterface) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                File jar = null;
                try {
                    File savePath = new File(donwloadPath);
                    if (!savePath.exists()) {
                        savePath.mkdirs();
                    }
                    Log.i("DOWNLOAD", "下载文件:" + url + " 保存文件:" + saveName);
                    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                    connection.addRequestProperty("User-Agent", getUa());
                    //   Log.i(TAG,"获取到网络请求："+connection.getResponseCode());


                    InputStream inputStream = connection.getInputStream();
                    jar = new File(donwloadPath + saveName + "_tmp.tmp");
                    jar.createNewFile();
                    Log.i("DOWNLOAD", "临时保存文件:" + jar.getAbsolutePath());
                    OutputStream outputStream = new FileOutputStream(jar);
                    byte[] bytes = new byte[1024];
                    double size = connection.getContentLength();
                    double downSize = 0;
                    int len;
                    while ((len = inputStream.read(bytes)) > 0) {
                        outputStream.write(bytes, 0, len);
                        downSize += len;
                        if (downloadInterface != null) {
                            downloadInterface.onDownloading(downSize, size);
                        }
                    }
                    outputStream.close();
                    inputStream.close();
                    File oldJar = new File(donwloadPath + saveName);
                    if (oldJar.exists()) {
                        oldJar.delete();
                    }
                    jar.renameTo(oldJar);
                    Log.i("DOWNLOAD", "实际保存：" + oldJar.getAbsolutePath() + " " + oldJar.getName());
                    if (downloadInterface != null) {
                        downloadInterface.onDownload(oldJar);

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    if (jar != null) {
                        jar.delete();
                    }
                    if (downloadInterface != null)
                        downloadInterface.onError(e);
                }
            }
        }).start();
    }

    public synchronized File http_syncDownload(final String url, final String saveName) {
        if (StringUtils.isEmpty(url)) {
            return null;
        }
        File jar = null;
        try {
            File savePath = new File(donwloadPath);
            if (!savePath.exists()) {
                savePath.mkdirs();
            }
            Log.i("DOWNLOAD", "下载文件:" + url + " 保存文件:" + saveName);
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.addRequestProperty("User-Agent", getUa());
            //   Log.i(TAG,"获取到网络请求："+connection.getResponseCode());


            InputStream inputStream = connection.getInputStream();
            jar = new File(donwloadPath + saveName + "_tmp.tmp");
            jar.createNewFile();
            Log.i("DOWNLOAD", "临时保存文件:" + jar.getAbsolutePath());
            OutputStream outputStream = new FileOutputStream(jar);
            byte[] bytes = new byte[1024];
            double size = connection.getContentLength();
            double downSize = 0;
            int len;
            while ((len = inputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, len);
                downSize += len;
            }
            outputStream.close();
            inputStream.close();
            File oldJar = new File(donwloadPath + saveName);
            if (oldJar.exists()) {
                oldJar.delete();
            }
            connection.disconnect();
            jar.renameTo(oldJar);
            Log.i("DOWNLOAD", "实际保存：" + oldJar.getAbsolutePath() + " " + oldJar.getName());
            return oldJar;

        } catch (Exception e) {
            e.printStackTrace();
            if (jar != null) {
                jar.delete();
            }
            return null;
        }
    }
}
