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.modules.stm.doc.entity.DocFiles;
import org.jeecg.modules.stm.doc.entity.DocFilesHistory;
import org.jeecg.modules.stm.doc.service.IDocFilesDirService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.jeecg.modules.stm.base.domain.service.IStDomainService;
import org.jeecg.modules.stm.base.lable.entity.StLable;
import org.jeecg.modules.stm.base.lable.service.IStLableService;
import org.jeecg.modules.stm.doc.service.IDocFilesHistoryService;
import org.jeecg.modules.stm.doc.service.IDocFilesService;

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

  
@RestController
@RequestMapping("/doc/docFiles")
@Slf4j
public class DocFilesController extends JeecgController<DocFiles, IDocFilesService> {
	@Autowired
	private IDocFilesService docFilesService;
	@Autowired
	private IStLableService stLableService;
	@Value(value = "${jeecg.path.upload}")
	private String uploadpath;
	@Autowired
	private IStDomainService stDomainService;
	@Autowired
	private IDocFilesDirService docFilesDirService;
	@Autowired
	private IDocFilesHistoryService docFilesHistoryService;

	//@AutoLog(value = "文档管理-分页列表查询")
	  
	@GetMapping(value = "/list")
	public Result<IPage<DocFiles>> queryPageList(DocFiles docFiles,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<DocFiles> queryWrapper = QueryGenerator.initQueryWrapper(docFiles, req.getParameterMap());
		Page<DocFiles> page = new Page<DocFiles>(pageNo, pageSize);
		IPage<DocFiles> pageList = docFilesService.page(page, queryWrapper);
		List<String> domainCodeList = new ArrayList<>();
		StringBuffer labelCodeSb  = new StringBuffer();
		for (DocFiles docFile : pageList.getRecords()) {
			String domainCode = docFile.getDomainCode();
			String lableCode = docFile.getLabels();
			if(domainCode!=null &&!domainCode.equals("")) {
				domainCodeList.add(domainCode);
			}
			if(lableCode!=null &&!lableCode.equals("")) {
				labelCodeSb.append(",").append(lableCode);
			}
		}

		return Result.OK(pageList);
	}

	@GetMapping(value = "/queryAllList")
	public Result<List<DocFiles>> queryAllList(DocFiles docFiles, HttpServletRequest req) {
		QueryWrapper<DocFiles> queryWrapper = QueryGenerator.initQueryWrapper(docFiles, req.getParameterMap());
		List<DocFiles> dataList = docFilesService.list(queryWrapper);
		List<String> domainCodeList = new ArrayList<>();
		StringBuffer labelCodeSb  = new StringBuffer();
		for (DocFiles docFile : dataList) {
			String domainCode = docFile.getDomainCode();
			String lableCode = docFile.getLabels();
			if(domainCode!=null &&!domainCode.equals("")) {
				domainCodeList.add(domainCode);
			}
			if(lableCode!=null &&!lableCode.equals("")) {
				labelCodeSb.append(",").append(lableCode);
			}
		}

		return Result.OK(dataList);
	}

	@AutoLog(value = "文档管理-添加")
	  
	@RequiresPermissions("doc:doc_files:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody DocFiles docFiles) {
		if(checkFileExist(docFiles)){
			return Result.error("文件名称重复!，保存失败");
		}
		if(docFiles.getInd()==null) {
			docFiles.setInd(0);
		}
		docFilesService.save(docFiles);
		return Result.ok();
	}

	@AutoLog(value = "文档管理-编辑")
	  
	@RequiresPermissions("doc:doc_files:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody DocFiles docFiles) {

		DocFiles oldDocFiles =  docFilesService.getById(docFiles.getId());

		DocFilesHistory his = new DocFilesHistory();
		BeanUtils.copyProperties(oldDocFiles,his);
		his.setHisid(docFiles.getId());
		his.setId(null);
		docFilesHistoryService.save(his);

		if(checkFileExist(docFiles)){
			return Result.error("文件名称重复!，保存失败");
		}
		docFilesService.updateById(docFiles);
		return Result.OK("编辑成功!");
	}

	@AutoLog(value = "文档管理-通过id删除")
	  
	@RequiresPermissions("doc:doc_files:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		DocFiles docFiles = docFilesService.getById(id);
		this.deleteFile(docFiles.getFilePath());
		docFilesService.removeById(id);
		return Result.OK("删除成功!");
	}

	@DeleteMapping(value = "/deleteByName")
	public Result<String> deleteByName(@RequestParam(name="fileName",required=true) String fileName) {
		QueryWrapper<DocFiles> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("file_name",fileName);
		List<DocFiles> docFiles = docFilesService.list(queryWrapper);
		for (DocFiles docFile : docFiles) {
			this.deleteFile(docFile.getFilePath());
			docFilesService.removeById(docFile.getId());
		}
		return Result.OK("删除成功!");
	}

	@AutoLog(value = "文档管理-批量删除")
	  
	@RequiresPermissions("doc:doc_files:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		List<String> listId = Arrays.asList(ids.split(","));
		List<DocFiles> listFile = this.docFilesService.listByIds(listId);
		for(DocFiles docFiles : listFile) {
			this.deleteFile(docFiles.getFilePath());
		}
		this.docFilesService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

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

    @RequiresPermissions("doc:doc_files:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, DocFiles docFiles) {
        return super.exportXls(request, docFiles, DocFiles.class, "文档管理");
    }

    @RequiresPermissions("doc:doc_files:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, DocFiles.class);
    }

	  
	@GetMapping(value = "/checkFileExist")
	public Result<List<String>> checkFileExist(String fileNames,HttpServletRequest request) {
		String[] aryFileName = fileNames.split(",");
		QueryWrapper<DocFiles> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("file_name",aryFileName);
		List<DocFiles>  list = this.docFilesService.list(queryWrapper);
		List<String> listFileName = new ArrayList<String>();
		for(DocFiles docFiles : list) {
			if(listFileName.contains(docFiles.getFileName())){
				continue;
			}
			listFileName.add(docFiles.getFileName());
		}
		return Result.ok(listFileName);
	}

	  
	@GetMapping(value = "/getDocFileLabels")
	public Result<List<String>> getDocFileLabels(String labelIds,HttpServletRequest request) {
		String[] aryLabelIds = labelIds.split(",");
		QueryWrapper<StLable> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("id",aryLabelIds);
		List<StLable>  list = this.stLableService.list(queryWrapper);
		List<String> listLabelName = new ArrayList<String>();
		for(int i=0;i<list.size();i++) {
			StLable stLable = list.get(i);
			listLabelName.add(stLable.getLableName());
		}
		return Result.ok(listLabelName);
	}

	 private void deleteFile( String filePath) {
		 String newfilePath = uploadpath + File.separator + filePath;
		 File file = new File(newfilePath);
		 if(file.isFile()) {
			 file.delete();
		 }
	 }


	private boolean checkFileExist(DocFiles docFiles) {
		QueryWrapper<DocFiles> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("file_name",docFiles.getFileName());
		if(docFiles.getId()!=null) {
			queryWrapper.ne("id",docFiles.getId());
		}
		List<DocFiles>  list = this.docFilesService.list(queryWrapper);
		return  list!=null&&list.size()>0;
	}

}
