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

import java.io.File;
import java.net.URLDecoder;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.myapps.common.data.ParamsTable;
import cn.myapps.common.exception.OBPMValidateException;
import cn.myapps.common.util.StringUtil;
import cn.myapps.constans.Web;
import cn.myapps.designtime.common.service.DesignTimeServiceManager;
import cn.myapps.designtime.form.service.FormDesignTimeService;
import cn.myapps.runtime.common.controller.AbstractRuntimeController;
import cn.myapps.runtime.common.service.RunTimeServiceManager;
import cn.myapps.runtime.dynaform.document.ejb.Document;
import cn.myapps.runtime.dynaform.document.ejb.DocumentProcess;
import cn.myapps.runtime.dynaform.form.ejb.Form;
import cn.myapps.runtime.dynaform.upload.ejb.UploadInfo;
import cn.myapps.runtime.dynaform.upload.ejb.UploadProcess;
import cn.myapps.runtime.dynaform.upload.ejb.UploadVO;

@Controller
@RequestMapping("/api/portal/upload")
public class UploadAct extends AbstractRuntimeController{
	
	private static final long serialVersionUID = 6865609097678926341L;
	
	@Autowired
	private HttpServletRequest request;
	
	

	private String applicationid;

	private static final Logger Log = LoggerFactory.getLogger(UploadAct.class);

	private File upload;

	private String uploadContentType;

	private String uploadFileName;

	private String path;

	private String id;

	private String viewid;

	private String uploadList_;

	private String fieldValue;

	private String newUploadFileName;

	private String webPath;

	private String allowedTypes;

	private String[] fileName;

	private double perc;

	private String layer;

	private String fileSaveMode = UploadInfo.FILE_SAVE_MODE_SYSTEM;

	private File[] file;

	private String fileFullName;

	public String getFileFullName() {
		return fileFullName;
	}

	public void setFileFullName(String fileFullName) {
		this.fileFullName = fileFullName;
	}

	public String getUploadList_() {
		return uploadList_;
	}

	public void setUploadList_(String uploadList_) {
		this.uploadList_ = uploadList_;
	}

	public String getFieldValue() {
		return fieldValue;
	}

	public void setFieldValue(String fieldValue) {
		this.fieldValue = fieldValue;
	}

	private int maximumSize = Integer.MAX_VALUE;

	private static final String IMAGE_TYPES[] = { "image/png", "image/gif",
			"image/jpeg", "image/pjpeg", "image/bmp", "application/pdf" };

	public double getPerc() {
		return perc;
	}

	public void setPerc(double perc) {
		this.perc = perc;
	}

	public String getLayer() {
		return layer;
	}

	public void setLayer(String layer) {
		this.layer = layer;
	}

	public String getViewid() {
		return viewid;
	}

	public void setViewid(String viewid) {
		this.viewid = viewid;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public int getMaximumSize() {
		return maximumSize;
	}

	public void setMaximumSize(int maximumSize) {
		this.maximumSize = maximumSize;
	}

	public String getAllowedTypes() {
		return allowedTypes;
	}

	public void setAllowedTypes(String allowedTypes) {
		this.allowedTypes = allowedTypes;
	}

	public String getWebPath() {
		return webPath;
	}

	public void setWebPath(String webPath) {
		this.webPath = webPath;
	}

	public String getPath() throws Exception {
		return this.path;
	}

	public void setPath(String path) throws Exception {
		this.path = path;
	}

	public String getNewUploadFileName() {
		return newUploadFileName;
	}

	public void setNewUploadFileName(String newUploadFileName) {
		this.newUploadFileName = newUploadFileName;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public File[] getFile() {
		return file;
	}

	public void setFile(File[] file) {
		this.file = file;
	}

	public void setFileName(String[] fileName) {
		this.fileName = fileName;
	}

	public String[] getFileName() {
		return fileName;
	}
	
	public String getFileSaveMode() {
		return fileSaveMode;
	}

	public void setFileSaveMode(String fileSaveMode) {
		this.fileSaveMode = fileSaveMode;
	}
	
	public String getApplicationid() {
		return applicationid;
	}

	public void setApplicationid(String applicationid) {
		this.applicationid = applicationid;
	}
	
	public ParamsTable getParams(HttpServletRequest request) {
		ParamsTable pm = ParamsTable.convertHTTP(request);

		// put the domain id to parameters table.
		if (getDomain() != null)
			pm.setParameter("domainid", getDomain());

		// put the page line count id to parameters table.
		if (pm.getParameter("_pagelines") == null)
			pm.setParameter("_pagelines", Web.DEFAULT_LINES_PER_PAGE);

		return pm;
	}
	
	/**
	 * 重新构建文档
	 * 
	 * @param doc
	 * @param params
	 * @return
	 */
	protected Document rebuildDocument(Document doc, ParamsTable params) {
		String formid = params.getParameterAsString("_formid");
		try {
			if (!StringUtil.isBlank(doc.getId()) && !StringUtil.isBlank(formid)) {
				FormDesignTimeService formPross = DesignTimeServiceManager.formDesignTimeService();
				Form form = (Form) formPross.doView(formid);
				doc = form.createDocument(doc, params, getUser());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return doc;
	}
	
	@RequestMapping("/delete.action")
	public String doDelete() {
		HttpServletRequest request = this.request;
		ParamsTable params = ParamsTable.convertHTTP(request);
		String docid = params.getParameterAsString("_docid");
		try {
			if (!StringUtil.isBlank(fileFullName)) {
				fileFullName = URLDecoder.decode(fileFullName, "UTF-8");
				UploadProcess uploadProcess = RunTimeServiceManager.uploadProcess(this.applicationid);
				String[] fileFullNameArry = fileFullName.split(";");
				for (int i = 0; i < fileFullNameArry.length; i++) {
					String fileFullName = fileFullNameArry[i];
					UploadVO uploadVO = null;
					if (!StringUtil.isBlank(fileFullName)
							&& fileFullName.indexOf("_/uploads") > 0) {
						String fileId = fileFullName.substring(0,
								fileFullName.indexOf("_/uploads"));
						uploadVO = (UploadVO) uploadProcess.doView(fileId);
					} else {
						uploadVO = (UploadVO) uploadProcess.findByColumnName1(
								"PATH", fileFullName);
					}

					if (uploadVO != null) {
						String fileRealPath = request.getServletContext().getRealPath(
								uploadVO.getPath());
						File file = new File(fileRealPath);
						if (file.exists()) {
							if (!file.delete()) {
								Log.warn("File(" + fileRealPath
										+ ") delete failed");
								throw new OBPMValidateException("File("
										+ fileRealPath + ") delete failed");
							}
						}
						uploadProcess.doRemove(uploadVO.getId());

						// 删除上传文件时，更新文档
						if (!StringUtil.isBlank(applicationid)) {
							DocumentProcess docProcess = RunTimeServiceManager.documentProcess(applicationid);
							if (!StringUtil.isBlank(docid)) {
								Document doc = (Document) docProcess
										.doView(docid);
								if (doc != null) {
									doc = rebuildDocument(doc, params);
									docProcess.doUpdate(doc, false, false);
								}
							}
						}

					}
				}
			}
		} catch (Exception e) {
			/*e.printStackTrace();
			addFieldError("", e.getMessage());
			return NONE;*/
			request.setAttribute("ERROR_MESSAGE", e.getMessage());
			return "NONE";
			
		}
		/*return NONE;*/
		return "forward:/core/upload/success.jsp";
	}
	
	/**
	 * 删除一个文件
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/deleteOne.action")
	public String doDeleteOne() throws Exception {
		HttpServletRequest request = this.request;
		ParamsTable params = ParamsTable.convertHTTP(request);
		String docid = params.getParameterAsString("_docid");
		if (!StringUtil.isBlank(fileFullName)) {
			fileFullName = URLDecoder.decode(fileFullName, "UTF-8");
			UploadProcess uploadProcess = RunTimeServiceManager.uploadProcess(this.applicationid);
			UploadVO uploadVO = null;
			if (!StringUtil.isBlank(fileFullName)
					&& fileFullName.indexOf("_/uploads") > 0) {
				String fileId = fileFullName.substring(0,
						fileFullName.indexOf("_/uploads"));
				uploadVO = (UploadVO) uploadProcess.doView(fileId);
			} else {
				uploadVO = (UploadVO) uploadProcess.findByColumnName1("PATH",
						fileFullName);
			}
			if (uploadVO != null) {
				String fileRealPath = request.getServletContext().getRealPath(
						uploadVO.getPath());
				File file = new File(fileRealPath);
				if (file.exists()) {
					if (!file.delete()) {
						Log.warn("File(" + fileRealPath + ") delete failed");
						throw new OBPMValidateException("File(" + fileRealPath
								+ ") delete failed");
					}
				}
				uploadProcess.doRemove(uploadVO.getId());

				// 删除上传文件时，更新文档
				if (!StringUtil.isBlank(applicationid)) {
					DocumentProcess docProcess = RunTimeServiceManager.documentProcess(applicationid);
					if (!StringUtil.isBlank(docid)) {
						Document doc = (Document) docProcess.doView(docid);
						if (doc != null) {
							doc = rebuildDocument(doc, params);
							docProcess.doUpdate(doc, false, false);
						}
					}
				}

			}
		}
		return "";
	}
}
