package com.sybotan.android.demo.tools;

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

import cn.hutool.core.util.IdUtil;

/**
 * Created by 何鑫欣 on 2017/8/8.
 */

public class UploadImage {
    private static final String TAG = "uploadFile";
    private static final int TIME_OUT = 10 * 10000000; // 超时时间
    private static final String CHARSET = "utf-8"; // 设置编码
    public static final String SUCCESS = "1";
    public static final String FAILURE = "0";

    public static final int UPLOAD_RECORD_SUCCESS = 0x122;
    public static final int UPLOAD_SUCCESS = 0x123;
    public static final int UPLOAD_FAIL = 0x124;
    public static final int UPlOAD_RECORD_FAIL = 0X125;

    public static final int DOWNLOAD_SUCCESS = 0x126;
    public static final int DOWNLOAD_FAIL = 0x127;

    public static final int READ_FROM_CACHE = 0x128;
    public static final int READ_FROM_INTERNET = 0x129;
    private static String result;

    public static String uploadFile(File file, String imageUrl) {
        String BOUNDARY = IdUtil.simpleUUID(); // 边界标识 随机生成
        String PREFIX = "--", LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; // 内容类型
        String RequestURL = imageUrl;
        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoInput(true); // 允许输入流
            conn.setDoOutput(true); // 允许输出流
            conn.setUseCaches(false); // 不允许使用缓存
            conn.setRequestMethod("POST"); // 请求方式
            conn.setRequestProperty("Charset", CHARSET); // 设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="
                    + BOUNDARY);
            if (file != null) {
                /**
                 * 当文件不为空，把文件包装并且上传
                 */
                OutputStream outputSteam = conn.getOutputStream();

                DataOutputStream dos = new DataOutputStream(outputSteam);
                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                /**
                 * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
                 * filename是文件的名字，包含后缀名的 比如:abc.png
                 */

                sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""
                        + file.getName() + "\"" + LINE_END);
                sb.append("Content-Type: application/octet-stream; charset="
                        + CHARSET + LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = is.read(bytes)) != -1) {
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
                        .getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                 * 获取响应码 200=成功 当响应成功，获取响应的流
                 */
                int res = conn.getResponseCode();
                if (res == 200) {
                    return SUCCESS;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FAILURE;
    }

    public static String uploadFile1(File file, String imageUrl) {
        String TAG = "uploadFile";
        int TIME_OUT = 10 * 10000000; // 超时时间
        String CHARSET = "utf-8"; // 设置编码
        String SUCCESS = "1";
        String FAILURE = "0";
        String BOUNDARY = IdUtil.simpleUUID(); // 边界标识 随机生成
        String PREFIX = "--", LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; // 内容类型
        String RequestURL = imageUrl;
        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoInput(true); // 允许输入流
            conn.setDoOutput(true); // 允许输出流
            conn.setUseCaches(false); // 不允许使用缓存
            conn.setRequestMethod("POST"); // 请求方式
            conn.setRequestProperty("Charset", CHARSET); // 设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
            /**
             * 当文件不为空，把文件包装并且上传
             *  何鑫欣  13:58:50
             */

            if (file != null) {
                DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                /**
                 * 这里重点注意： name里面的值为服务端需要key 只有这个key 才可以得到对应的文件
                 * filename是文件的名字，包含后缀名的 比如:abc.png
                 */
                sb.append("Content-Disposition: form-data; name=\"" + "ht" + "\"; filename=\""
                        + file.getName() + "\"" + LINE_END);
                //"Content-Type: application/octet-stream; charset=" + CHARSET
                sb.append("Content-Type:imagepeg" + LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = is.read(bytes)) != -1) {
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
                        .getBytes();
                dos.write(end_data);
                dos.flush();
                Log.e("======", "====flush===");

                /**
                 * 获取响应码 200=成功 当响应成功，获取响应的流
                 */
                int res = conn.getResponseCode();
                Log.e("========", "response code:" + res);
                if (res == 200) {
                    Log.e(TAG, "request success");
                    InputStream input = conn.getInputStream();
                    StringBuffer sb1 = new StringBuffer();
                    int ss;
                    while ((ss = input.read()) != -1) {
                        sb1.append((char) ss);
                    }
                    result = sb1.toString();
                    Log.e(TAG, "result : " + result);
                    return result;
                } else {
                    Log.e(TAG, "request error");
                }

            }

        } catch (Exception e) {

        }
        return result;
    }


    /**
     * @param file 要上传的文件
     * @return true if upload success else false
     * @throws IOException
     */
    public static String uploadFiles(File file, String url) {
        String result = "";
        Log.e("url", "--------" + url);
        try {
//            HttpClient client = new DefaultHttpClient();// 开启一个客户端 HTTP 请求
//            HttpPost post = new HttpPost(url);//创建 HTTP POST 请求
//
//            //MultipartEntity对象，需要httpmime-4.1.1.jar文件。
//            MultipartEntity multipartEntity = new MultipartEntity();
//            //filesPath为List<String>对象，里面存放的是需要上传的文件的地址
//            ContentBody fi = new FileBody(file);
//            multipartEntity.addPart("file", fi);
//
//            post.setEntity(multipartEntity);//设置请求参数

            // 将文件将其转换为io流
            InputStream inputStream = new FileInputStream(file);
            // 定义一个字节数组封装io流
            byte[] b = new byte[inputStream.available()];
            // 将io读入到数组中
            inputStream.read(b);
            ByteArrayEntity mEntitys = new ByteArrayEntity(b);

            HttpClient httpclient = HttpClientBuilder.create().build();// 开启一个客户端 HTTP 请求
            url = url.replaceAll(" ", "%20");
            HttpPost httpPost = new HttpPost(url);
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(50000)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(50000)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(50000)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();
            httpPost.setConfig(requestConfig);
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            // 设置请求的的参数
            httpPost.setEntity(mEntitys);
            HttpResponse response = httpclient.execute(httpPost);// 发起请求 并返回请求的响应
            Log.e("state_Http", String.valueOf(response.getStatusLine().getStatusCode()));

            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entit11 = response.getEntity();

                if (entit11 != null) {
                    result = EntityUtils.toString(entit11, "utf-8");
                    Log.e(TAG, "uploadFiles: " + result);
                }
                return result;
            } else {
                result = "网络异常，请检查网络后重试";
            }
        } catch (Exception e) {
            result = "网络异常，请检查网络后重试";
            e.printStackTrace();

        }
        return result;
    }
}
