package com.cftech.core.util;

import com.alibaba.fastjson.JSONObject;
import com.baidu.ueditor.upload.StorageManager;
import com.cftech.core.config.MpGlobalConfig;
import com.qcloud.cos.request.UploadFileRequest;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.collections.map.HashedMap;
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 org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by liuling on 16/4/23.
 */
@Slf4j
public class UploadUtils {

	private static Logger logger = LoggerFactory.getLogger(UploadUtils.class);
	// 图片目录
	public static final String USER_IMAGES_DIR = SystemConfig.p.getProperty("userfiles.imgdir");
	/**
	 * 表单字段常量
	 */
	public static final String FORM_FIELDS = "form_fields";
	/**
	 * 文件域常量
	 */
	public static final String FILE_FIELDS = "file_fields";

	/**
	 * 文件允许格式
	 */
	public static String[] ALLOW_FILE_TYPE = { ".rar", ".doc", ".docx", ".zip",
			".pdf", ".txt" };

	/**
	 * 媒体允许格式
	 */
	public static String[] ALLOW_MEDIA_TYPE = {".swf", ".wmv", ".mp4" };

	/**
	 * 图片允许格式
	 */
	public static String[] ALLOW_IMAGE_TYPE = { ".gif", ".png", ".jpg", ".jpeg",
			".bmp" };

	/**
	 * 生成新名字
	 * @param moduleName
	 * @return
	 */
	public static String getRundomName(String moduleName) {
		String res = moduleName + "" + UUID.randomUUID().toString();
		return res;
	}



	/**
	 * 上传到本地
	 */
	public static Map<String,Object> uploadMedia(Long accountsId, String moduleName, MultipartFile file, HttpServletRequest request){
		Map<String,Object> params = new HashedMap();
		BufferedInputStream bis = null;
		FileOutputStream fos = null;
		HttpURLConnection conn = null;
		String finalFileName = "";
		try {
			String dir = USER_IMAGES_DIR + accountsId;
			File ff = new File(dir);
			if (!ff.exists()) {
				ff.mkdir();
			}
			String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));//文件扩展名
			String fileName =UUID.randomUUID().toString();
			finalFileName = fileName + suffix;

			String realPath = dir + File.separator + finalFileName;
			params.put("localPath",realPath);
			File localFile = new File(realPath);
			if (!localFile.exists() && !localFile.isFile()) {
				file.transferTo(localFile);
			}
		} catch (IOException e) {
			log.error("上传文件失败：{}", e.getMessage());
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					log.error("上传文件失败 IOException：{}", e.getMessage());
				}
			}

			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					log.error("上传文件失败 IOException：{}", e.getMessage());
				}
			}

			if (conn != null) {
				conn.disconnect();
			}
		}
		String mediaUrl = ImageUrlUtils.formatImageUrl(finalFileName, accountsId.toString());//文件访问URL
		params.put("mediaUrl",mediaUrl);
		return params;
	}

	/**
	 * 获取所有的上传文件
	 * @param request
	 * @return
	 */
	//    private List<UploadFile> getFiles(HttpServletRequest request) {
	//        if (request instanceof MultipartRequest == false)
	//            request = new MultipartRequest(request);
	//        return ((MultipartRequest)request).getFiles();
	//    }

	/**
	 * 图片压缩
	 * @throws IOException
	 */
	public static String zipImage(String newFileName,FileItem item,String path) throws IOException{
		String fix = newFileName.split("\\.")[1];
		String res=null;
		UploadFileRequest uploadFileRequest = new UploadFileRequest(SystemConfig.p.getProperty("Qcloud_BUCKET_NAME"), path+newFileName, "");
		if(isFileType(newFileName,ALLOW_IMAGE_TYPE)){
			String oldMediaPath = System.getProperty("user.dir")+"\\old."+fix;
			String newMediaPath = System.getProperty("user.dir")+"\\new."+fix;
			File fosFile = new File(oldMediaPath);//暂存老文件
			OutputStream fos = new FileOutputStream(fosFile);
			byte[] receData = com.cftech.core.util.FileUtils.instreamToByte(item.getInputStream());
			fos.write(receData);
			fos.flush();
			fos.close();
			Thumbnails.of(oldMediaPath).scale(1f).outputQuality(0.3f).toFile(newMediaPath);//生成新文件
			File fis = new File(newMediaPath);
//			String res = QcloudUploadUtils.uploadStream(uploadFileRequest, item);
			InputStream stream = new FileInputStream(fis);
			receData=com.cftech.core.util.FileUtils.instreamToByte(stream);
			ByteArrayInputStream array = new ByteArrayInputStream(receData);
			String content = new String(receData,"ISO-8859-1");
			res=QcloudUploadUtils.uploadStream(uploadFileRequest, array, content);
			fosFile.delete();
			stream.close();
			fis.delete();
		}else{
			res=QcloudUploadUtils.uploadStream(uploadFileRequest, item);
		}
		return res;
	}
	public static Map<String, Object> uploadImageSingleFilesByQcloudNew(HttpServletRequest request,String prefix,String path) throws IOException {
		Map<String, Object> resultMap = new HashMap<String,Object>();
		resultMap.put("errCode", "0");//默认赋值为0
		try {
			//校验是否上传及创建没有的文件夹
			Map<String, Object> map = validateQiniuUpload(request);
			Map<String,Object> mapform=null;
			int errCode = (Integer) map.get("errCode");
			if (errCode == 0) {
				//处理上传
				List<FileItem> fileItemList = (List<FileItem>) map.get(FILE_FIELDS);
				mapform = (Map<String, Object>) map.get(FORM_FIELDS);
				boolean isPermissionMaxSize = false;
				if (fileItemList != null) {
					for(FileItem item: fileItemList) {
						if (item.getSize()/1024 < MpGlobalConfig.IMAGE_UPLOAD_MAXSIZE) {
							isPermissionMaxSize = true;
						}
					}
					//超出文件大小限制
					if (!isPermissionMaxSize) {
						errCode = 40009;
					}
					if (errCode == 0) {
						for(FileItem item: fileItemList) {
							String newFileName = getUploadFileName(item.getName(), prefix+new Date().getTime());
							String extName = getFileExt(newFileName);
							UploadFileRequest uploadFileRequest = new UploadFileRequest(SystemConfig.p.getProperty("Qcloud_BUCKET_NAME"), path+newFileName, "");
							String res = QcloudUploadUtils.uploadStreamNoUrl(uploadFileRequest, item);
							JSONObject resJson = JSONObject.parseObject(res);
							if(resJson!=null){
								if(resJson.getInteger("code")==0){
									JSONObject retObj = resJson.getJSONObject("data");
									resultMap.put("errCode",resJson.getInteger("code"));
									resultMap.put("fileUrl", retObj.get("access_url"));//CDN加速访问地址
									resultMap.put("ext",extName);
									resultMap.put("title",newFileName);
									resultMap.put("size",item.getSize());
									break;
								}else{
									resultMap.put("errCode",resJson.getInteger("code"));
								}
							}else{
								logger.info("resJson为空，程序异常");
							}
							//                           Response res = QiniuUploadUtils.uploadDiskFileItem((DiskFileItem)item,newFileName);
							//                            if (res.isJson()) {
							//                                try {
							//                                    JSONObject retObj = JSONObject.fromObject(res.bodyString());
							//                                    resultMap.put(item.getFieldName(), retObj.get("key"));
							//                                } catch (QiniuException e) {
							//                                    logger.error(e.getMessage());
							//                                }
							//                            }
						}
					}
				}
			} else {
				resultMap.put("errCode",errCode);
				resultMap.put("errMsg", ReturnCode.get(errCode));
			}
			resultMap.putAll(mapform);
		} catch (Exception e) {
			resultMap.put("errCode","-1");
			logger.error("UploadUtils上传异常！");
			e.printStackTrace();
		}

		return resultMap;
	}

	public static Map<String, Object> uploadImageSingleFilesByQcloud(HttpServletRequest request,String prefix,String path) throws IOException {
		Map<String, Object> resultMap = new HashMap<String,Object>();
		resultMap.put("errCode", "0");//默认赋值为0
		try {
			//校验是否上传及创建没有的文件夹
			Map<String, Object> map = validateQiniuUpload(request);
			Map<String,Object> mapform=null;
			int errCode = (Integer) map.get("errCode");
			if (errCode == 0) {
				//处理上传
				List<FileItem> fileItemList = (List<FileItem>) map.get(FILE_FIELDS);
				mapform = (Map<String, Object>) map.get(FORM_FIELDS);
				boolean isPermissionMaxSize = false;
				if (fileItemList != null) {
					for(FileItem item: fileItemList) {
						if (item.getSize()/1024 < MpGlobalConfig.IMAGE_UPLOAD_MAXSIZE) {
							isPermissionMaxSize = true;
						}
					}
					//超出文件大小限制
					if (!isPermissionMaxSize) {
						errCode = 40009;
					}
					if (errCode == 0) {
						for(FileItem item: fileItemList) {
							String newFileName = getUploadFileName(item.getName(), prefix+new Date().getTime());
							UploadFileRequest uploadFileRequest = new UploadFileRequest(SystemConfig.p.getProperty("Qcloud_BUCKET_NAME"), path+newFileName, "");
							String res = QcloudUploadUtils.uploadStream(uploadFileRequest, item);
							JSONObject resJson = JSONObject.parseObject(res);
							if(resJson!=null){
								if(resJson.getInteger("code")==0){
									JSONObject retObj = resJson.getJSONObject("data");
									resultMap.put("errCode",resJson.getInteger("code"));
									resultMap.put(item.getFieldName(), retObj.get("access_url"));//CDN加速访问地址
								}else{
									resultMap.put("errCode",resJson.getInteger("code"));
								}
							}else{
								logger.info("resJson为空，程序异常");
							}
							//                           Response res = QiniuUploadUtils.uploadDiskFileItem((DiskFileItem)item,newFileName);
							//                            if (res.isJson()) {
							//                                try {
							//                                    JSONObject retObj = JSONObject.fromObject(res.bodyString());
							//                                    resultMap.put(item.getFieldName(), retObj.get("key"));
							//                                } catch (QiniuException e) {
							//                                    logger.error(e.getMessage());
							//                                }
							//                            }
						}
					}
				}
			} else {
				resultMap.put("errCode",errCode);
				resultMap.put("errMsg", ReturnCode.get(errCode));
			}
			resultMap.putAll(mapform);
		} catch (Exception e) {
			resultMap.put("errCode","-1");
			logger.error("UploadUtils上传异常！");
			e.printStackTrace();
		}

		return resultMap;
	}


	/**
	 * 使用common-uploads上传图片到七牛
	 * @param request
	 * @param prefix 图片前缀,用于区分图片的上传来源
	 * @param path 上传到服务器的路径
	 * @return
	 * @throws IOException
	 */
	public static Map<String, Object> uploadImageFilesByQcloud(HttpServletRequest request,String prefix,String path) throws IOException {
		Map<String, Object> resultMap = new HashMap<String,Object>();
		resultMap.put("errCode", "0");//默认赋值为0
		try {
			//校验是否上传及创建没有的文件夹
			Map<String, Object> map = validateQiniuUpload(request);
			Map<String,Object> mapform=null;
			int errCode = (Integer) map.get("errCode");
			if (errCode == 0) {
				//处理上传
				List<FileItem> fileItemList = (List<FileItem>) map.get(FILE_FIELDS);
				mapform = (Map<String, Object>) map.get(FORM_FIELDS);
				boolean isPermissionMaxSize = false;
				if (fileItemList != null) {
					for(FileItem item: fileItemList) {
						if (item.getSize()/1024 < MpGlobalConfig.IMAGE_UPLOAD_MAXSIZE) {
							isPermissionMaxSize = true;
						}
					}
					//超出文件大小限制
					if (!isPermissionMaxSize) {
						errCode = 40009;
					}
					if (errCode == 0) {
						for(FileItem item: fileItemList) {
							String newFileName = getUploadFileName(item.getName(), prefix+new Date().getTime());
							UploadFileRequest uploadFileRequest = new UploadFileRequest(SystemConfig.p.getProperty("Qcloud_BUCKET_NAME"), path+newFileName, "");
							String res = QcloudUploadUtils.uploadStream(uploadFileRequest, item);
							JSONObject resJson = JSONObject.parseObject(res);
							if(resJson!=null){
								if(resJson.getInteger("code")==0){
									JSONObject retObj = resJson.getJSONObject("data");
									resultMap.put("errCode",resJson.getInteger("code"));
									resultMap.put(item.getFieldName(), retObj.get("access_url"));//CDN加速访问地址
								}else{
									resultMap.put("errCode",resJson.getInteger("code"));
								}
							}else{
								logger.info("resJson为空，程序异常");
							}
							//                           Response res = QiniuUploadUtils.uploadDiskFileItem((DiskFileItem)item,newFileName);
							//                            if (res.isJson()) {
							//                                try {
							//                                    JSONObject retObj = JSONObject.fromObject(res.bodyString());
							//                                    resultMap.put(item.getFieldName(), retObj.get("key"));
							//                                } catch (QiniuException e) {
							//                                    logger.error(e.getMessage());
							//                                }
							//                            }
						}
					}
				}
			} else {
				resultMap.put("errCode",errCode);
				resultMap.put("errMsg", ReturnCode.get(errCode));
			}
			resultMap.putAll(mapform);
		} catch (Exception e) {
			resultMap.put("errCode","-1");
			logger.error("UploadUtils上传异常！");
			e.printStackTrace();
		}

		return resultMap;
	}

	/**
	 * 使用common-uploads上传图片到腾讯云
	 * @param request
	 * @param prefix 图片前缀,用于区分图片的上传来源
	 * @param path 上传到服务器的路径
	 * @return
	 * @throws IOException
	 */
	public static Map<String, Object> uploadImageFilesByQcloudInputStearm(HttpServletRequest request,String prefix,MultipartFile file,String path) throws IOException {
		Map<String, Object> resultMap = new HashMap<String,Object>();
		resultMap.put("errCode", "0");//默认赋值为0
		try {
			//校验是否上传及创建没有的文件夹
			Map<String, Object> map = validateQiniuUpload(request);
			Map<String,Object> mapform=new HashMap<String, Object>();
			int errCode = (Integer) map.get("errCode");
			if (errCode == 0) {
				//处理上传
				boolean isPermissionMaxSize = false;
				if (file.getSize() < MpGlobalConfig.IMAGE_UPLOAD_MAXSIZE) {
					isPermissionMaxSize = true;
				}
				if (!isPermissionMaxSize) {
					errCode = 40009;
				}
				String newFileName = getUploadFileName(file.getOriginalFilename(), prefix+new Date().getTime());
				UploadFileRequest uploadFileRequest = new UploadFileRequest(SystemConfig.p.getProperty("Qcloud_BUCKET_NAME"), path+newFileName, "");
				byte[] receData = file.getBytes();
				ByteArrayInputStream array = new ByteArrayInputStream(receData);
				String content  = new String(receData, "ISO-8859-1");
				String res = QcloudUploadUtils.uploadStreamWithFileMeta(uploadFileRequest, array,content,file);
				JSONObject resJson = JSONObject.parseObject(res);
				if(resJson!=null){
					if(resJson.getInteger("code")==0){
						JSONObject retObj = resJson.getJSONObject("data");
						resultMap.put("errCode",resJson.getInteger("code"));
						resultMap.put("fileUrl", retObj.get("access_url"));//CDN加速访问地址
					}else{
						resultMap.put("errCode",resJson.getInteger("code"));
					}
				}else{
					logger.info("resJson为空，程序异常");
				}
			} else {
				resultMap.put("errCode",errCode);
				resultMap.put("errMsg", ReturnCode.get(errCode));
			}
			resultMap.putAll(mapform);
		} catch (Exception e) {
			resultMap.put("errCode","-1");
			logger.error("UploadUtils上传异常！");
			e.printStackTrace();
		}

		return resultMap;
	}




	public static File saveFileByInputStream(InputStream is) {
		File tmpFile = getTmpFile();
		byte[] dataBuf = new byte[ 2048 ];
		BufferedInputStream bis = new BufferedInputStream(is, StorageManager.BUFFER_SIZE);
		try {
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(tmpFile), StorageManager.BUFFER_SIZE);
			int count = 0;
			while ((count = bis.read(dataBuf)) != -1) {
				bos.write(dataBuf, 0, count);
			}
			bos.flush();
			bos.close();
		} catch (IOException e) {
		}
		return tmpFile;
	}

	private static File getTmpFile() {
		File tmpDir = FileUtils.getTempDirectory();
		String tmpFileName = (Math.random() * 10000 + "").replace(".", "");
		return new File(tmpDir, tmpFileName);
	}


	/**
	 * 校验是否有附件,是否超出文件上传限制,文件类型等
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> validateQiniuUpload(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int errCode = 0;
		// 判断请求中是否有附件
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(1024 * 1024 * 10);
			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("ISO_8859_1");
			// 设置编码为UTF-8
			//upload.setHeaderEncoding("UTF-8");
			// 最大上传限制,总量控制
			upload.setSizeMax(MpGlobalConfig.UPLOAD_MAXSIZE);
			List<FileItem> items = null;
			try {
				items = upload.parseRequest(request);
			} catch (FileUploadException e) {
				errCode = 10001;
				logger.error(e.getMessage());
			}

			if (items != null && items.size() > 0) {
				Iterator<FileItem> it = items.iterator();
				List<FileItem> list = new ArrayList<FileItem>();
				Map<String, String> fields = new HashMap<String, String>();
				while (it.hasNext()) {
					FileItem item = it.next();
					// 处理所有表单元素和文件域表单元素
					if (item.isFormField()) { // 表单元素
						String name = item.getFieldName();
						String value="";
						try {
							value = item.getString("utf-8");
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						fields.put(name, value);
					} else { // 文件域表单元素
						boolean isPermissionFileType = false;
						String fileName = item.getName();
						if (isFileType(fileName, ALLOW_FILE_TYPE) || isFileType(fileName, ALLOW_IMAGE_TYPE) || isFileType(fileName, ALLOW_MEDIA_TYPE)) {
							isPermissionFileType = true;
						}
						if (isPermissionFileType) {
							list.add(item);
						} else {
							errCode = 40005;
						}
					}
				}
				map.put(FORM_FIELDS, fields);
				map.put(FILE_FIELDS, list);
			}
		} else {
			//请求不包含multipart/form-data流
			errCode = 8001001;
		}

		map.put("errCode", errCode);
		return map;
	}

	/**
	 * 判断文件是否属于可允许的类型
	 * @param fileName
	 * @param typeArray
	 * @return
	 */
	public static boolean isFileType(String fileName, String[] typeArray) {
		for (String type : typeArray) {
			if (fileName.toLowerCase().endsWith(type)) {
				return true;
			}
		}
		return false;
	}


	/**
	 * 得到上传目录,根据文件类型不同而不同
	 * @param basePath  一般用现在的用户id
	 * @param fileName  文件名称
	 * @param time      当前的时间戳
	 * @return  上传目录
	 */
	public static String getUploadPath(String basePath,String fileName, long time) {
		SimpleDateFormat formater = new SimpleDateFormat("yyyy/MM/dd");

		String uploadBasePath = "";
		if (isFileType(fileName,ALLOW_IMAGE_TYPE)) {
			uploadBasePath = MpGlobalConfig.UPLOAD_IMAGE_DIR;
		} else if (isFileType(fileName, ALLOW_FILE_TYPE)) {
			uploadBasePath = MpGlobalConfig.UPLOAD_FILE_DIR;
		} else if (isFileType(fileName, ALLOW_MEDIA_TYPE)) {
			uploadBasePath = MpGlobalConfig.UPLOAD_MEDIA_DIR;
		} else {
			uploadBasePath = MpGlobalConfig.UPLOAD_IMAGE_DIR;
		}

		String uploadPath = basePath+"/"+ uploadBasePath + formater.format(new Date()) + "/";
		File dir = new File(uploadPath);
		if (!dir.exists()) {
			try {
				dir.mkdirs();
			} catch (Exception e) {
				e.printStackTrace();
				return "";
			}
		}
		return uploadPath;
	}

	/**
	 * 重新生成文件名称,按时间戳
	 * @param fileName
	 * @param time
	 * @return
	 */
	public static String getUploadFileName(String fileName, String time) {
		String extName = getFileExt(fileName);
		String newFileName=time + extName;

		return newFileName;
	}

	/**
	 * 初始化上传临时目录
	 * @return  上传临时目录
	 */
	public static void initUploadTempPath() {

		File dir = new File(MpGlobalConfig.TEMP_PATH);
		if (!dir.exists()) {
			try {
				dir.mkdirs();
			} catch (Exception e) {
				logger.error("init upload tempPath failure,"+e.getMessage());
			}
		}

	}

	/**
	 * 获取文件扩展名
	 *
	 * @return string
	 */
	public static String getFileExt(String fileName) {
		return fileName.substring(fileName.lastIndexOf("."));
	}

	/**
	 * 校验是否有附件,是否超出文件上传限制,文件类型等
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private Map<String, Object> validateUpload(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int errCode = 0;
		// 判断请求中是否有附件
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			DiskFileItemFactory factory = new DiskFileItemFactory();

			factory.setSizeThreshold(1024 * 1024 * 10);
			factory.setRepository(new File(MpGlobalConfig.TEMP_PATH));

			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 设置编码为UTF-8
			upload.setHeaderEncoding("UTF-8");
			// 最大上传限制,总量控制
			upload.setSizeMax(MpGlobalConfig.UPLOAD_MAXSIZE);
			List<FileItem> items = null;
			try {
				items = upload.parseRequest(request);
			} catch (FileUploadException e) {
				errCode = 10001;
				logger.error(e.getMessage());
			}

			if (items != null && items.size() > 0) {
				Iterator<FileItem> it = items.iterator();
				List<FileItem> list = new ArrayList<FileItem>();
				Map<String, String> fields = new HashMap<String, String>();
				while (it.hasNext()) {
					FileItem item = it.next();
					// 处理所有表单元素和文件域表单元素
					if (item.isFormField()) { // 表单元素
						String name = item.getFieldName();
						String value = item.getString();
						fields.put(name, value);
					} else { // 文件域表单元素
						boolean isPermissionFileType = false;
						String fileName = item.getName();
						if (isFileType(fileName, ALLOW_FILE_TYPE) || isFileType(fileName, ALLOW_IMAGE_TYPE) || isFileType(fileName, ALLOW_MEDIA_TYPE)) {
							isPermissionFileType = true;
						}
						if (isPermissionFileType) {
							list.add(item);
						} else {
							errCode = 40005;
						}
					}
				}
				map.put(FORM_FIELDS, fields);
				map.put(FILE_FIELDS, list);
			}
		} else {
			//请求不包含multipart/form-data流
			errCode = 8001001;
		}

		map.put("errCode", errCode);
		return map;
	}

	public Map<String, Object> uploadFileItem(String basePath, FileItem fileItem) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> fieldMap = new HashMap<String, String>();
		int errCode = 0;

		String fileName = fileItem.getName();
		long nowtime = new Date().getTime();
		String newFileName = getUploadFileName(fileName, String.valueOf(nowtime));
		String uploadFilePath = getUploadPath(basePath,newFileName,nowtime);

		try {
			fileItem.write(new File(uploadFilePath+newFileName));
			//增加文件上传后,文件名和字段field的对应关系
			fieldMap.put(fileItem.getFieldName(), newFileName);
		} catch (Exception e) {
			logger.error("file " + fileName + " upload failure"+ e.getMessage());
			errCode = 9001010;
		}
		map.put("errCode", errCode);
		return map;
	}

	public static void initUpload() {
		//初始化临时文件夹
		initUploadTempPath();
	}

	/**
	 * 上传文件
	 *
	 * @param request http请求
	 * @param basePath 基础目录,如果传入的是userid,则按照人员id的目录做文件的隔离
	 * @return
	 */
	public String[] upload(HttpServletRequest request, String basePath) {

		initUpload();

		String[] retStr = new String[2];
		//校验是否上传及创建没有的文件夹
		Map<String, Object> map = this.validateUpload(request);
		int errCode = (Integer) map.get("errCode");
		if (errCode == 0) {
			//处理上传
			List<FileItem> fileItemList = (List<FileItem>) map.get(FILE_FIELDS);
			if (fileItemList != null) {
				for(FileItem item: fileItemList) {

				}
			}
		} else {
			retStr[0] = "1";
			retStr[1] = ReturnCode.get(errCode);
		}

		return retStr;
	}
}
