package com.huimv.video.dhicc.test.utils;

import com.alibaba.fastjson.JSONObject;
import com.huimv.video.dhicc.test.constant.Constant;
import com.huimv.video.dhicc.test.request.BaseRequest;
import com.huimv.video.dhicc.test.request.BaseRequest02;
import com.huimv.video.dhicc.test.request.BaseRequest03;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;


/**
 * Http请求类，基于JDK自带的HttpURLConnectionUtil请求类
 */
public class HttpURLConnectionUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpURLConnectionUtil.class);

    /**
     * @param request 请求对象
     * @return String json字符串格式的响应数据
     * **/
    public static String doGet(BaseRequest request){
        String httpUrl = request.getUrl();
        Map<String, String> headers = request.getHeader();
        logger.info("HttpURLConnectionUtil,doGet,URL:{}, headers:{}", httpUrl, headers);
        StringBuilder response = new StringBuilder();
        BufferedReader bufferedReader = null;

        try{
            //创建连接
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();

            //设置请求方式
            connection.setRequestMethod(Constant.HTTP_GET);
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
            //设置自定义请求头信息
            setCustomHeader(connection, headers);

            //设置请求超时时间:10秒
            connection.setConnectTimeout(10 * 1000);
            //设置读取超时时间:10秒
            connection.setReadTimeout(10 * 1000);
            //开始连接
            connection.connect();
            if(connection.getResponseCode() == 404){
                JSONObject result = new JSONObject();
                result.put("code","404");
                result.put("errMsg","子系统未安装或接口与版本不匹配");
                return result.toJSONString();
            }
            //获取响应数据
            String readLine = null;
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            while((readLine = bufferedReader.readLine()) != null){
                response.append(readLine);
            }
            bufferedReader.close();
        }catch (MalformedURLException e){
            logger.error("HttpURLConnectionUtil,doGet,request error:{}", e.getMessage());
            e.printStackTrace();
        }catch (IOException e){
            logger.error("HttpURLConnectionUtil,doGet,request error:{}", e.getMessage());
            e.printStackTrace();
        }
        return response.toString();
    }


    public static String doGet02(BaseRequest02 request){
        String httpUrl = request.getUrl();
        Map<String, String> headers = request.getHeader();
        logger.info("HttpURLConnectionUtil,doGet,URL:{}, headers:{}", httpUrl, headers);
        StringBuilder response = new StringBuilder();
        BufferedReader bufferedReader = null;

        try{
            //创建连接
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();

            //设置请求方式
            connection.setRequestMethod(Constant.HTTP_GET);
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
            //设置自定义请求头信息
            setCustomHeader(connection, headers);

            //设置请求超时时间:10秒
            connection.setConnectTimeout(10 * 1000);
            //设置读取超时时间:10秒
            connection.setReadTimeout(10 * 1000);
            //开始连接
            connection.connect();
            if(connection.getResponseCode() == 404){
                JSONObject result = new JSONObject();
                result.put("code","404");
                result.put("errMsg","子系统未安装或接口与版本不匹配");
                return result.toJSONString();
            }
            //获取响应数据
            String readLine = null;
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            while((readLine = bufferedReader.readLine()) != null){
                response.append(readLine);
            }
            bufferedReader.close();
        }catch (MalformedURLException e){
            logger.error("HttpURLConnectionUtil,doGet,request error:{}", e.getMessage());
            e.printStackTrace();
        }catch (IOException e){
            logger.error("HttpURLConnectionUtil,doGet,request error:{}", e.getMessage());
            e.printStackTrace();
        }
        return response.toString();
    }
    public static String doGet03(BaseRequest03 request){
        String httpUrl = request.getUrl();
        Map<String, String> headers = request.getHeader();
        logger.info("HttpURLConnectionUtil,doGet,URL:{}, headers:{}", httpUrl, headers);
        StringBuilder response = new StringBuilder();
        BufferedReader bufferedReader = null;

        try{
            //创建连接
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();

            //设置请求方式
            connection.setRequestMethod(Constant.HTTP_GET);
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
            //设置自定义请求头信息
            setCustomHeader(connection, headers);

            //设置请求超时时间:10秒
            connection.setConnectTimeout(10 * 1000);
            //设置读取超时时间:10秒
            connection.setReadTimeout(10 * 1000);
            //开始连接
            connection.connect();
            if(connection.getResponseCode() == 404){
                JSONObject result = new JSONObject();
                result.put("code","404");
                result.put("errMsg","子系统未安装或接口与版本不匹配");
                return result.toJSONString();
            }
            //获取响应数据
            String readLine = null;
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            while((readLine = bufferedReader.readLine()) != null){
                response.append(readLine);
            }
            bufferedReader.close();
        }catch (MalformedURLException e){
            logger.error("HttpURLConnectionUtil,doGet,request error:{}", e.getMessage());
            e.printStackTrace();
        }catch (IOException e){
            logger.error("HttpURLConnectionUtil,doGet,request error:{}", e.getMessage());
            e.printStackTrace();
        }
        return response.toString();
    }

    /**
     * @param httpUrl 请求地址
     * @param jsonStr json字符串格式的请求数据
     * @return String json字符串格式的响应数据
     * **/
    public static String doPost(String httpUrl, String jsonStr, Map<String, String> headers){
        logger.info("HttpURLConnectionUtil,doPost,URL:" + httpUrl);
        StringBuilder response = new StringBuilder();
        BufferedReader bufferedReader = null;

        try{
            //创建连接
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();

            //设置请求方式
            connection.setRequestMethod(Constant.HTTP_POST);
            connection.setRequestProperty("accept", "application/json");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("content-type", "application/json;charset=UTF-8");
            //设置自定义请求头信息
            setCustomHeader(connection, headers);

            connection.setDoOutput(true);
            connection.setDoInput(true);
            //设置请求超时时间:10秒
            connection.setConnectTimeout(10 * 1000);
            //设置读取超时时间:10秒
            connection.setReadTimeout(10 * 1000);
            //设置请求参数
            if(jsonStr != null && !"".equalsIgnoreCase(jsonStr)){
                OutputStream outputStream = connection.getOutputStream();
                byte[] input = jsonStr.getBytes("utf-8");
                outputStream.write(input, 0, input.length);
                outputStream.flush();
                outputStream.close();
            }
            connection.connect();
            if(connection.getResponseCode() == 404){
                JSONObject result = new JSONObject();
                result.put("code","404");
                result.put("errMsg","子系统未安装或接口与版本不匹配");
                return result.toJSONString();
            }
            //获取响应数据
            String readLine = null;
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            while((readLine = bufferedReader.readLine()) != null){
                response.append(readLine);
            }
            bufferedReader.close();
        }catch (MalformedURLException e){
            logger.error("HttpURLConnectionUtil,doPost,request error:{}", e.getMessage());
            e.printStackTrace();
        }catch (IOException e){
            logger.error("HttpURLConnectionUtil,doPost,request error:{}", e.getMessage());
            e.printStackTrace();
        }

        return response.toString();
    }




    /**
     * @param httpUrl 请求地址
     * @param jsonStr json字符串格式的请求数据
     * @return String json字符串格式的响应数据
     * **/
    public static String doPut(String httpUrl, String jsonStr, Map<String, String> headers){
        logger.info("HttpURLConnectionUtil,doPut,URL:" + httpUrl);
        StringBuilder response = new StringBuilder();
        BufferedReader bufferedReader = null;

        try{
            //创建连接
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();

            //设置请求方式
            connection.setRequestMethod(Constant.HTTP_PUT);
            connection.setRequestProperty("accept", "application/json");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("content-type", "application/json;charset=UTF-8");
            //设置自定义请求头信息
            setCustomHeader(connection, headers);

            connection.setDoOutput(true);
            connection.setDoInput(true);
            //设置请求超时时间:10秒
            connection.setConnectTimeout(10 * 1000);
            //设置读取超时时间:10秒
            connection.setReadTimeout(10 * 1000);
            //设置请求参数
            if(jsonStr != null && !"".equalsIgnoreCase(jsonStr)){
                OutputStream outputStream = connection.getOutputStream();
                byte[] input = jsonStr.getBytes("utf-8");
                outputStream.write(input, 0, input.length);
                outputStream.flush();
                outputStream.close();
            }
            connection.connect();
            if(connection.getResponseCode() == 404){
                JSONObject result = new JSONObject();
                result.put("code","404");
                result.put("errMsg","子系统未安装或接口与版本不匹配");
                return result.toJSONString();
            }
            //获取响应数据
            String readLine = null;
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            while((readLine = bufferedReader.readLine()) != null){
                response.append(readLine);
            }
            bufferedReader.close();
        }catch (MalformedURLException e){
            logger.error("HttpURLConnectionUtil,doPut,request error:{}", e.getMessage());
            e.printStackTrace();
        }catch (IOException e){
            logger.error("HttpURLConnectionUtil,doPut,request error:{}", e.getMessage());
            e.printStackTrace();
        }

        return response.toString();
    }

    /**
     * @param httpUrl 请求地址
     * @param jsonStr json字符串格式的请求数据
     * @return String json字符串格式的响应数据
     * **/
    public static String doDelete(String httpUrl, String jsonStr, Map<String, String> headers){
        logger.info("HttpURLConnectionUtil,doDelete,URL:" + httpUrl);
        StringBuilder response = new StringBuilder();
        BufferedReader bufferedReader = null;

        try{
            //创建连接
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();

            //设置请求方式
            connection.setRequestMethod(Constant.HTTP_DELETE);
            connection.setRequestProperty("accept", "application/json");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("content-type", "application/json;charset=UTF-8");
            //设置自定义请求头信息
            setCustomHeader(connection, headers);

            connection.setDoOutput(true);
            connection.setDoInput(true);
            //设置请求超时时间:10秒
            connection.setConnectTimeout(10 * 1000);
            //设置读取超时时间:10秒
            connection.setReadTimeout(10 * 1000);
            //设置请求参数
            if(jsonStr != null && !"".equalsIgnoreCase(jsonStr)){
                OutputStream outputStream = connection.getOutputStream();
                byte[] input = jsonStr.getBytes("utf-8");
                outputStream.write(input, 0, input.length);
                outputStream.flush();
                outputStream.close();
            }
            connection.connect();
            if(connection.getResponseCode() == 404){
                JSONObject result = new JSONObject();
                result.put("code","404");
                result.put("errMsg","子系统未安装或接口与版本不匹配");
                return result.toJSONString();
            }
            //获取响应数据
            String readLine = null;
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            while((readLine = bufferedReader.readLine()) != null){
                response.append(readLine);
            }
            bufferedReader.close();
        }catch (MalformedURLException e){
            logger.error("HttpURLConnectionUtil,doDelete,request error:{}", e.getMessage());
            e.printStackTrace();
        }catch (IOException e){
            logger.error("HttpURLConnectionUtil,doDelete,request error:{}", e.getMessage());
            e.printStackTrace();
        }

        return response.toString();
    }

    /**
     * 设置自定义请求头信息
     * **/
    public static void setCustomHeader(HttpURLConnection connection, Map<String, String> headers){
        if(!CollectionUtils.isEmpty(headers)){
            Set set = headers.entrySet();
            Iterator iterator = set.iterator();
            while(iterator.hasNext()){
                Map.Entry<String, String> entry = (Map.Entry<String, String>)iterator.next();
                String key = entry.getKey();
                String value = entry.getValue();
                connection.setRequestProperty(key, value);
            }
        }
    }
}
