package com.zcloud.controller.study;

import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.logs.LogAnno;
import com.zcloud.service.study.MfolderStipulateService;
import com.zcloud.util.*;
import net.sf.json.JSONArray;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;

/**
 * 说明：文件管理
 * 作者：zCloud
 * 官网：
 */
@Controller
@RequestMapping("/app/mfolderStipulate")
public class AppMfolderStipulateController extends BaseController {

	@Autowired
	private MfolderStipulateService mfolderService;
	@Autowired
	private Smb smb;
	/**创建目录
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/add")
	// @RequiresPermissions("mfolderStipulate:add")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "文件管理",instructionsOperate = "文件管理",instructionsType = "创建目录")
	public Object add() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("MFOLDER_ID", this.get32UUID());			//主键
		pd.put("FILEPATH", "");							//路径
		pd.put("CTIME", DateUtil.date2Str(new Date()));	//创建时间
		pd.put("UNAME", Jurisdiction.getName());		//上传者
		pd.put("MASTER", Jurisdiction.getUsername());	//所属人
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业
		pd.put("FILESIZE", "");
		mfolderService.save(pd);
		map.put("result", errInfo);
		return map;
	}

	/**上传文件
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/upload")
	// @RequiresPermissions("mfolderStipulate:add")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "文件管理",instructionsOperate = "文件管理",instructionsType = "上传文件")
	public Object add(
			@RequestParam(value="FFILE",required=false) MultipartFile file) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String  ffile = DateUtil.getDays(), fileName = "";
		if (null != file && !file.isEmpty()) {
			File tempFile = new File(file.getOriginalFilename()); //新建file
			FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile); //将MultipartFile复制到File
			fileName = this.get32UUID()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			smb.sshSftp(file, fileName, Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile);
			pd.put("FILEPATH", Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile + "/" + fileName);			//文件路径
			//pd.put("NAME", NAME);							//文件名
			//pd.put("PARENT_ID", PARENT_ID);					//目录ID
			pd.put("CTIME", DateUtil.date2Str(new Date()));	//创建时间
			pd.put("UNAME", Jurisdiction.getName());		//上传者,当前用户的姓名
			pd.put("MASTER", Jurisdiction.getUsername());	//用户名
			pd.put("FILESIZE", FileUtil.getFilesize(tempFile));	//文件大小
			//pd.put("REMARKS", REMARKS);						//备注
			//pd.put("SHARE", SHARE);							//是否共享
			//pd.put("TYPE", TYPE);							//数据类型 1.文件夹   2.文件

			pd.put("MFOLDER_ID", this.get32UUID());			//主键
			pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业
			mfolderService.save(pd);						//存入数据库表

			FileUtils.deleteQuietly(tempFile);//删除临时文件
		}else{
			errInfo = "error";
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**上传文件
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/editUpload")
	// @RequiresPermissions("mfolderStipulate:add")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "文件管理",instructionsOperate = "文件管理",instructionsType = "上传文件")
	public Object editUpload(
			@RequestParam(value="FFILE",required=false) MultipartFile file) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String  ffile = DateUtil.getDays(), fileName = "";
		if (null != file && !file.isEmpty()) {
			File tempFile = new File(file.getOriginalFilename()); //新建file
			FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile); //将MultipartFile复制到File
			fileName = this.get32UUID()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			smb.sshSftp(file, fileName, Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile);
			pd.put("FILEPATH", Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile + "/" + fileName);			//文件路径
			//pd.put("NAME", NAME);							//文件名
			//pd.put("PARENT_ID", PARENT_ID);					//目录ID
			pd.put("UNAME", Jurisdiction.getName());		//上传者,当前用户的姓名
			pd.put("MASTER", Jurisdiction.getUsername());	//用户名
			pd.put("FILESIZE", FileUtil.getFilesize(tempFile));	//文件大小
			//pd.put("REMARKS", REMARKS);						//备注
			//pd.put("SHARE", SHARE);							//是否共享
			//pd.put("TYPE", TYPE);							//数据类型 1.文件夹   2.文件

			pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业
			FileUtils.deleteQuietly(tempFile);//删除临时文件
		}
		mfolderService.edit(pd);						//存入数据库表
		map.put("result", errInfo);				//返回结果
		return map;
	}


	 /**去修改页面获取数据
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/goEdit")
	// @RequiresPermissions("mfolderStipulate:edit")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "文件管理",instructionsOperate = "文件管理",instructionsType = "去修改页面获取数据")
	public Object goEdit() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd = mfolderService.findById(pd);	//根据ID读取
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	/**上传文件
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/uploadAll")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "文件管理",instructionsOperate = "文件管理",instructionsType = "上传文件")
	public Object uploadAll(
			@RequestParam(value="file",required=false) MultipartFile file,
			@RequestParam(value="FH_ID",required=false) String MFOLDER_ID
			) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		String  ffile = DateUtil.getDays(), fileName = "";
		if (null != file && !file.isEmpty()) {
			File tempFile = new File(file.getOriginalFilename()); //新建file
			FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile); //将MultipartFile复制到File
    		fileName = this.get32UUID()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		 	smb.sshSftp(file, fileName, Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile);
			pd.put("FILEPATH", Const.FILEPATHFILE + Jurisdiction.getCORPINFO_ID() + "/" + ffile + "/" + fileName);			//文件路径
			String realName = file.getOriginalFilename();
			String[] fileFullNames = realName.split("\\.");//上传文件全名
			String extension =fileFullNames[fileFullNames.length-1];//上传文件文件后缀
			String realName2 =realName.substring(0,realName.length()-extension.length()-1); //去除文件后缀名称
			pd.put("NAME", realName2);				//文件名
			pd.put("PARENT_ID", MFOLDER_ID);				//目录ID
			pd.put("CTIME", DateUtil.date2Str(new Date()));	//创建时间
			pd.put("UNAME", Jurisdiction.getName());		//上传者,当前用户的姓名
			pd.put("MASTER", Jurisdiction.getUsername());	//用户名
			pd.put("FILESIZE", FileUtil.getFilesize(tempFile));	//文件大小
			pd.put("REMARKS", "无");							//备注
			pd.put("SHARE", "no");							//是否共享
			pd.put("MFOLDER_ID", this.get32UUID());			//主键
			pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业
			mfolderService.save(pd);						//存入数据库表

			FileUtils.deleteQuietly(tempFile);//删除临时文件
		}else{
			errInfo = "error";
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}
	/**删除
	 * @param out
	 * @throws Exception
	 */
	@RequestMapping(value="/delete")
	// @RequiresPermissions("mfolderStipulate:del")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "文件管理",instructionsOperate = "文件管理",instructionsType = "删除")
	public Object delete(@RequestParam String MFOLDER_ID, @RequestParam String FILEPATH) throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd.put("parentId", MFOLDER_ID);
		if(mfolderService.listByParentId(pd).size() > 0){		//判断是否有子级，是：不允许删除
			errInfo = "error";
		}else{
			pd.put("MFOLDER_ID", MFOLDER_ID);
			mfolderService.delete(pd);
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**修改
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/edit")
	// @RequiresPermissions("mfolderStipulate:edit")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "文件管理",instructionsOperate = "文件管理",instructionsType = "修改")
	public Object edit() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		mfolderService.edit(pd);
		map.put("result", errInfo);
		return map;
	}

	/**列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/list")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "文件管理",instructionsOperate = "文件管理",instructionsType = "列表")
	public Object list(Page page) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		//pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业
		String KEYWORDS = pd.getString("KEYWORDS");								//关键词检索条件
		if(Tools.notEmpty(KEYWORDS))pd.put("KEYWORDS", KEYWORDS.trim());
		String MFOLDER_ID = null;
		if( pd.get("MFOLDER_ID")!=null && Tools.notEmpty( pd.get("MFOLDER_ID").toString())) {
			MFOLDER_ID = null == pd.get("MFOLDER_ID")?"":pd.get("MFOLDER_ID").toString();
			pd.put("MFOLDER_ID", MFOLDER_ID);										//当作上级ID
		}

//		if(Tools.notEmpty(SHARE) && "yes".equals(SHARE)) {
//			pd.put("SHARE", "yes");
//		}else {
//			pd.put("USERNAME", "admin".equals(Jurisdiction.getUsername())?"":Jurisdiction.getUsername()); //除admin用户外，只能查看自己的数据
//		}
		pd.put("SHARE", "yes");
		page.setPd(pd);
		List<PageData>	varList = mfolderService.list(page);					//列出Mfolder列表
		if(MFOLDER_ID==null || "0".equals(MFOLDER_ID)) {
			map.put("PARENT_ID", "0");											//上级ID
		}else {
			map.put("PARENT_ID", mfolderService.findById(pd).getString("PARENT_ID"));	//上级ID
		}
		for(int i=0;i<varList.size();i++){
			String FILEPATH = varList.get(i).getString("FILEPATH");
			if(Tools.isEmpty(FILEPATH))break;
			String extension_name =  FILEPATH.substring(59, FILEPATH.length());//文件拓展名
			String fileType = "file";
			int zindex1 = "java,php,jsp,html,css,txt,asp".indexOf(extension_name);
			if(zindex1 != -1){
				fileType = "wenben";	//文本类型
			}
			int zindex2 = "jpg,gif,bmp,png".indexOf(extension_name);
			if(zindex2 != -1){
				fileType = "tupian";	//图片文件类型
			}
			int zindex3 = "rar,zip,rar5".indexOf(extension_name);
			if(zindex3 != -1){
				fileType = "yasuo";		//压缩文件类型
			}
			int zindex4 = "doc,docx".indexOf(extension_name);
			if(zindex4 != -1){
				fileType = "doc";		//doc文件类型
			}
			int zindex5 = "xls,xlsx".indexOf(extension_name);
			if(zindex5 != -1){
				fileType = "xls";		//xls文件类型
			}
			int zindex6 = "ppt,pptx".indexOf(extension_name);
			if(zindex6 != -1){
				fileType = "ppt";		//ppt文件类型
			}
			int zindex7 = "pdf".indexOf(extension_name);
			if(zindex7 != -1){
				fileType = "pdf";		//ppt文件类型
			}
			int zindex8 = "fly,f4v,mp4,m3u8,webm,ogg,avi".indexOf(extension_name);
			if(zindex8 != -1){
				fileType = "video";		//视频文件类型
			}
			varList.get(i).put("extension_name", extension_name);	//文件拓展名
			varList.get(i).put("fileType", fileType);				//用于文件图标
		}
		map.put("varList", varList);
		map.put("page", page);
		map.put("result", errInfo);
		return map;
	}

	/**
	 * 显示列表ztree
	 * @return
	 */
	@RequestMapping(value="/listTree")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "文件管理",instructionsOperate = "文件管理",instructionsType = "显示列表")
	public Object listTree()throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String SHARE = pd.getString("SHARE");
		/*if(!(Tools.notEmpty(SHARE) && "yes".equals(SHARE))) {
			pd.put("USERNAME", "admin".equals(Jurisdiction.getUsername())?"":Jurisdiction.getUsername()); //除admin用户外，只能查看自己的数据
		}*/
		pd.put("parentId", "0");
		pd.put("SHARE", SHARE);
		//pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业
		JSONArray arr = JSONArray.fromObject(mfolderService.listTree(pd,SHARE));
		String json = arr.toString();
		json = json.replaceAll("MFOLDER_ID", "id").replaceAll("PARENT_ID", "pId").replaceAll("NAME", "name").replaceAll("subMfolder", "nodes").replaceAll("hasMfolder", "checked").replaceAll("treeurl", "url");
		map.put("zTreeNodes", json);
		map.put("result", errInfo);
		return map;
	}

	/**
	 * app显示列表ztree
	 * @return
	 */
	@RequestMapping(value="/appListTree")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "文件管理",instructionsOperate = "文件管理",instructionsType = "显示列表")
	public Object appListTree()throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String SHARE = pd.getString("SHARE");
		/*if(!(Tools.notEmpty(SHARE) && "yes".equals(SHARE))) {
			pd.put("USERNAME", "admin".equals(Jurisdiction.getUsername())?"":Jurisdiction.getUsername()); //除admin用户外，只能查看自己的数据
		}*/
		pd.put("parentId", "0");
		pd.put("SHARE", SHARE);
		//pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业
		if(Tools.isEmpty(pd.getString("KEYWORDS"))){
			JSONArray arr = JSONArray.fromObject(mfolderService.appListTree(pd,SHARE));
			String json = arr.toString();
			json = json.replaceAll("MFOLDER_ID", "id").replaceAll("PARENT_ID", "pId").replaceAll("NAME", "title").replaceAll("subMfolder", "children").replaceAll("hasMfolder", "checked").replaceAll("treeurl", "url");
			map.put("zTreeNodes", json);
		} else {
			List<PageData> varList = mfolderService.findByName(pd);
			map.put("varList", varList);
		}

		map.put("result", errInfo);
		return map;
	}


	 /**批量操作
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/makeAll")
	// @RequiresPermissions("mfolderStipulate:edit")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "文件管理",instructionsOperate = "文件管理",instructionsType = "批量操作")
	public Object deleteAll() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String DATA_IDS = pd.getString("DATA_IDS");
		if(Tools.notEmpty(DATA_IDS)){
			String ArrayDATA_IDS[] = DATA_IDS.split(",");
			pd.put("IDS", ArrayDATA_IDS);
			mfolderService.makeAll(pd);
			errInfo = "success";
		}else{
			errInfo = "error";
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**下载
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value="/download")
	@LogAnno(menuType= "手机",menuServer= "文件管理",instructionsOperate = "文件管理",instructionsType = "下载")
	public void download(HttpServletResponse response)throws NofileStiException {
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			pd = mfolderService.findById(pd);
			String FILEPATH = pd.getString("FILEPATH");
//			String fileName = pd.getString("NAME");
			FileDownload.mfFileDownload(response, Const.HTTPFILEURL + FILEPATH, FILEPATH.substring(FILEPATH.length()<85?27:60, FILEPATH.length()));
		} catch (Exception e) {
			throw new NofileStiException("=========要下载的文件已经没有了=========");
		}
	}

	/**listByParentId
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value="/listByParentId")
	@ResponseBody
	public Object listByParentId()throws NofileStiException {
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String KEYWORDS = pd.getString("KEYWORDS");								//关键词检索条件
		if(Tools.notEmpty(KEYWORDS))pd.put("KEYWORDS", KEYWORDS.trim());
		List<PageData> varList = new ArrayList<PageData>();
		try {
			varList = mfolderService.listAll(pd);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}					//列出Mfolder列表
		for(int i=0;i<varList.size();i++){
			String FILEPATH = varList.get(i).getString("FILEPATH");
			if(Tools.isEmpty(FILEPATH))break;
			String extension_name =  FILEPATH.substring(59, FILEPATH.length());//文件拓展名
			String fileType = "file";
			int zindex1 = "java,php,jsp,html,css,txt,asp".indexOf(extension_name);
			if(zindex1 != -1){
				fileType = "wenben";	//文本类型
			}
			int zindex2 = "jpg,gif,bmp,png".indexOf(extension_name);
			if(zindex2 != -1){
				fileType = "tupian";	//图片文件类型
			}
			int zindex3 = "rar,zip,rar5".indexOf(extension_name);
			if(zindex3 != -1){
				fileType = "yasuo";		//压缩文件类型
			}
			int zindex4 = "doc,docx".indexOf(extension_name);
			if(zindex4 != -1){
				fileType = "doc";		//doc文件类型
			}
			int zindex5 = "xls,xlsx".indexOf(extension_name);
			if(zindex5 != -1){
				fileType = "xls";		//xls文件类型
			}
			int zindex6 = "ppt,pptx".indexOf(extension_name);
			if(zindex6 != -1){
				fileType = "ppt";		//ppt文件类型
			}
			int zindex7 = "pdf".indexOf(extension_name);
			if(zindex7 != -1){
				fileType = "pdf";		//ppt文件类型
			}
			int zindex8 = "fly,f4v,mp4,m3u8,webm,ogg,avi".indexOf(extension_name);
			if(zindex8 != -1){
				fileType = "video";		//视频文件类型
			}
			varList.get(i).put("extension_name", extension_name);	//文件拓展名
			varList.get(i).put("fileType", fileType);				//用于文件图标
		}
		map.put("varList", varList);
		map.put("result", errInfo);
		return map;
	}
}
