package com.platform.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.*;
import java.net.*;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Slf4j
public class HttpRequestorUtil {

	private String charset = "utf-8";
    private Integer connectTimeout = null;
    private Integer socketTimeout = null;
    private String proxyHost = null;
    private Integer proxyPort = null;
    
    /**
     * Do GET request
     * @param url
     * @return
     * @throws Exception
     * @throws IOException
     */
    public String doGet(String url) throws Exception {
        
        URL localURL = new URL(url);
        
        URLConnection connection = openConnection(localURL);
        HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
        
        httpURLConnection.setRequestProperty("Accept-Charset", charset);
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;
        
        if (httpURLConnection.getResponseCode() >= 300) {
            log.info("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
            return null;
        }
        
        try {
            inputStream = httpURLConnection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
            reader = new BufferedReader(inputStreamReader);
            
            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }
            
        } finally {
            
            if (reader != null) {
                reader.close();
            }
            
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
            
            if (inputStream != null) {
                inputStream.close();
            }
            
        }

        return resultBuffer.toString();
    }
    
    /**
     * Do POST request
     * @param url
     * @param parameterMap
     * @return
     * @throws Exception 
     */
    public static String doPost(String url, Map parameterMap) throws Exception {
        
        /* Translate parameter map to parameter date string */
        StringBuffer parameterBuffer = new StringBuffer();
        if (parameterMap != null) {
            Iterator iterator = parameterMap.keySet().iterator();
            String key = null;
            String value = null;
            while (iterator.hasNext()) {
                key = (String)iterator.next();
                if (parameterMap.get(key) != null) {
                    value = (String)parameterMap.get(key);
                } else {
                    value = "";
                }
                
                parameterBuffer.append(key).append("=").append(value);
                if (iterator.hasNext()) {
                    parameterBuffer.append("&");
                }
            }
        }
        
        log.info("POST parameter : " + parameterBuffer.toString());
        
        URL localURL = new URL(url);
        log.info("POST URL : " + url);
        HttpURLConnection connection = (HttpURLConnection) localURL.openConnection();
        HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
        
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Accept-Charset", "UTF-8");
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterBuffer.length()));
        
        OutputStream outputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;
        
        try {
            outputStream = httpURLConnection.getOutputStream();
            outputStreamWriter = new OutputStreamWriter(outputStream);
            
            outputStreamWriter.write(parameterBuffer.toString());
            outputStreamWriter.flush();
            
            if (httpURLConnection.getResponseCode() >= 300) {
                throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
            }
            log.info("POST finish.");
            
            inputStream = httpURLConnection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(inputStreamReader);
            
            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }
            
        } finally {
            
            if (outputStreamWriter != null) {
                outputStreamWriter.close();
            }
            
            if (outputStream != null) {
                outputStream.close();
            }
            
            if (reader != null) {
                reader.close();
            }
            
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
            
            if (inputStream != null) {
                inputStream.close();
            }
            
        }

        return resultBuffer.toString();
    }

    /**
     * 文件上传支持中文
     *
     * @param reportUrl
     * @param filepath
     * @param savepath
     * @throws IOException
     */
    public static void uploadReport(String reportUrl, String filepath,
                                    String savepath) {
        CloseableHttpClient closeableHttpClient = null;
        CloseableHttpResponse response = null;
        try {
            closeableHttpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(reportUrl);
            String filename = filepath.split("/")[filepath.split("/").length - 1];
            File file = new File(filepath);

            FileBody fileBody = new FileBody(file, ContentType.create("multipart/form-data", "UTF-8"), filename);
            StringBody userIdStringBody = new StringBody(savepath, ContentType.create("multipart/form-data", "UTF-8"));
            StringBody reportNameStringBody = new StringBody(filename, ContentType.create("multipart/form-data", "UTF-8"));

            HttpEntity httpEntity = MultipartEntityBuilder
                    .create()
                    .setCharset(Charset.forName("UTF-8"))
                    .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                    .addPart("file", fileBody)
                    .addPart("savepath", userIdStringBody)
                    .addPart("reportName", reportNameStringBody)
                    .build();

            httpPost.setEntity(httpEntity);
            response = closeableHttpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                log.info("上传成功:" + savepath);
            } else {
                BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
                StringBuffer buffer = new StringBuffer();
                String str = "";
                while ((str = reader.readLine()) != null && (str = reader.readLine()).trim().length() > 0) {
                    buffer.append(str);
                }
                log.info(buffer.toString());
                log.info("上传失败：" + statusCode);
            }
            closeableHttpClient.close();
            if (response != null) {
                response.close();
            }

        } catch (Exception ex) {
            log.info("uploadReport发生异常：" + ex);
        } finally {
            try {
                if (closeableHttpClient != null) {
                    closeableHttpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 发送HttpPost请求
     *
     * @param strURL
     *            服务地址
     * @param params
     *            json字符串,例如: "{ \"id\":\"12345\" }" ;其中属性名必须带双引号<br/>
     * @return 成功:返回json字符串<br/>
     */
    public static String postJson(String strURL, String params, String type) {
        log.info(strURL);
        log.info(params);
        BufferedReader reader = null;
        try {
            URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod(type); // 设置请求方式
            // connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.setRequestProperty("Authorizations", "Y9z$w*WA%z!uz0O$dcCQ@i1KHKs5rhQW");
            connection.connect();
            //一定要用BufferedReader 来接收响应， 使用字节来接收响应的方法是接收不到内容的
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(params);
            out.flush();
            out.close();
            // 读取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            String res = "";
            while ((line = reader.readLine()) != null) {
                res += line;
            }
            reader.close();

            //如果一定要使用如下方式接收响应数据， 则响应必须为: response.getWriter().print(StringUtils.join("{\"errCode\":\"1\",\"errMsg\":\"", message, "\"}")); 来返回
//            int length = (int) connection.getContentLength();// 获取长度
//            if (length != -1) {
//                byte[] data = new byte[length];
//                byte[] temp = new byte[512];
//                int readLen = 0;
//                int destPos = 0;
//                while ((readLen = is.read(temp)) > 0) {
//                    System.arraycopy(temp, 0, data, destPos, readLen);
//                    destPos += readLen;
//                }
//                String result = new String(data, "UTF-8"); // utf-8编码
//                log.info(result);
//                return result;
//            }

            return res;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "error"; // 自定义错误信息
    }

    public static void main(String[] args) {
        try{
            Map postData = new HashMap();
//            postData.put("vrBuilding", "http://192.168.0.47:8086/showProMobile.html?m=001-zFzxA5FkS");
//            postData.put("editBuilding", "http://192.168.0.47:8086/editProMobile.html?m=001-zFzxA5FkS");
//            postData.put("siweiId", "001-zFzxA5FkS");
//            postData.put("name", "中国银行2");
//            String result = doPost("http://49.4.86.68:8080/bankBack/back/vrhome/insertbuilding.htm", postData);
            HttpRequestorUtil util = new HttpRequestorUtil();
//            String result = util.doGet("https://4dkk.4dage.com/data/datagu6HmTLKp/hot.json");
//            JSONArray array = JSONObject.parseArray(result);
//
//            for (int i = 0; i < array.size(); i++) {
//                JSONObject jsonObject = array.getJSONObject(i);
//                System.out.println(("hotName:" + jsonObject.getString("label")));
//                System.out.println(("media:" + jsonObject.getString("media").replace("\"", "").replace("[", "").replace("]", "")));
//            }

//            postData.put("num", "gu6HmTLKp");
//            String result = util.doPost("https://www.4dkankan.com/api/scene/getInfo", postData);
//            JSONObject object = JSON.parseObject(result);
//            if(object.getIntValue("code") == 0){
//                JSONObject data = object.getJSONObject("data");
//                log.info(data.getString("sceneName"));
//            }

//            JSONObject post = new JSONObject();
//            post.put("num", "t-SWRrFu3");
//            String result = util.postJson("https://test.4dkankan.com/api/scene/getInfo", post.toString(), "POST");
//            JSONObject object = JSON.parseObject(result);
//            if(object.getIntValue("code") == 0){
//                JSONArray array = object.getJSONArray("data");
//                for (int i = 0; i < array.size(); i++) {
//                    log.info("1111");
//                }
//                log.info("sad");
//            }

            postData = new HashMap();
            postData.put("num", "t-SWRrFu3");
            String result = util.doPost("https://test.4dkankan.com/api/scene/getInfo", postData);
            JSONObject object = JSON.parseObject(result);
            if(object.getIntValue("code") == 0){
                JSONObject data = object.getJSONObject("data");
                String sceneName = new String(data.getString("sceneName").getBytes(), "UTF-8");
                System.out.println(sceneName);
            }

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

//        uploadReport("http://114.215.208.201:8080/filecommon/file/uploadsiweifile.htm", "F:\\桌面\\迁移场景\\bi8u5kUcn\\tex\\texture1.jpg",
//                "scene/data/datat-KvqDwm3/");
    }

    private URLConnection openConnection(URL localURL) throws IOException {
        URLConnection connection;
        if (proxyHost != null && proxyPort != null) {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
            connection = localURL.openConnection(proxy);
        } else {
            connection = localURL.openConnection();
        }
        return connection;
    }
    
    /**
     * Render request according setting
     */
    private void renderRequest(URLConnection connection) {
        
        if (connectTimeout != null) {
            connection.setConnectTimeout(connectTimeout);
        }
        
        if (socketTimeout != null) {
            connection.setReadTimeout(socketTimeout);
        }
        
    }

    /*
     * Getter & Setter
     */
    public Integer getConnectTimeout() {
        return connectTimeout;
    }

    public void setConnectTimeout(Integer connectTimeout) {
        this.connectTimeout = connectTimeout;
    }

    public Integer getSocketTimeout() {
        return socketTimeout;
    }

    public void setSocketTimeout(Integer socketTimeout) {
        this.socketTimeout = socketTimeout;
    }

    public String getProxyHost() {
        return proxyHost;
    }

    public void setProxyHost(String proxyHost) {
        this.proxyHost = proxyHost;
    }

    public Integer getProxyPort() {
        return proxyPort;
    }

    public void setProxyPort(Integer proxyPort) {
        this.proxyPort = proxyPort;
    }

    public String getCharset() {
        return charset;
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }
}
