package market.Com.pb;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

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

import market.Com.pb.fdfs.PbCode;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;



public class UploadFile  extends HttpServlet {    
	private static final long serialVersionUID = 7579265950932321867L;   
	
	 // 设置文件默认上传目录（如果你没有在web.xml中配置的话）
  private String uploadDir = "c:/"; // 文件上传目录
  private String tempUploadDir = "c:/"; // 文件临时存放目录（会话销毁后由监听器自动删除）
  
  private final String tempDate=new SimpleDateFormat("yyyyMMdd").format(new Date());
  
	/**  
   * @see HttpServlet#HttpServlet()  
   */    
  public UploadFile() {    
      super();    
  }   
  
  public void init() throws ServletException {
      // 判断目标是否存在，不存在就建立
      String uploadDir =this.getInitParameter("UploadDir");
      String tempUploadDir = this.getInitParameter("TempUploadDir");
      File f_uploadDir = new File(uploadDir);
      File f_tempUploadDir = new File(tempUploadDir);
      if (!f_uploadDir.exists()) {
          f_uploadDir.mkdirs();
      }
      if (!f_tempUploadDir.exists()) {
          f_tempUploadDir.mkdirs();
      }
      // 给变量赋值
      this.uploadDir = uploadDir;
      this.tempUploadDir = tempUploadDir;
  }
  //*/
  
  public void setDefaultValue(String optType){
	   String uploadDir="",tempUploadDir="";
	   if(optType=="default"){
		   //默认的文件管理目录
		   uploadDir=this.getInitParameter("UploadDir");
		   tempUploadDir=this.getInitParameter("TempUploadDir");
	   }else if(optType==""){
		   //知识库文件管理目录
		   uploadDir =this.getInitParameter("UploadDir");
		   tempUploadDir = this.getInitParameter("TempUploadDir");
	   }else{
		   return;
	   }
	   
	   File f_uploadDir = new File(uploadDir);
      File f_tempUploadDir = new File(tempUploadDir);
      if (!f_uploadDir.exists()) {
          f_uploadDir.mkdirs();
      }
      if (!f_tempUploadDir.exists()) {
          f_tempUploadDir.mkdirs();
      }
      // 给变量赋值
      this.uploadDir = uploadDir;
      this.tempUploadDir = tempUploadDir;
  }
  
  //*
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding("UTF-8");
        }
		
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
		MultipartHttpServletRequest mrequest = commonsMultipartResolver.resolveMultipart(request);

		String str="";
		List<String> ay=new ArrayList<String>();
		String f_path=PbCode.SvrTempDir().get("tempDir")+tempDate;
		
		try{
			StringBuffer strbuf = new StringBuffer("{\"rows\":[");
			for (Iterator<String> it = mrequest.getFileNames(); it.hasNext();) {
				String key = (String) it.next();
				MultipartFile file = mrequest.getFile(key);
				if(!file.isEmpty()){
					File f_tempdir=new File(f_path);
					if(!f_tempdir.exists())
						f_tempdir.mkdirs();
					
					String strmsec=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
					String strprefix=strmsec.substring(strmsec.length()-3)+PbCode.RandomCreate(3);
					String strname=strprefix+file.getOriginalFilename();
					File f_tempname=new File(f_path,strname);
					/*if(!f_tempname.exists())
						f_tempname.createNewFile();*/
					
					byte[] content=new byte[file.getInputStream().available()];
					file.getInputStream().read(content);
					FileOutputStream fos=new FileOutputStream(f_tempname);
					fos.write(content);
					fos.flush();
					fos.close();
					
					ay.add(PbCode.EncryptByBase64(tempDate+"/"+strname));
					
					String s_tmpName=PbCode.EncryptByBase64(tempDate+"/"+strname).replaceAll("\\n", "").replaceAll("\\r", "");
					String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
					String fileType=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
					String strshow=PbCode.SvrTempDir().get("tempDir")+"/"+tempDate+"/"+strname; 
					strbuf.append("{\"name\":\"").append(strshow).append("\",\"path\":\"").append(s_tmpName).append("\",\"filename\":\"").append(file.getOriginalFilename()).append("\",\"filetime\":\"").append(date).append("\",\"filetype\":\"").append(fileType).append("\"},");
				}
			}
			str = strbuf.toString();
            str = str.substring(0, str.length() - 1).concat("]}");
		}catch(Exception e){
			e.printStackTrace();
		}
		
		ServletOutputStream out=response.getOutputStream();
		OutputStreamWriter ow=new OutputStreamWriter(out,"UTF-8");//"GB2312");
		ow.write(str);
		ow.flush();
		ow.close();
		return;	
	}
  
  
  
  /**
   * 拼接JSON，将保存文件的文件名和日期目录返回给前端（前端可能需要这个路径完成其他表单操作，比如将文件路径存放到数据库）
   * @param result JSON格式的字符串
   * @return
   * @throws UnsupportedEncodingException
   */
  private String jointJSON (String result) throws UnsupportedEncodingException {
      String str = "";
      String date2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
      if(!"".equals(result)) {
          String rs[] = result.split(",");
          StringBuffer buffer = new StringBuffer("{\"rows\":[");
          for (int i = 0; i < rs.length; i++) {
              String s_tmpName = rs[i];
              buffer.append("{\"name\":\"").append(s_tmpName).append("\",\"filename\":\"").append(s_tmpName.substring(s_tmpName.lastIndexOf("/")+1, s_tmpName.lastIndexOf("."))).append("\",\"filetime\":\"").append(date2).append("\",\"filetype\":\"").append(s_tmpName.substring(s_tmpName.lastIndexOf("."), s_tmpName.length())).append("\"},");
          }
          str = buffer.toString();
          str = str.substring(0, str.length() - 1).concat("]}");
      } else {
          str = "{\"error\":\"-2\""; //上传失败
      }
      return str;
      //获取请求 请求包含文件的唯一标示
      //根据这个标识获取
  }

  /**
   * 设置响应类型ContentType为"application/x-json"
   * @param response
   */
  private void setResponse(HttpServletResponse response) {
      response.setCharacterEncoding("UTF-8");
      response.setContentType("application/json;charset=UTF-8");
      response.setHeader("cache-control", "no-cache");
  }  

}
