package easydo.technology.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.MessageFormat;

public class HttpUtil {

    /***
     * 向指定URL发送POST方法的请求
     *
     * @param apiUrl
     * @param data
     * @return
     */
    public static JSONObject sendPOST(String apiUrl, String data) {
        StringBuffer strBuffer = null;
        JSONObject obj = null;
        try {
            // 建立连接
            URL url = new URL(apiUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 需要输出
            httpURLConnection.setDoOutput(true);
            // 需要输入
            httpURLConnection.setDoInput(true);
            // 不允许缓存
            httpURLConnection.setUseCaches(false);

            httpURLConnection.setRequestMethod("POST");
            // 设置Headers
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            // 连接会话
            httpURLConnection.connect();
            // 建立输入流，向指向的URL传入参数
            DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
            // 设置请求参数
            dos.write(data.getBytes("UTF-8"));
            dos.flush();
            dos.close();
            // 获得响应状态
            int http_StatusCode = httpURLConnection.getResponseCode();
            String http_ResponseMessage = httpURLConnection.getResponseMessage();
            obj = new JSONObject();
            if (HttpURLConnection.HTTP_OK == http_StatusCode) {
                strBuffer = new StringBuffer();
                String readLine = new String();
                BufferedReader responseReader = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    strBuffer.append(readLine);
                }
                responseReader.close();
                obj = JSONObject.parseObject(strBuffer.toString());
            } else {
                throw new RuntimeException(
                        MessageFormat.format("POST请求失败,失败原因: Http状态码 = {0} , {1}", http_StatusCode, http_ResponseMessage));
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static JSONObject sendPOST(String apiUrl) {
        StringBuffer strBuffer = null;
        JSONObject obj = null;
        try {
            // 建立连接
            URL url = new URL(apiUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 需要输出
            httpURLConnection.setDoOutput(true);
            // 需要输入
            httpURLConnection.setDoInput(true);
            // 不允许缓存
            httpURLConnection.setUseCaches(false);

            httpURLConnection.setRequestMethod("POST");
            // 设置Headers
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 连接会话
            httpURLConnection.connect();
            // 获得响应状态
            int http_StatusCode = httpURLConnection.getResponseCode();
            String http_ResponseMessage = httpURLConnection.getResponseMessage();
            obj = new JSONObject();
            if (HttpURLConnection.HTTP_OK == http_StatusCode) {
                strBuffer = new StringBuffer();
                String readLine = new String();
                BufferedReader responseReader = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    strBuffer.append(readLine);
                }
                responseReader.close();
                obj = JSONObject.parseObject(strBuffer.toString());
            } else {
                throw new RuntimeException(
                        MessageFormat.format("POST请求失败,失败原因: Http状态码 = {0} , {1}", http_StatusCode, http_ResponseMessage));
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static JSONObject sendPMPOST(String apiUrl, String data) {
        StringBuffer strBuffer = null;
        JSONObject obj = null;
        try {
            // 建立连接
            URL url = new URL(apiUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 需要输出
            httpURLConnection.setDoOutput(true);
            // 需要输入
            httpURLConnection.setDoInput(true);
            // 不允许缓存
            httpURLConnection.setUseCaches(false);

            httpURLConnection.setRequestMethod("POST");
            // 设置Headers
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("cookie", "_dataflulx_usr_id=c72d1d41-5923-47d8-b7f9-53631a621c17; ppid4gc=1153067; _bp_fg_=3IgQ9XNJ2D41NoGW+cT4AQ==; _bp_ff_=nWGv52nJ9u0udeQ9nQm2DvYoC2mjyhDiDn/T0I9Mkl+v8AkzjQSuRCADFydBMP09iDpotTY/LyIRYnhdi4Y29A==; userToken=s2kLDSW0yDW2QgY%2BsqGiYeQj4cDDpqF%2Bo3p0knPLhS5HzYfhtAtiPF0VxwdmcF7nzymfwNJ8T8UnHEGvfPKFtVfBRObW3%2FsShoJ8g%2BnQu2CCmPpFXQS4VnHOrklWcy7qaccBFE14E2PjrtU8AKwXYKHLDd3k%2FAYWSXUVL8lNON2UMloDyoalnAuoYGnnajwo; _site3_f_ue_=lIq19fS8GO85MlbkDBPoboqS/5TUtG2wddhag/q9vDC9GrBl1b36MzGWz6NcBLkFLoY/GSVCkqGb/RJs4kqjvBGevZCODPK46qhHLc2/KUszSNcaz6nUZSJs4A5CuoNI0LjE3AALySanpfxQr9frxgrb6Z5EKm1ASt6+iNc/2P0FOdBGguKaGKRI4qJ7FO4RcacZBHex0A51AiNaLUEFvBBI9oeEjTvHJUVaHNj7dY4OIyf5v19GrrmbraNmkl7kNi16L75jKDrcOzYBsH2BffWp8Vb4llQf/Zt7b9FQc6RJYUIiq8o6YmZn9QCN5NVsffMoy3/qZG0lsjD4mpTbOQ==; PLUG_TIME=null; JSESSIONID=8C36CF36ABE9D146BF412C023AE4BF84; _site2_f_ue_=19iDEFkVC%2F1btRFZNUHM9qDR0f7PO1CmYJr5InnXsRnPaynxqsELx5rCcA0wTSWb%2BmvAI1mZXMsqSQ5%2FQ7U8g%2BW%2F3gF0eDiQA4XsO3CSVjoWW0jyqrWiUWUANS%2FXGUysQHjpbefODCch2OzXKy2xTl8g2%2Fm5u1UtYn3EhuYMdpbg1iuu8fOZuOU4yDKAMarXnVIr5IvJMhZpAwVhJq1jckvHkgGoRjcXEOFQBz4%2FoV47qoXyAO9slWrh8junHJkrqJsABPJSlBfM4IkZcK7UJ%2BTcZX%2B1VetywxQcfAQ7YK9CfL5VubbGK2ITo%2F4PVOz2uYTu5BszkmVjmDyaLSdyqbc2NNnlSR%2BRZAzYNQ6N0Z0%3D; _dataflux_s=rum=1&id=30bd6180-079a-43e2-9d6b-b88fb23b3110&created=1685949880156&expire=1685952355592");
            // 连接会话
            httpURLConnection.connect();
            // 建立输入流，向指向的URL传入参数
            DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
            // 设置请求参数
            dos.write(data.getBytes("UTF-8"));
            dos.flush();
            dos.close();
            // 获得响应状态
            int http_StatusCode = httpURLConnection.getResponseCode();
            String http_ResponseMessage = httpURLConnection.getResponseMessage();
            obj = new JSONObject();
            if (HttpURLConnection.HTTP_OK == http_StatusCode) {
                strBuffer = new StringBuffer();
                String readLine = new String();
                BufferedReader responseReader = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    strBuffer.append(readLine);
                }
                responseReader.close();
                obj = JSONObject.parseObject(strBuffer.toString());
            } else {
                throw new RuntimeException(
                        MessageFormat.format("POST请求失败,失败原因: Http状态码 = {0} , {1}", http_StatusCode, http_ResponseMessage));
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static JSONObject sendMSPPOST(String apiUrl, String data) {
        StringBuffer strBuffer = null;
        JSONObject obj = null;
        try {
            // 建立连接
            URL url = new URL(apiUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 需要输出
            httpURLConnection.setDoOutput(true);
            // 需要输入
            httpURLConnection.setDoInput(true);
            // 不允许缓存
            httpURLConnection.setUseCaches(false);

            httpURLConnection.setRequestMethod("POST");
            // 设置Headers
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("cookie", "access_token=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2ODc5NDY5MDUsInVzZXJfbmFtZSI6IjIwMjEwMDAwNzY1LeaWveW3pSIsImp0aSI6IjhiN2FjYjJmLWM5YTctNGJhZi05MTkyLWEzZGRmOTZmNDU5OCIsImNsaWVudF9pZCI6Im1pY3Jvc2VydmljZS1jb21tb24tcHJvdmlkZXIiLCJzY29wZSI6WyJzZXJ2aWNlIiwiYWxsIl19.DJ2d86SY_oIGzizOKQnFnDrErA_AWz9sdQZCSQZdQJ0UqvMT8pbkT8gjCbJwxbw1KuGmIQCQVawK3sxQCnhLmtB7HLBmzuB0cwexFqtW6-VkA-iBKu_b0BONaUtyzymP3Kzbm-M_VFZdWdatw3t6bNM7-l1SP3ZaaIbhvEPFlc6NHdZfMX0ywfikGHwcMgr88qUM4wGaQpTmgmKTwyg6xP4AM5XeTO1AwsX4lUq0luVAjDmNDwB62Do-IzZGF-ckwVhy-I8yGQq2tPWEbNnjiyqPlorTnptpJjkdYyatpx9CW4RQr9vW4amer6VLxkquDONBx7US1N187eDk-J8Ttg; userUuid=9d499592b57c452cbd2726037b8fc5d3");

            // 连接会话
            httpURLConnection.connect();
            // 建立输入流，向指向的URL传入参数
            DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
            // 设置请求参数
            dos.write(data.getBytes("UTF-8"));
            dos.flush();
            dos.close();
            // 获得响应状态
            int http_StatusCode = httpURLConnection.getResponseCode();
            String http_ResponseMessage = httpURLConnection.getResponseMessage();
            obj = new JSONObject();
            if (HttpURLConnection.HTTP_OK == http_StatusCode) {
                strBuffer = new StringBuffer();
                String readLine = new String();
                BufferedReader responseReader = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    strBuffer.append(readLine);
                }
                responseReader.close();
                obj = JSONObject.parseObject(strBuffer.toString());
            } else {
                throw new RuntimeException(
                        MessageFormat.format("POST请求失败,失败原因: Http状态码 = {0} , {1}", http_StatusCode, http_ResponseMessage));
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static JSONObject sendPMGET(String apiUrl) {
        StringBuffer strBuffer = null;
        JSONObject obj = null;
        try {
            // 建立连接
            URL url = new URL(apiUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 需要输出
            httpURLConnection.setDoOutput(true);
            // 需要输入
            httpURLConnection.setDoInput(true);
            // 不允许缓存
            httpURLConnection.setUseCaches(false);

            httpURLConnection.setRequestMethod("GET");
            // 设置Headers
            httpURLConnection.setRequestProperty("Content-Type", "application/json");

            httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
            httpURLConnection.setRequestProperty("cookie", "ppid4gc=1153067; _bp_fg_=3IgQ9XNJ2D41NoGW+cT4AQ==; _bp_ff_=nWGv52nJ9u0udeQ9nQm2DvYoC2mjyhDiDn/T0I9Mkl/IjmyRisigCTmpLWEsyj3b0UXogKJ8Nkom/u98B5Nb5A==; userToken=X9KqHhDoBK5Y%2B2ScaGzciYOzWVADQxX3VIyWciFYPgOvbYLL%2BdT1pr2%2BygjRvSLmpUYOA20%2FB0Pd6%2FGItjF9Rj%2Flcrcl2qEre2JdetUqJ6V7344nLvZYwx5YvFfzx5e00K2LLCbdIABz%2FMPV8QAxfWK9SeBMt732B%2Bh%2F5Y9agdv2u0ajwlCI1QQF2OxV4bO6; _dataflulx_usr_id=b8e83542-1b63-47a2-aec3-01df980aef0a; _site3_f_ue_=lIq19fS8GO85MlbkDBPoboqS/5TUtG2wddhag/q9vDB2xiUiW+/ykNTfSdzXqKbzysck/4KxDSfDQujvQV9XWw0+6WXfYsavobgpeTViH/HGUJBeb6bcur+LiafHSil61kP3bzVXVhlO84XpucJCzKvk/O43ZxW9G9lKPrufQAP/dexI8S+ufpdfsgwt9dge+8lsLBuRB1GcH6cBkMTQmOQ7XlZq99xR1GIBCNrqMXULLAH9RYWT7ZXcZyCeBOmwQDnRu8Tq0EzHpT8KsNiZ8tic09zRjqNdMzXlFFckh1DvSWlIeYqS0Qw+7rvzNxGBtdN3lVkS3zdWqAfwhfehlg==; PLUG_TIME=null; JSESSIONID=E6B7C33374E6E5C50F2E8041A16AA178; _dataflux_s=rum=1&id=216039bc-ebe0-4408-82d6-cef5f8194588&created=1704853982491&expire=1704858554151");
            httpURLConnection.setRequestProperty("authorization", "Bearer eyJ0b2tlblR5cGUiOiJhY2Nlc3NUb2tlbiIsImFsZyI6IkhTMzg0In0.eyJqdGkiOiJkNmFmMWVmNy1jMDI5LTRmZjktOTI0Mi0zYTgyOTM2MWE3NDEiLCJpc3MiOiJzc28iLCJpYXQiOjE3MDQ4NDg3MDQsIm5iZiI6MTcwNDg0ODcwNCwiZXhwIjoxNzA2ODQ4NzA0LCJjcmVhdGVUaW1lIjoxNzA0ODQ4NzA0NzExLCJleHBpcmVkU2Vjb25kIjoyMDAwMDAwLCJsb2dpblRpbWUiOjE3MDQ4NDg3MDQ2OTgsImFwcEtleSI6IjhhOWNhMzIwNWJiNTBiZTcwMTViYjUwYmU3NGEwMDAwIiwidXNlciI6eyJpZCI6IjJjOTQ4Y2VjN2I4Mjc4Y2EwMTdjYzZjMGMxMzg1M2EzIiwibWVtYmVyTmFtZSI6IueOi-WIqSIsImxvZ2luTmFtZSI6IjU4MjhkODVjLTg3YWEtNGVjZC04ODljLTcwOTk2NmE2MmEyOC10IiwiaXBBZGRyZXNzIjoiMTcyLjIwLjU3LjIwMiIsImFwcEtleSI6IjhhOWNhMzIwNWJiNTBiZTcwMTViYjUwYmU3NGEwMDAwIiwibG9naW5UaW1lIjoxNzA0ODQ4NzA0Njk4LCJyZW1lbWJlclNlYyI6ODY0MDB9fQ.0E_0cB-2W6x3g9fA9MyramVs8U1boyronb86xo1pjgtINH6bMEk8u9E600l_t8Q7");
            // 连接会话
            httpURLConnection.connect();
            // 获得响应状态
            int http_StatusCode = httpURLConnection.getResponseCode();
            String http_ResponseMessage = httpURLConnection.getResponseMessage();

            if (HttpURLConnection.HTTP_OK == http_StatusCode) {
                strBuffer = new StringBuffer();
                String readLine = new String();
                BufferedReader responseReader = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    strBuffer.append(readLine);
                }
                responseReader.close();
                obj = JSONObject.parseObject(strBuffer.toString());
            } else {
                throw new RuntimeException(
                        MessageFormat.format("GET请求失败,失败信息:Http状态码 = {0} , {1}", http_StatusCode,
                                http_ResponseMessage));
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return obj;
    }

    /***
     * 向指定URL发送GET方法的请求
     *
     * @return
     */
    public static JSONObject sendGET(String apiUrl) {
        StringBuffer strBuffer = null;
        JSONObject obj = null;
        try {
            // 建立连接
            URL url = new URL(apiUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 需要输出
            httpURLConnection.setDoOutput(true);
            // 需要输入
            httpURLConnection.setDoInput(true);
            // 不允许缓存
            httpURLConnection.setUseCaches(false);

            httpURLConnection.setRequestMethod("GET");
            // 设置Headers
            httpURLConnection.setRequestProperty("Content-Type", "application/json");

            httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
            httpURLConnection.setRequestProperty("contentType", "utf-8");
            // 连接会话
            httpURLConnection.connect();
            // 获得响应状态
            int http_StatusCode = httpURLConnection.getResponseCode();
            String http_ResponseMessage = httpURLConnection.getResponseMessage();

            if (HttpURLConnection.HTTP_OK == http_StatusCode) {
                strBuffer = new StringBuffer();
                String readLine = new String();
                BufferedReader responseReader = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    strBuffer.append(readLine);
                }
                responseReader.close();
                obj = JSONObject.parseObject(strBuffer.toString());
            } else {
                throw new RuntimeException(
                        MessageFormat.format("GET请求失败,失败信息:Http状态码 = {0} , {1}", http_StatusCode,
                                http_ResponseMessage));
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static JSONObject sendEzvizChannelStatusGET(String apiUrl, String accessToken, String deviceSerial) {
        StringBuffer strBuffer = null;
        JSONObject obj = null;
        try {
            // 建立连接
            URL url = new URL(apiUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // 需要输出
            httpURLConnection.setDoOutput(true);
            // 需要输入
            httpURLConnection.setDoInput(true);
            // 不允许缓存
            httpURLConnection.setUseCaches(false);

            httpURLConnection.setRequestMethod("GET");
            // 设置Headers
            httpURLConnection.setRequestProperty("Content-Type", "application/json");

            httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
            httpURLConnection.setRequestProperty("contentType", "utf-8");
            httpURLConnection.setRequestProperty("accessToken", accessToken);
            httpURLConnection.setRequestProperty("deviceSerial", deviceSerial);
            // 连接会话
            httpURLConnection.connect();
            // 获得响应状态
            int http_StatusCode = httpURLConnection.getResponseCode();
            String http_ResponseMessage = httpURLConnection.getResponseMessage();

            if (HttpURLConnection.HTTP_OK == http_StatusCode) {
                strBuffer = new StringBuffer();
                String readLine = new String();
                BufferedReader responseReader = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    strBuffer.append(readLine);
                }
                responseReader.close();
                obj = JSONObject.parseObject(strBuffer.toString());
            } else {
                throw new RuntimeException(
                        MessageFormat.format("GET请求失败,失败信息:Http状态码 = {0} , {1}", http_StatusCode,
                                http_ResponseMessage));
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return obj;
    }

    /***
     * 向指定URL发送GET方法的请求
     *
     * @return
     */
    public static JSONObject sendHttpGET(String apiUrl) {
        StringBuffer strBuffer = null;
        JSONObject obj = null;
        try {
            HttpGet httpGet = new HttpGet(apiUrl);
            CloseableHttpResponse response = HttpClientBuilder.create().build().execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            HttpEntity entity = response.getEntity();
            String s = EntityUtils.toString(entity);
            obj = JSONObject.parseObject(s);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return obj;
    }
}
