package org.jeecg.modules.stm.doc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;


import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;

import org.jeecg.modules.stm.doc.entity.DocFilesDir;
import org.jeecg.modules.stm.doc.service.IDocFilesDirService;
import org.jeecg.modules.system.model.TreeSelectModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import org.jeecg.modules.stm.doc.service.IDocFilesService;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: 文件分类
 * @Author: jeecg-boot
 * @Date:   2024-05-17
 * @Version: V1.0
 */

@RestController
@RequestMapping("/doc/docFilesDir")
@Slf4j
public class DocFilesDirController extends JeecgController<DocFilesDir, IDocFilesDirService> {
	@Autowired
	private IDocFilesDirService docFilesDirService;
	@Autowired
	private IDocFilesService docFilesService;
	private Map<Integer,Integer> ctpFileCntMap = new HashMap<>();
	/**
	 * 分页列表查询
	 *
	 * @param docFilesDir
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "文件分类-分页列表查询")

	@GetMapping(value = "/list")
	public Result<IPage<DocFilesDir>> queryPageList(DocFilesDir docFilesDir,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		if(oConvertUtils.isEmpty(docFilesDir.getPid())){
			docFilesDir.setPid(0);
		}
		QueryWrapper<DocFilesDir> queryWrapper = QueryGenerator.initQueryWrapper(docFilesDir, req.getParameterMap());
		Page<DocFilesDir> page = new Page<DocFilesDir>(pageNo, pageSize);
		IPage<DocFilesDir> pageList = docFilesDirService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param docFilesDir
	 * @return
	 */
	@AutoLog(value = "文件分类-添加")

	@RequiresPermissions("doc:doc_files_dir:add")
	@PostMapping(value = "/add")
	public Result<DocFilesDir> add(@RequestBody DocFilesDir docFilesDir) {
		Result<DocFilesDir> result = new Result<DocFilesDir>();
		Integer pid = docFilesDir.getPid();
		if(docFilesDir.getPid()==0) {
			DocFilesDir parentFilesDir = new DocFilesDir();
			parentFilesDir.setId(0);
			parentFilesDir.setCode("");
			String strCode = createCurNodeCode(parentFilesDir);
			docFilesDir.setCode(strCode);

		} else {
			DocFilesDir parentFilesDir = docFilesDirService.getById(docFilesDir.getPid());
			if(parentFilesDir.getHasChild() == 0 ) {
				parentFilesDir.setHasChild(1);
				docFilesDirService.updateById(parentFilesDir);
			}
			String strCode = createCurNodeCode(parentFilesDir);
			docFilesDir.setCode(strCode);
		}
		docFilesDir.setHasChild(0);
		if(docFilesDir.getInd()==null) {
			docFilesDir.setInd(createCurNodeInd(pid));
		}
		docFilesDir.setBuiltin(0);
		docFilesDirService.save(docFilesDir);
		result.setResult(docFilesDir);
		result.success("添加成功");
		return result;
	}
	
	/**
	 *  编辑
	 *
	 * @param docFilesDir
	 * @return
	 */
	@AutoLog(value = "文件分类-编辑")

	@RequiresPermissions("doc:doc_files_dir:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<DocFilesDir> edit(@RequestBody DocFilesDir docFilesDir) {
		Result<DocFilesDir> result = new Result<DocFilesDir>();
		docFilesDirService.updateById(docFilesDir);
		result.setResult(docFilesDir);
		result.success("编辑成功");
		return result;
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "文件分类-通过id删除")

	@RequiresPermissions("doc:doc_files_dir:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {

		docFilesDirService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "文件分类-批量删除")

	@RequiresPermissions("doc:doc_files_dir:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.docFilesDirService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "文件分类-通过id查询")

	@GetMapping(value = "/queryById")
	public Result<DocFilesDir> queryById(@RequestParam(name="id",required=true) String id) {
		DocFilesDir docFilesDir = docFilesDirService.getById(id);
		if(docFilesDir==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(docFilesDir);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param docFilesDir
    */
    @RequiresPermissions("doc:doc_files_dir:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, DocFilesDir docFilesDir) {
        return super.exportXls(request, docFilesDir, DocFilesDir.class, "文件分类");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("doc:doc_files_dir:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, DocFilesDir.class);
    }

	@GetMapping(value = "/treeList")
	public Result<List<TreeSelectModel>> treeList(DocFilesDir docFilesDir,
													HttpServletRequest req) {
		QueryWrapper<DocFilesDir> queryWrapper = new QueryWrapper<>();
		String[]  orderAry = {"pid","ind"};
		queryWrapper.orderByAsc(Arrays.asList(orderAry));
		List<DocFilesDir> dirList = docFilesDirService.list(queryWrapper);
		this.ctpFileCntMap = this.getNodeFileCount();
		List<TreeSelectModel> ret = buildTree(dirList);
		traverseTree(ret);
		return Result.OK(ret);
	}

	@RequestMapping(value = "/loadTreeData", method = RequestMethod.GET)
	public Result<List<TreeSelectModel>> loadTreeData(@RequestParam(name="pid",required = false) String pid,@RequestParam(name="pcode",required = false) String pcode, @RequestParam(name="condition",required = false) String condition) {
		QueryWrapper<DocFilesDir> queryWrapper = new QueryWrapper<>();
		queryWrapper.orderByAsc("ind");
		List<DocFilesDir> dirList = docFilesDirService.list(queryWrapper);
		List<TreeSelectModel> ret = buildTree(dirList);
		return Result.OK(ret);
	}

	@GetMapping(value = "/childList")
	public Result<List<DocFilesDir>> queryPageList(DocFilesDir docFilesDir,HttpServletRequest req) {
		Result<List<DocFilesDir>> result = new Result<List<DocFilesDir>>();
		QueryWrapper<DocFilesDir> queryWrapper = QueryGenerator.initQueryWrapper(docFilesDir, req.getParameterMap());
		List<DocFilesDir> list = docFilesDirService.list(queryWrapper);
		result.setSuccess(true);
		result.setResult(list);
		return result;
	}

	@GetMapping("/getChildListBatch")
	public Result getChildListBatch(@RequestParam("parentIds") String parentIds) {
		try {
			QueryWrapper<DocFilesDir> queryWrapper = new QueryWrapper<>();
			List<String> parentIdList = Arrays.asList(parentIds.split(","));
			queryWrapper.in("pid", parentIdList);
			List<DocFilesDir> list = docFilesDirService.list(queryWrapper);
			IPage<DocFilesDir> pageList = new Page<>(1, 10, list.size());
			pageList.setRecords(list);
			return Result.OK(pageList);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error("批量查询子节点失败：" + e.getMessage());
		}
	}

	@GetMapping("/changeTreeNodeOrder")
	public Result changeTreeNodeOrder(@RequestParam("tid") Integer tid, @RequestParam("cid") Integer cid,
									  @RequestParam("isfolder") Boolean isfolder) {
		try {
			DocFilesDir targetDocDir = docFilesDirService.getById(tid);
			DocFilesDir newFilesDir = docFilesDirService.getById(cid);
			//boolean isPlus = targetDocDir.getInd()<newFilesDir.getInd();
			Integer pid = isfolder ? targetDocDir.getId() : targetDocDir.getPid();
			int stInd = isfolder ? 1 : targetDocDir.getInd()+1;
			QueryWrapper<DocFilesDir> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("pid", pid).ne("id", cid).ne("id",tid).ge("ind", stInd);
			queryWrapper.orderByAsc("ind");

			List<DocFilesDir> list = docFilesDirService.list(queryWrapper);
			newFilesDir.setPid(pid);
			newFilesDir.setInd(stInd);
			docFilesDirService.updateById(newFilesDir);

			for (DocFilesDir docFilesDir : list) {
				docFilesDir.setInd(docFilesDir.getInd()+1);
			}
			docFilesDirService.saveOrUpdateBatch(list);

			return Result.OK();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error("保存失败：" + e.getMessage());
		}
	}



	private List<TreeSelectModel> buildTree(List<DocFilesDir> dataList) {

		Map<Integer, TreeSelectModel> map = new HashMap<>();
		List<TreeSelectModel> rootList = new ArrayList<>();
		for (DocFilesDir node : dataList) {
			TreeSelectModel treeNode = DocNode2TreeNode(node);
			map.put(node.getId(),treeNode);
			Integer fileCnt = this.ctpFileCntMap.get(node.getId());

			if (node.getPid() == 0) {
				rootList.add(treeNode);
			} else {
				Integer pid = node.getPid();
				Integer cid = node.getId();
				TreeSelectModel parent = map.get(pid);
				if (parent != null) {
					if(parent.getChildren()==null){
						parent.setChildren(new ArrayList<>());
					}
					int pcnt = this.ctpFileCntMap.get(pid)==null?0:this.ctpFileCntMap.get(pid);
					int ccnt = this.ctpFileCntMap.get(cid)==null?0:this.ctpFileCntMap.get(cid);
					this.ctpFileCntMap.put(pid,pcnt+ccnt);
					parent.getChildren().add(treeNode);
				}
			}
		}
		return rootList;
	}

	private TreeSelectModel DocNode2TreeNode(DocFilesDir docNode){
		TreeSelectModel treeNode = new TreeSelectModel();
		treeNode.setTitle(docNode.getName());
		treeNode.setLeaf(false);

		//treeNode.setBuiltin(docNode.getBuiltin());
		treeNode.setParentId(docNode.getPid().toString());
		treeNode.setCode(docNode.getCode());
		treeNode.setKey(docNode.getId().toString());
		//treeNode.setOtherData("label",docNode.getLabelNames());
		return treeNode;
	}

	private String createCurNodeCode(DocFilesDir parentDir){
		QueryWrapper<DocFilesDir> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("pid",parentDir.getId()).orderByDesc("code");
		List<DocFilesDir> list  = docFilesDirService.list(queryWrapper);
		String strCode = null;
		if(list==null||list.size()==0) {
			strCode = parentDir.getCode()+"10";
		} else {
			strCode = getSameLeveCode(list.get(0).getCode());
		}
		return strCode;
	}

	private String getSameLeveCode(String strCode){
		String strCode1 = strCode.substring(0, strCode.length()-2);
		String strCode2 = strCode.substring(strCode.length()-2);
		Integer newCode = Integer.valueOf(strCode2) +1;
		strCode = strCode1 + newCode.toString();
		return  strCode;
	}

	private Map<Integer,Integer> getNodeFileCount(){
		List<Map<String,Object>> list = docFilesService.queryCtpFileCount();
		Map<Integer,Integer> retMap = new HashMap<>();
		for(Map<String,Object> tmpMap:list){
			Object ctpObj = tmpMap.get("ctp");
			Object cntObj = tmpMap.get("cnt");
			if(cntObj!=null && ctpObj!=null) {
				retMap.put(Integer.parseInt(ctpObj.toString()),Integer.parseInt(cntObj.toString()));
			} else {

			}

		}
		return retMap;
	}

	private void traverseTree(List<TreeSelectModel> treeList) {
		for (TreeSelectModel node : treeList) {
			Integer id = Integer.parseInt(node.getKey());
			Integer pid = Integer.parseInt(node.getParentId());
			Integer fileCnt = this.ctpFileCntMap.get(id);
			if(fileCnt!=null&&fileCnt>0){
				//node.setOtherData("cnt",fileCnt);
			}
			if (node.getChildren() != null && !node.getChildren().isEmpty()) {
				traverseTree(node.getChildren()); // 递归遍历子节点
			}
		}
	}

	private Integer createCurNodeInd(Integer pid){
		QueryWrapper<DocFilesDir> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("pid",pid).orderByDesc("ind");
		List<DocFilesDir> list  = docFilesDirService.list(queryWrapper);
		Integer ind = list!=null&&list.size()>0?list.get(0).getInd()+1:1;
		return ind;
	}
}
