package com.steerinfo.ems.tmcdocdirectory.controller;

import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.Utils.TreeUtils;
import com.steerinfo.ems.tcm0317.mapper.TCm0317Mapper;
import com.steerinfo.ems.tcm0317.service.ITCm0317Service;
import com.steerinfo.ems.tmcdocdirectory.model.TMcDocdirectory;
import com.steerinfo.ems.tmcdocdirectory.service.ITMcDocdirectoryService;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TMcDocdirectory RESTful接口：
 * @author generator
 * @version 1.0-SNAPSHORT 2019-10-30 10:40
 * 类描述
 * 修订历史：
 * 日期：2019-10-30
 * 作者：generator
 * 参考：
 * 描述：TMcDocdirectory RESTful接口
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@RestController
@RequestMapping("/${api.version}/tmcdocdirectorys")
public class TMcDocdirectoryController extends BaseRESTfulController {

    private static final Logger LOGGER = LoggerFactory.getLogger(TMcDocdirectoryController.class);

    @Autowired
    ITMcDocdirectoryService tMcDocdirectoryService;
    
    @Autowired
    private TCm0317Mapper tCm0317Mapper;
    
    /** 文件保存路径  */
	public static final String FILE_DIR = "/static/";

    @ApiOperation(value="创建", notes="根据TMcDocdirectory对象创建")
    @ApiImplicitParam(name = "tMcDocdirectory", value = "详细实体tMcDocdirectory", required = true, dataType = "TMcDocdirectory")
    //@RequiresPermissions("tmcdocdirectory:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@ModelAttribute TMcDocdirectory model){
        if(tMcDocdirectoryService.getById(model.getItemcode()) != null){
            return failed(null, "目录名不能重复");
        }
        if(model.getPath() == null || "".equals(model.getPath())){
            model.setPath("文档目录/");
        }
        if(!model.getPath().endsWith("/")){
            model.setPath(model.getPath() + "/");
        }
        try {
            model.setPath(model.getPath() + model.getItemcode());
            // 文档目录地址
            String folderpath = FILE_DIR + model.getPath();
            // 如果目录不存在，自动创建
            File dir = new File(folderpath);
            if (dir.exists()) {
                LOGGER.error("新建失败,此目录下已存在该文件夹！");
                return failed(null, "新建失败,此目录下已存在！");
            } else {
                dir.mkdirs();
                List<String> pathlist = Arrays.asList(model.getPath().split("\\\\"));
                if (pathlist.size() >= 2) {
                    model.setParentId(pathlist.get(pathlist.size() - 2));
                }
                TMcDocdirectory tMcDocdirectory = tMcDocdirectoryService.add(model);
                return success(tMcDocdirectory, "新建目录文件夹成功！");
            }
        } catch (Exception e) {
            LOGGER.error("新建目录失败," + e);
            return failed(null, "新建目录失败," + e);
        }
    }

    @ApiOperation(value="更新详细信息", notes="根据url的itemcode来指定更新对象，并根据传过来的newcode,path,note信息来更新详细信息")
    //@RequiresPermissions("tmcdocdirectory:update")
    @PutMapping(value = "/", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@RequestParam HashMap params){
    	TMcDocdirectory model = new TMcDocdirectory();
    	String itemcode = params.get("itemcode").toString(); // 原目录
    	String newcode = params.get("newcode").toString(); // 新目录
        if(tMcDocdirectoryService.getById(params.get("newcode").toString()) != null && !itemcode.equalsIgnoreCase(newcode)){
            return failed(null, "已存在该文件名");
        } else{
            try {
            	// 只改目录描述
            	if(itemcode.equalsIgnoreCase(newcode)) {
            		model = tMcDocdirectoryService.update(params);
            	}else{
            		TMcDocdirectory old = tMcDocdirectoryService.getById(itemcode);
            		String oldPath = old.getPath();
            		File file = new File(FILE_DIR + oldPath);  //修改前的文件路径
                    //获取修改后的文件路径
                    String newpath = oldPath.substring(0, oldPath.lastIndexOf("/")) + "/" + newcode;
                    //对指定目录重命名
                    file.renameTo(new File(FILE_DIR + newpath));
                    params.put("path", newpath);
                    model = tMcDocdirectoryService.update(params);
            	}
                return success(model);
            } catch (Exception e){
                LOGGER.error("修改目录失败," + e);
                return failed(null, "修改目录失败," + e);
            }
        }
    }

    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("tmcdocdirectory:delete")
    @DeleteMapping(value = "/{id}")
    public RESTfulResult delete(@PathVariable String id){
        TMcDocdirectory model = tMcDocdirectoryService.getById(id);
        try {
        	if(model!=null){
        		Map<String,Object> params =  new HashMap<>();
                params.put("parentcode", model.getPath());
                if (!tCm0317Mapper.selectByParameters(params).isEmpty()) {
                	return failed(null,"此文件目录下已存在文件,请先删除文件！");
                }
                File file = new File(FILE_DIR + model.getPath());
                if(file.exists()){
                	if(!file.delete()){
                		return failed(null,"此文件目录下已存在目录或者文件,请先删除");
                	}
                }
                tMcDocdirectoryService.delete(id);
                return success();
        	} else {
        		return failed(null,"目录信息不存在");
        	}
        } catch (Exception e){
            LOGGER.error("删除目录失败," + e);
            return failed(null,"删除目录失败," + e);
        }
    }

    @ApiOperation(value="获取树状数据", notes="获取TRmWorkproc的树形数据")
    @GetMapping(value = "/gettree/")
    public RESTfulResult getTree(){
        TreeUtils treeUtils = new TreeUtils();
        List<TMcDocdirectory> list = tMcDocdirectoryService.getTree();
        return success(treeUtils.getTreeData(list));
    }

    @ApiOperation(value="获取列表")
    //@RequiresPermissions("tmcdocdirectory:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas){
        List<TMcDocdirectory> list = tMcDocdirectoryService.query(parmas);
        return success(list);
    }


/**
 @ApiOperation(value="获取列表", notes="分页查询")
 @ApiImplicitParams({
 @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
 @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
 })
 //@RequiresPermissions("tmcdocdirectory:view")
 @GetMapping(value = "/")
 public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
 PageList<TMcDocdirectory> list = tMcDocdirectoryService.queryForPage(parmas, pageNum, pageSize);
 return success(list);
 }

 @ApiOperation(value="获取列表", notes="分页模糊查询")
 @ApiImplicitParams({
 @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
 @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
 })
 //@RequiresPermissions("tmcdocdirectory:view")
 @GetMapping(value = "/like/")
 public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
 PageList<TMcDocdirectory> list = tMcDocdirectoryService.queryLikeForPage(parmas, pageNum, pageSize);
 return success(list);
 }

 @ApiOperation(value="获取详细信息", notes="根据url的id来获取详细信息")
 @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
 //@RequiresPermissions("tmcdocdirectory:view")
 @GetMapping(value = "/{id}")
 public RESTfulResult get(@PathVariable String id){
 TMcDocdirectory tMcDocdirectory = tMcDocdirectoryService.getById(id);
 return success(tMcDocdirectory);
 }
 */
}
