package cn.base.servlet;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.stream.FileImageOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.log4j.Logger;

import cn.base.bean.BeanHelper;
import cn.base.tinyftp.TinyFtpCfgInfo;
import cn.base.util.FTPUrl;
import cn.base.util.FTPUtil;
import cn.base.util.RHUtil;
import cn.base.util.StringUtil;
import net.sf.json.JSONObject;



public class UploadNhywCpxh extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger iLog = Logger.getLogger(UploadNhywCpxh.class);
	private static FTPUrl ftp = null;
	
	
	public UploadNhywCpxh() {
		super();
	}
	 
	public void destroy() {
		super.destroy(); 
	}

	 
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}
	
	public void byte2image(byte[] data,String path){
	    if(data.length<3||path.equals("")) return;//判断输入的byte是否为空
	    try{
		    FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));//打开输入流
		    imageOutput.write(data, 0, data.length);//将byte写入硬盘
		    imageOutput.close();
		    System.out.println("Make Picture success,Please find image in " + path);
	    } catch(Exception ex) {
	      ex.printStackTrace();
	    }
	}
	 
	 public static byte[] readStream(InputStream inStream) throws Exception{	
		    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		    byte[] buffer = new byte[1024];	  
		    int len = -1;	
		    while((len = inStream.read(buffer)) != -1){	  
		      outStream.write(buffer, 0, len);	  
		    }	  
		    outStream.close();	  
		    inStream.close();
		    return outStream.toByteArray();	  
	}
	 
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");  
		DiskFileUpload fu = new DiskFileUpload();
//		fu.setHeaderEncoding("utf-8");
		fu.setSizeMax(60000000);
		fu.setSizeThreshold(40960);
			
		System.out.println(request.getParameterMap());
		 
		//下载全地址
		try {
			java.util.List<FileItem> fileItems = fu.parseRequest(request);
			JSONObject  json = new JSONObject ();
			if(RHUtil.isNotEmpty(fileItems)) {
				ftp = getFtpConfig();
				String path = "nhyw/cpxh";
				boolean flag = true;
				List<String> list = new ArrayList();
				for(int i=0; i<fileItems.size(); i++) {
					FileItem file = fileItems.get(i);					
					if (file.getName() != null && !file.isFormField()) {     // 是否有文件上传
						String fileName = file.getName();
					//	System.out.println("这是第"+i+"个文件："+fileName);
						// 写入本地测试
					//	byte2image(readStream(file.getInputStream()),"D:\\logback\\"+fileName);
						
						String uuid = StringUtil.getUUID();
						String suf = fileName.substring(fileName.lastIndexOf("."));
						String fileUrl ="ftp://"+ftp.getFtpUser()+":"+ftp.getFtpUserPassword()+"@"+ ftp.getFtpIp()+":"+ftp.getFtpPort()+"/"+path+"/"+uuid;
						//		System.out.println("文件路径："+fileUrl);
						String wjlj = fileUrl+suf;
						String kz1 = null;
						String outPath = null;
						
						flag = FTPUtil.uploadFile(ftp, path, uuid+suf, file.getInputStream());
						if(flag) {
							json.put("flag", "success");
						}else {
							json.put("flag", "fail");
						}
						json.put("url"+i, wjlj);
					}else {
						json.put("url"+i, "");
					}
				}
				
			}
			response.getWriter().write(json.toString());
			response.getWriter().flush();
			
		} catch (Exception e) {
			iLog.error("文件上传失败", e);
			try {
				response.getWriter().write("!");
				response.getWriter().flush();
			} catch (Exception ex) {
			}
		}
	}

	public FTPUrl getFtpConfig() throws Exception {
		if (ftp == null) {
			List<TinyFtpCfgInfo> list = BeanHelper.getModuleConfFactory().getFtps().getimpywTinyFtpCfgInfoList();
			if(RHUtil.isNotEmpty(list)) {
				TinyFtpCfgInfo tfci = list.get(0);
				String ip = tfci.getFtpServerHost();
				String port = tfci.getFtpServerPort();
				String user = tfci.getLoginName();
				String password = tfci.getLoginPasword();
				ftp = new FTPUrl(ip,Integer.parseInt(port),user,password);
			}			
		}
		return ftp;
	}

}
