package cn.base.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
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.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.Doc2HtmlUtil;
import cn.base.util.FTPUrl;
import cn.base.util.FTPUtil;
import cn.base.util.FileUtils;
import cn.base.util.RHUtil;
import cn.base.util.StringUtil;
import net.sf.json.JSONObject;



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

	 
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}
	

	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);
			
		 
		//下载全地址
		try {
			java.util.List<FileItem> fileItems = fu.parseRequest(request);
			Date dateNow = new Date();
			for (FileItem files : fileItems) {
				if (files.getName() != null && !files.isFormField()) {
					String fileName = files.getName();
					String path = "nhyw/xmwd";
					ftp = getFtpConfig();
					String uuid = StringUtil.getUUID();
					int len = fileName.lastIndexOf(".");
					String suf = fileName.substring(len);
			//		String fileUrl ="ftp://"+ftp.getFtpUser()+":"+ftp.getFtpUserPassword()+"@"+ ftp.getFtpIp()+":"+ftp.getFtpPort()+"/"+path+"/"+uuid+suf;
					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;
					if(".html".equals(suf)||".txt".equals(suf)||".pdf".equals(suf)) {
						kz1 = wjlj;
					}else {						
						String rootPath = BeanHelper.getModuleConfFactory().getScatter().getDownPath();
							
						//文件转换成 html格式					
						String changeFileName = Doc2HtmlUtil.file2Html(files.getInputStream(), rootPath,suf,".pdf");
						outPath = rootPath+File.separator+changeFileName;
		//				System.out.println("生成的html文件: "+outPath);
						FTPUtil.uploadFile(ftp, path, uuid+".pdf", new FileInputStream(outPath));
						kz1 = fileUrl+".pdf";						
					}
					
					boolean flag = FTPUtil.uploadFile(ftp, path, uuid+suf, files.getInputStream());		
					
					System.out.println("生成的html文件: "+kz1);
					
					//System.out.println("生成的html文件: "+htmlUrl);
					if(RHUtil.isNotEmpty(outPath)) {
						FileUtils.delFile(outPath);
					}
					
					
					JSONObject  json = new JSONObject ();
					json.put("fileUrl", wjlj);
					json.put("fileName", fileName);
					json.put("kz1", kz1);
					if(flag) {
						json.put("flag", "success");
					}else {
						json.put("flag", "fail");
					}
					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 void init(ServletConfig config) throws ServletException {
		String charset = config.getInitParameter("character");
	    System.out.println(charset);
	}

	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;
	}

	

}
