package cn.myapps.runtime.dynaform.upload.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import cn.myapps.common.Environment;
import cn.myapps.common.util.StringUtil;
import cn.myapps.util.sequence.Sequence;
import net.sf.json.JSONObject;

/**
 * Servlet implementation class Upload
 */
public class CommonUploadServlet extends HttpServlet {


	/**
	 * 
	 */
	private static final long serialVersionUID = -2707998202343005461L;

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	}

	/**
	 * 文件上传请求调用的方法
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @throws Exception
	 */
	public void processRequest(HttpServletRequest request,
			HttpServletResponse response)

	throws Exception {
		try {
			String uuid = request.getParameter("uuid");
			String path = request.getParameter("path");
			if(StringUtil.isBlank(uuid)){
				uuid = Sequence.getSequence();
			}
			Calendar calendar = Calendar.getInstance();
			int year = calendar.get(Calendar.YEAR);
			int month = calendar.get(Calendar.MONTH) + 1;
			int date = calendar.get(Calendar.DATE);
			// 获得文件保存的真实路径
			String savePath = Environment.getInstance().getRealPath("");
			// 拼接好文件要保存的真实文件夹   
			// /updoads/{path}/{year}/{month}/{date}/ 的形式
			StringBuffer rPath = new StringBuffer();//网站的相对路径
			rPath.append("uploads").append(File.separator).append(path)
					.append(File.separator).append(year).append(File.separator)
					.append(month).append(File.separator).append(date);

			// 生成文件
			File f1 = new File(savePath + rPath);
			// 如果该文件夹不存在则创建
			if (!f1.exists()) {
				if (!f1.mkdirs()) {
					throw new IOException("Failed to create folder ("
							+ savePath + ")");
				}
			}
			// 磁盘文件个项工厂
			DiskFileItemFactory fac = new DiskFileItemFactory();
			// servlet文件上传
			ServletFileUpload upload = new ServletFileUpload(fac);
			// 设置上传编码
			upload.setHeaderEncoding("utf-8");
			List<?> fileList = null;// 文件列表
			try {
				request.setCharacterEncoding("UTF-8");
				fileList = upload.parseRequest(request);// 获得列表
			} catch (FileUploadException ex) {
				throw ex;
			}
			Iterator<?> it = fileList.iterator();
			String extName = "";// 文件扩展名
			while (it.hasNext()) {
				FileItem item = (FileItem) it.next();
				if (!item.isFormField()) {
					if (item.getName().indexOf(".") > -1) {
						extName = item.getName().substring(
								item.getName().lastIndexOf("."));
					}
					try {
						rPath.append(File.separator).append(uuid).append(extName).toString();
						File saveFile = new File(savePath + rPath);
						item.write(saveFile);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

			}
			JSONObject result = new JSONObject();
			result.put("path",rPath.toString());
			// 解决中文乱码返回网络路径
			response.setContentType("text/html;charset=UTF-8");
			response.getWriter().print(result.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			processRequest(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			processRequest(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
