package com.x.sso.assemble.control.utils;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.x.base.core.project.tools.Crypto;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
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 javax.crypto.CipherInputStream;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HttpClientUtilsUpfile {
    public static final int THREAD_POOL_SIZE = 5;

    public interface HttpClientDownLoadProgress {
        public void onProgress(int prgetInstanceogress);
    }

    private static HttpClientUtilsUpfile httpClientDownload;

    private ExecutorService downloadExcutorService;

    private HttpClientUtilsUpfile() {
        downloadExcutorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
    }

    public static HttpClientUtilsUpfile getInstance() {
        if (httpClientDownload == null) {
            httpClientDownload = new HttpClientUtilsUpfile();
        }
        return httpClientDownload;
    }

    /**
     * 下载文件
     *
     * @param url
     * @param filePath
     */
    public void download(final String url, final String filePath) {
        downloadExcutorService.execute(new Runnable() {
            public void run() {
                httpDownloadFile(url, filePath, null, null);
            }
        });
    }

    /**
     * 下载文件
     *
     * @param url
     * @param filePath
     * @param progress
     */
    public void download(final String url, final String filePath, final HttpClientDownLoadProgress progress) {
        downloadExcutorService.execute(new Runnable() {
            public void run() {
                httpDownloadFile(url, filePath, progress, null);
            }
        });
    }

    /**
     * 下载文件
     *
     * @param url
     * @param filePath
     */
    private void httpDownloadFile(String url, String filePath,
                                  HttpClientDownLoadProgress progress, Map<String, String> headMap) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            setGetHead(httpGet, headMap);
            CloseableHttpResponse response1 = httpclient.execute(httpGet);
            try {
                HttpEntity httpEntity = response1.getEntity();
                long contentLength = httpEntity.getContentLength();
                InputStream is = httpEntity.getContent();

                ByteArrayOutputStream output = new ByteArrayOutputStream();
                byte[] buffer = new byte[4096];
                int r = 0;
                long totalRead = 0;
                while ((r = is.read(buffer)) > 0) {
                    output.write(buffer, 0, r);
                    totalRead += r;
                    if (progress != null) {
                        progress.onProgress((int) (totalRead * 100 / contentLength));
                    }
                }
                FileOutputStream fos = new FileOutputStream(filePath);
                output.writeTo(fos);
                output.flush();
                output.close();
                fos.close();
                EntityUtils.consume(httpEntity);
            } finally {
                response1.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发送Get请求
     *
     * @param url
     * @return
     */
    public String httpGet(String url) {
        return httpGet(url, null);
    }

    /**
     * 发送Get请求
     *
     * @param url
     * @return
     */
    public String httpGet(String url, Map<String, String> headMap) {
        String responseContent = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response1 = httpclient.execute(httpGet);
            setGetHead(httpGet, headMap);
            try {
                System.out.println(response1.getStatusLine());
                HttpEntity entity = response1.getEntity();
                responseContent = getRespString(entity);
                System.out.println("debug:" + responseContent);
                EntityUtils.consume(entity);
            } finally {
                response1.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }

    public String httpPost(String url, Map<String, String> paramsMap) {
        return httpPost(url, paramsMap, null);
    }

    /**
     * 发送Post请求
     *
     * @param url
     * @param paramsMap
     * @return
     */
    public String httpPost(String url, Map<String, String> paramsMap, Map<String, String> headMap) {
        String responseContent = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            setPostHead(httpPost, headMap);
            setPostParams(httpPost, paramsMap);
            CloseableHttpResponse response = httpclient.execute(httpPost);
            try {
                System.out.println(response.getStatusLine());
                HttpEntity entity = response.getEntity();
                responseContent = getRespString(entity);
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("responseContent = " + responseContent);
        return responseContent;
    }

    /**
     * 设置Post请求的HttpHeader
     *
     * @param httpPost
     * @param headMap
     */
    private void setPostHead(HttpPost httpPost, Map<String, String> headMap) {
        if (headMap != null && headMap.size() > 0) {
            Set<String> keySet = headMap.keySet();
            for (String key : keySet) {
                httpPost.addHeader(key, headMap.get(key));
            }
        }
    }

    /**
     * 设置Get请求的HttpHeader
     *
     * @param httpGet
     * @param headMap
     */
    private void setGetHead(HttpGet httpGet, Map<String, String> headMap) {
        if (headMap != null && headMap.size() > 0) {
            Set<String> keySet = headMap.keySet();
            for (String key : keySet) {
                httpGet.addHeader(key, headMap.get(key));
            }
        }
    }


    /**
     * 上传文件的实现方法
     *
     * @param serverUrl
     * @param localFilePath
     * @param serverFieldName
     * @param params
     * @return
     * @throws Exception
     */
    public String uploadFileImpl(String serverUrl, String localFilePath, String serverFieldName, Map<String, String> params, Map<String, String> paramshead)
            throws Exception {
        String respStr = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost(serverUrl);
            setPostHead(httppost, paramshead);
            FileBody binFileBody = new FileBody(new File(localFilePath));

            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            // add the file params
            multipartEntityBuilder.addPart(serverFieldName, binFileBody);
            setUploadParams(multipartEntityBuilder, params);
            HttpEntity reqEntity = multipartEntityBuilder.build();
            httppost.setEntity(reqEntity);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity resEntity = response.getEntity();
                respStr = getRespString(resEntity);
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
        System.out.println("resp=" + respStr);
        return respStr;
    }


    /**
     * 上传文件的实现方法
     *
     * @param serverUrl
     * @param urlFilePath
     * @param urlFileName
     * @param serverFieldName
     * @param params
     * @return
     * @throws Exception
     */
    public String uploadUrlFileImpl(String serverUrl, String urlFilePath, String urlFileName, String serverFieldName, Map<String, String> params, Map<String, String> paramshead)
            throws Exception {
        String respStr = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost(serverUrl);
            setPostHead(httppost, paramshead);
            FileBody binFileBody = new FileBody(new File(urlFilePath));
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            // add the file params
            BufferedInputStream in = getFileInputStream(urlFilePath);
            InputStreamBody inputStreamBody = new InputStreamBody(in, urlFileName);
            multipartEntityBuilder.addPart(serverFieldName, inputStreamBody);
            setUploadParams(multipartEntityBuilder, params);
            HttpEntity reqEntity = multipartEntityBuilder.build();
            httppost.setEntity(reqEntity);

            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                respStr = getRespString(resEntity);
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
        System.out.println("resp=" + respStr);
        return respStr;
    }

    /**
     * 上传文件的实现方法
     * 上传前 需要解密
     *
     * @param serverUrl       上传附件服务
     * @param urlFilePath     附件URL
     * @param urlFileName     附件名称
     * @param serverFieldName
     * @param params          附件参数
     * @param paramshead      文件头
     * @param skey            密钥
     * @param siv             向量
     * @return
     * @throws Exception
     */
    public String uploadByteFileImpl(String serverUrl, String urlFilePath, String urlFileName, String serverFieldName, Map<String, String> params, Map<String, String> paramshead, String skey, String siv)
            throws Exception {
        String respStr = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost(serverUrl);
            setPostHead(httppost, paramshead);
            //ileBody binFileBody = new FileBody(new File(urlFilePath));
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            // add the file params

            BufferedInputStream fis = getFileInputStream(URLDecoder.decode(urlFilePath, "UTF-8"));
            ;
            //解密
            CipherInputStream cis = AESFile.decryptedFile(fis, skey, siv);

            if (cis != null) {
                //InputStream inputByteFile = new ByteArrayInputStream(byteFile);
                //BufferedInputStream in = new BufferedInputStream(inputByteFile);
                InputStreamBody inputStreamBody = new InputStreamBody(cis, urlFileName);
                multipartEntityBuilder.addPart(serverFieldName, inputStreamBody);
                setUploadParams(multipartEntityBuilder, params);
                HttpEntity reqEntity = multipartEntityBuilder.build();
                httppost.setEntity(reqEntity);

                CloseableHttpResponse response = httpclient.execute(httppost);
                try {
                    System.out.println(response.getStatusLine());
                    HttpEntity resEntity = response.getEntity();
                    respStr = getRespString(resEntity);
                    EntityUtils.consume(resEntity);
                } finally {
                    response.close();
                }
            } else {
                respStr = "解密失败";
            }

        } finally {
            httpclient.close();
        }
        System.out.println("resp=" + respStr);
        return respStr;
    }

    /**
     * 设置上传时的参数
     *
     * @param multipartEntityBuilder
     * @param params
     */
    private void setUploadParams(MultipartEntityBuilder multipartEntityBuilder,
                                 Map<String, String> params) {
        if (params != null && params.size() > 0) {
            Set<String> keys = params.keySet();
            for (String key : keys) {
                multipartEntityBuilder.addPart(key, new StringBody(params.get(key), ContentType.APPLICATION_JSON));

            }
        }
    }

    /**
     * 获取响应内容
     *
     * @param entity
     * @return
     * @throws Exception
     */
    private String getRespString(HttpEntity entity) throws Exception {
        if (entity == null) {
            return null;
        }
        InputStream is = entity.getContent();
        StringBuffer strBuf = new StringBuffer();
        byte[] buffer = new byte[4096];
        int r = 0;
        while ((r = is.read(buffer)) > 0) {
            strBuf.append(new String(buffer, 0, r, "UTF-8"));
        }
        return strBuf.toString();
    }

    /**
     * 设置Post请求发送的参数
     *
     * @param httpPost
     * @param paramsMap
     * @throws Exception
     */
    private void setPostParams(HttpPost httpPost, Map<String, String> paramsMap)
            throws Exception {
        if (paramsMap != null && paramsMap.size() > 0) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            Set<String> keySet = paramsMap.keySet();
            for (String key : keySet) {
                nvps.add(new BasicNameValuePair(key, paramsMap.get(key)));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        }
    }

    /**
     * 发送Post请求
     *
     * @param url
     * @param param
     * @return
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println(" POST" + e);
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        System.out.println(result);
        return result;
    }

    /**
     * 根据ssoToken获取人员认证后的真实xtoken
     *
     * @param url
     * @param client
     * @param login_uid
     * @param sso_key
     * @return
     */
    public String getToken(String url, String client, String login_uid, String sso_key) {
        long time = new Date().getTime();
        String xtoken = null;

        try {
            xtoken = Crypto.encrypt(login_uid + "#" + time, sso_key);
            System.out.println(xtoken);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        String string = "{\"token\": " + xtoken + ", \"client\": " + client + "}";
        String str = getInstance().sendPost(url, string);
        System.out.println("sso response: " + str);
        try {
            JsonElement jsonObj = new JsonParser().parse(str);
            if (jsonObj != null && jsonObj.getAsJsonObject().get("data") != null) {
                JsonObject data = jsonObj.getAsJsonObject().get("data").getAsJsonObject();
                System.out.println("getToken: " + data.get("token"));
                return data.get("token").getAsString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private BufferedInputStream getFileInputStream(String urlPath) {
        BufferedInputStream bin = null;
        URL url;
        try {
            url = new URL(urlPath);
            URLConnection urlConnection = url.openConnection();
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            httpURLConnection.setConnectTimeout(1000 * 5);
            httpURLConnection.setRequestMethod("GET");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.connect();
            bin = new BufferedInputStream(httpURLConnection.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bin;
    }

    private InputStream getInputStream(String urlPath) {
        InputStream bin = null;
        URL url;
        try {
            url = new URL(urlPath);
            URLConnection urlConnection = url.openConnection();
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            httpURLConnection.setConnectTimeout(1000 * 5);
            httpURLConnection.setRequestMethod("GET");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.connect();
            bin = httpURLConnection.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bin;
    }

    public static void main(String[] args) throws IOException, Exception {
        HttpClientUtilsUpfile h = new HttpClientUtilsUpfile();

        String path = "http://www.harbinxiaoshi.cn/x_organization_assemble_authentication/jaxrs/sso";
        String login_uid = "15004512051";
        String client = "dongzaixing";
        String sso_key = "Dzx123!@#";

        String tockennnn = h.getToken(path, client, login_uid, sso_key);
        System.out.println("tockennnn:" + tockennnn);
    }
}