package com.tofly.znb.utils;

import cn.hutool.core.collection.CollectionUtil;
import com.tofly.common.core.util.StringUtil;
import com.tofly.znb.common.exception.FeesErrorCode;
import com.tofly.znb.common.exception.FeesException;
import com.tofly.znb.common.util.ToolsUtils;
import com.tofly.znb.config.ZnbConfig;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class HttpRequestUtil {


    public static String GETRequest(String urlstr, String token) {
        return GETRequest(urlstr, token, "");
    }

    public static String GETRequest(String urlstr, String token, String params) {
        try {
            URL url = null;
            if (!StringUtil.isEmpty(params)) {
                url = new URL(urlstr + "?param=" + params);
            } else {
                url = new URL(urlstr);
            }
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            // 设置头信息
            con.setRequestMethod("GET");
            //con.setRequestProperty("X-Access-Token", token);
            // con.setRequestProperty("Accept", "application/json, text/plain, */*");
            //  con.setRequestProperty("X-Sign", "239D943E6EF1E33BDC18BDED629CBE55");
            //  con.setRequestProperty("X-Version", "v3");
            con.setRequestProperty("ContentType", "application/form-data");

            // 发送请求
            con.connect();

            // 读取响应
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer content = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
             //   content.append(inputLine.replace("\"", ""));
                content.append(inputLine);
            }
            in.close();
            if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
                con.disconnect();
                return content.toString();
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String POSTRequest(String urlstr, String params) {
        return POSTRequest(urlstr, params, "");
    }

    public static String POSTRequest2(String urlstr, String params, Map<String, String> dicHeder) {
        return POSTRequest2(urlstr, params, "", dicHeder);
    }


    public static String POSTRequest2(String urlstr, String params, String token, Map<String, String> dicHeder) {
        try {
            URL url = new URL(urlstr);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            // 设置头信息
            con.setRequestMethod("POST");
            if (StringUtil.isEmpty(token)) {
                con.setRequestProperty("X-Access-Token", "null");
            } else {
                con.setRequestProperty("X-Access-Token", token);
            }
            //     con.setRequestProperty("Accept", "application/json, text/plain, */*");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            //con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
//            if(!dicHeder.isEmpty()){
//               for (Map.Entry<String,String> entry:dicHeder.entrySet()){
//                    String key=entry.getKey();
//                    String value=entry.getValue();
//                    con.setRequestProperty(key, value);
//               }
//            }


            // 发送请求
            con.setDoOutput(true);
            DataOutputStream out = new DataOutputStream(con.getOutputStream());
            out.writeBytes(params);
            out.flush();
            out.close();

            // 读取响应
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer content = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine.replace("\"", ""));
            }
            in.close();

            // 获取身份标识
            if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
                con.disconnect();
                return content.toString();
            }
            return "";

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }


    public static String doPostByForm(String url, Map<String, String> dicvalue) {
        String strResult = "";
        //获取默认的client实例
        CloseableHttpClient client = HttpClients.createDefault();
        //创建httppost实例
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        //创建参数队列（键值对列表）
        List<NameValuePair> paramPairs = new ArrayList<>();

        if (!dicvalue.isEmpty()) {
            for (Map.Entry<String, String> entry : dicvalue.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                paramPairs.add(new BasicNameValuePair(key, value));
            }
        }

        UrlEncodedFormEntity entity;
        try {
            // 4. 将参数设置到entity对象中
            entity = new UrlEncodedFormEntity(paramPairs, "UTF-8");
            System.out.println("封装的参数：" + entity);
            // 5. 将entity对象设置到httppost对象中
            httpPost.setEntity(entity);
            // 6. 发送请求并回去响应
            CloseableHttpResponse resp = client.execute(httpPost);
            try {
                // 7. 获取响应entity
                HttpEntity respEntity = resp.getEntity();
                strResult = EntityUtils.toString(respEntity, "UTF-8");
            } finally {
                // 9. 关闭响应对象
                resp.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 10. 关闭连接，释放资源
            try {
                client.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return strResult;
    }

    public static String POSTRequest(String urlstr, String params, String token) {
        try {
            URL url = new URL(urlstr);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            // 设置头信息
            con.setRequestMethod("POST");
            if (StringUtil.isEmpty(token)) {
                con.setRequestProperty("X-Access-Token", "null");
            } else {
                con.setRequestProperty("X-Access-Token", token);
            }

            con.setRequestProperty("Accept", "application/json, text/plain, */*");
            con.setRequestProperty("Content-Type", "application/json");
            //con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            con.setRequestProperty("X-Sign", "239D943E6EF1E33BDC18BDED629CBE55");
            con.setRequestProperty("X-Version", "v3");

            // 发送请求
            con.setDoOutput(true);
            DataOutputStream out = new DataOutputStream(con.getOutputStream());
            out.writeBytes(params);
            out.flush();
            out.close();

            // 读取响应
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer content = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine.replace("\"", ""));
            }
            in.close();

            // 获取身份标识
            if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
                con.disconnect();
                return content.toString();
            }
            return "";

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }


    public static String POSTFileRequest(String urlstr, String params, String token) {
        try {
            URL url = new URL(urlstr);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            // 设置头信息
            con.setRequestMethod("POST");
            if (StringUtil.isEmpty(token)) {
                con.setRequestProperty("X-Access-Token", "null");
            } else {
                con.setRequestProperty("X-Access-Token", token);
            }

            con.setRequestProperty("Accept", "multipart/form-data,text/plain, */*");
            con.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
            con.setRequestProperty("X-Sign", "239D943E6EF1E33BDC18BDED629CBE55");
            con.setRequestProperty("X-Version", "v3");

            // 发送请求
            con.setDoOutput(true);
            DataOutputStream out = new DataOutputStream(con.getOutputStream());
            out.writeBytes(params);
            out.flush();
            out.close();

            // 读取响应
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer content = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine.replace("\"", ""));
            }
            in.close();

            // 获取身份标识
            if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
                con.disconnect();
                return content.toString();
            }
            return "";

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String PUTRequest(String urlstr, String params, String token) {
        try {
            URL url = new URL(urlstr);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            // 设置头信息
            con.setRequestMethod("PUT");
            if (StringUtil.isEmpty(token)) {
                con.setRequestProperty("X-Access-Token", "null");
            } else {
                con.setRequestProperty("X-Access-Token", token);
            }

            con.setRequestProperty("Accept", "application/json, text/plain, */*");
            con.setRequestProperty("Content-Type", "application/json");
            //con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            con.setRequestProperty("X-Sign", "239D943E6EF1E33BDC18BDED629CBE55");
            con.setRequestProperty("X-Version", "v3");

            // 发送请求
            con.setDoOutput(true);
            DataOutputStream out = new DataOutputStream(con.getOutputStream());
            out.writeBytes(params);
            out.flush();
            out.close();

            // 读取响应
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer content = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine.replace("\"", ""));
            }
            in.close();

            // 获取身份标识
            if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
                con.disconnect();
                return content.toString();
            }
            return "";

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }


    /**
     * 获取Token
     *
     * @return String字符串
     */
    public static String GetToken(ZnbConfig znbConfig) {
        String appId = znbConfig.getAppId();
        String secret = znbConfig.getSecret();
        String apiHome = znbConfig.getApiUrl();
        Map<String, String> dicHeder = new HashMap<>();
        dicHeder.put("appId", appId);
        dicHeder.put("secret", secret);
        String token = HttpRequestUtil.doPostByForm(apiHome + "/api/auth/getToken", dicHeder);

        if (StringUtil.isEmpty(token)) {
            throw new FeesException("获取token异常", FeesErrorCode.BUSINESS_ERROR);
        }
        JSONObject jsonObj = new JSONObject(token);
        Map<String, Object> tokenMap = ToolsUtils.toMap(jsonObj);

        return tokenMap.get("token").toString();
    }

}
