package cn.net.caoyao.cpzshandset.common.util;

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

import android.util.Log;


public class UpCarPicture {
	private static UpCarPicture uploadUtil;
	private static final String BOUNDARY = UUID.randomUUID().toString(); // 边界标识
																			// 随机生成
	private static final String PREFIX = "--"; // 字段的开始标识符 必须是--
	private static final String LINE_END = "\r\n"; // 字段的结束标示符 必须是 \r\n
	private static final String CONTENT_TYPE = "multipart/form-data"; // 内容类型
	private UpCarPicture() {

	}
	/**
	 * 单例模式获取上传工具类
	 * 
	 * @return
	 */
	public static UpCarPicture getInstance() {
		if (null == uploadUtil) {
			uploadUtil = new UpCarPicture();
		}
		return uploadUtil;
	}

	private static final String TAG = "UploadUtil";
	private int readTimeOut = 10 * 1000; // 读取超时
	private int connectTimeout = 10 * 1000; // 超时时间
	private static int requestTime = 0; // 请求使用多长时间
	private static final String CHARSET = "utf-8"; // 设置编码

	public static final int SUCCESS = 1; // 上传成功
	// 文件不存在
	public static final int NOFILE = 0;
	// 服务器出错
	public static final int SERVERERROR = 4;

	private OnUploadProcessListener onUploadProcessListener;

	public void setOnUploadProcessListener(OnUploadProcessListener onUploadProcessListener) {
		this.onUploadProcessListener = onUploadProcessListener;
	}

	/**
	 * android上传文件到服务器
	 * 
	 * @param filePath
	 *            需要上传的文件的路径
	 * @param fileKey
	 *            在网页上<input type=file name=xxx/> xxx就是这里的fileKey
	 * @param RequestURL
	 *            请求的URL
	 */
	public void uploadFile(String filePrefix,String filePath, String fileKey, String RequestURL) {
		if (filePath == null) {
			onUploadProcessListener.onUploadDone(NOFILE, "文件不存在");
			return;
		}
		try {
			File file = new File(filePath);
			uploadFile(filePrefix,file, fileKey, RequestURL);
		} catch (Exception e) {
			onUploadProcessListener.onUploadDone(NOFILE, "文件不存在");
			e.printStackTrace();
			return;
		}
	}

	/**
	 * android上传文件到服务器
	 * 
	 * @param file
	 *            需要上传的文件
	 * @param fileKey
	 *            在网页上<input type=file name=xxx/> xxx就是这里的fileKey
	 * @param RequestURL
	 *            请求的URL
	 */
	public void uploadFile(String filePrefix,final File file, final String fileKey, final String RequestURL) {
		if (file == null || (!file.exists())) {
			onUploadProcessListener.onUploadDone(NOFILE, "文件不存在");
			return;
		}

		/*
		 * Log.i(TAG, "请求的URL=" + RequestURL); Log.i(TAG, "请求的fileName=" +
		 * file.getName()); Log.i(TAG, "请求的fileKey=" + fileKey);
		 */
		// new Thread(new Runnable() { // 开启线程上传文件
		//
		// public void run() {
		// // Looper.prepare();
		// toUploadFile(file, fileKey, RequestURL, param);
		// // Looper.loop();
		// }
		// }).start();
		toUploadFile(filePrefix,file, fileKey, RequestURL);

	}

	private void toUploadFile(String filePrefix, File file, String fileKey, String RequestURL) {
		String result = null;
		requestTime = 0;

		try {
			URL url = new URL(RequestURL);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(readTimeOut);
			conn.setConnectTimeout(connectTimeout);
			conn.setDoInput(true); // 允许输入流
			conn.setDoOutput(true); // 允许输出流
			conn.setUseCaches(false); // 不允许使用缓存
			conn.setRequestMethod("POST"); // 请求方式
			conn.setRequestProperty("Charset", CHARSET); // 设置编码
			conn.setRequestProperty("connection", "keep-alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

			// 当文件不为空，把文件包装并且上传
			DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

			// 当文件不为空，把文件包装并且上传
			StringBuffer sb = new StringBuffer();
			String params = "";

			/**
			 * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
			 * filename是文件的名字，包含后缀名的 比如:abc.png
			 */
			sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
			sb.append("Content-Disposition:form-data; name=\"" + fileKey + "\"; filename=\"" + filePrefix+"_"+file.getName() + "\""
					+ LINE_END);
			sb.append("Content-Type:image/jpeg" + LINE_END); // 这里配置的Content-type很重要的
																// ，用于服务器端辨别文件的类型的
			sb.append(LINE_END);
			Log.i(TAG,sb.toString());
			params = sb.toString();
			sb = null;

			Log.i(TAG, file.getName() + "=" + params + "##");
			dos.write(params.getBytes());
			
			/** 上传文件 */
			InputStream is = new FileInputStream(file);
			onUploadProcessListener.initUpload((int) file.length());
			byte[] bytes = new byte[1024];
			int len = 0;
			int curLen = 0;
			while ((len = is.read(bytes)) != -1) {
				curLen += len;
				dos.write(bytes, 0, len);
				onUploadProcessListener.onUploadProcess(curLen);
			}
			is.close();

			dos.write(LINE_END.getBytes());
			byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
			dos.write(end_data);
			dos.flush();
			// dos.write(tempOutputStream.toByteArray());

			// 获取响应码 200=成功 当响应成功，获取响应的流
			int res = conn.getResponseCode();

			// this.requestTime = (int) ((responseTime-requestTime)/1000);
			Log.e(TAG, "服务器返回response code:" + res);
			if (res == 200) {
				Log.e(TAG, "提交成功");
				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);
				onUploadProcessListener.onUploadDone(SUCCESS, result);
				return;
			} else {
				Log.e(TAG, "request error");
				onUploadProcessListener.onUploadDone(SERVERERROR, "上传失败：code=" + res);
				return;
			}
		} catch (MalformedURLException e) {
			onUploadProcessListener.onUploadDone(SERVERERROR, "上传失败：error=" + e.getMessage());
			e.printStackTrace();
			return;
		} catch (IOException e) {
			onUploadProcessListener.onUploadDone(SERVERERROR, "上传失败：error=" + e.getMessage());
			e.printStackTrace();
			return;
		}
	}
}
