package com.sys.bus.file.controller;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Enhancer;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.upload.UploadFile;
import com.sys.bus.file.model.Attachment;
import com.sys.bus.file.service.AttachmentService;
import com.sys.core.model.DataBean;
import com.sys.core.utils.ConstUtil;
import com.sys.core.utils.Tool;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class FileController extends Controller {
	Log log = LogFactory.getLog(this.getClass());
	static AttachmentService service = Enhancer.enhance(AttachmentService.class);//需要事务处理的service，必须使用增强方法
	static String basePath = "upload"+File.separator+"jx"+File.separator;
	static String pathHead = PropKit.get("file.uploadPath");
	static{
		if(StringUtils.isBlank(pathHead)){
			 String tomcat_path = System.getProperty( "user.dir" );  
			 pathHead = tomcat_path.substring(0, tomcat_path.length()-3);
		}
	}
	/**
	 * 文件上传，只支持单文件上传
	 */
	public void upload(){
		String relationId = this.getPara("relationId");
		String title = this.getPara("title");
		//获取文件
		UploadFile file = this.getFile("file");
		int fileSize = (int)file.getFile().length()/1024;
		String attachmentName = file.getFileName();
		//获取附件新名字  
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String attachmentNewName = simpleDateFormat.format(new Date()) + Tool.uuid().substring(20) +"."+attachmentName.substring(attachmentName.lastIndexOf(".") + 1);
		//上传文件
		File upFile = new File(pathHead + basePath+attachmentNewName);
			if (!upFile.getParentFile().exists()) {
	             upFile.getParentFile().mkdirs();
	    }
		file.getFile().renameTo(upFile);
		
		//保存到附件表中
		Attachment attachment = new Attachment();
		String uuid = Tool.uuid();
		attachment.setId(uuid);
		attachment.setTitle(title);
		attachment.setAttachmentPath(basePath);
		attachment.setAttachmentName(attachmentName);
		attachment.setAttachmentNewName(attachmentNewName);
		attachment.setAttachmentSize(fileSize);
		//从session中获取username 
		attachment.setCreator((String)this.getSessionAttr(ConstUtil.SESSION_USER));
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String createTime = dateformat.format(new Date());
		attachment.setCreateTime(createTime);
		attachment.setRelationId(relationId);
		service.save(attachment);
		DataBean dataBean = new DataBean();

		dataBean.setCode(0);
		JSONObject j = new JSONObject();
		j.put("attachmentName", file.getFileName());
		j.put("attachmentSize",fileSize);
		j.put("createTime", createTime);
		j.put("attachmentId",uuid);
		j.put("attachmentNewName", attachmentNewName);
		dataBean.setJsonText(j.toString());
		this.renderJson("json",dataBean);
	}

	/**
	 * 文件下载
	 */
	public void download() {//文件下载
		String attachmentNewName = this.getPara("attachmentNewName");
	    File file = new File(pathHead + basePath + attachmentNewName);
	    if (file.exists()) { //如果文件存在
	        renderFile(file);
	    }else{
	    	throw new RuntimeException("文件不存在");
	    }
	    
	}
	/**
	 * 删除附件
	 */
	public void delete(){
		String attachmentId = this.getPara("attachmentId");
		//获取newname    删除文件
		Attachment attachment = service.getByAttachmentId(attachmentId);
		service.deleteAttachmentById(attachmentId);
		String attachmentNewName = attachment.getAttachmentNewName();
	    File file = new File(pathHead + basePath + attachmentNewName);
	    if(file.exists() && file.isFile()){  
	    	file.delete();  
	    }  
		DataBean dataBean = new DataBean();
		dataBean.setCode(0);
		this.renderJson("json",dataBean);
	}
	
	/**
	 * 附件列表
	 */
	public void list(){
		String relationId = this.getPara("relationId"); 
		List<Attachment> list = service.listByRelationId(relationId);
		DataBean dataBean = new DataBean();
		dataBean.setCount(list.size());
		dataBean.setData(list);
		this.renderJson("json",dataBean);
		
		
	}
}
