package com.yunzhupaas.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.xuyanwu.spring.file.storage.FileInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import com.yunzhupaas.base.ActionResult;
import com.yunzhupaas.base.Page;
import com.yunzhupaas.base.UserInfo;
import com.yunzhupaas.base.controller.SuperController;
import com.yunzhupaas.base.util.OptimizeUtil;
import com.yunzhupaas.base.vo.DownloadVO;
import com.yunzhupaas.base.vo.ListVO;
import com.yunzhupaas.config.ConfigValueUtil;
import com.yunzhupaas.constant.FileTypeConstant;
import com.yunzhupaas.constant.MsgCode;
import com.yunzhupaas.entity.DocumentEntity;
import com.yunzhupaas.entity.DocumentLogEntity;
import com.yunzhupaas.entity.DocumentShareEntity;
import com.yunzhupaas.exception.DataException;
import com.yunzhupaas.extend.service.DocumentApi;
import com.yunzhupaas.flowable.entity.TaskEntity;
import com.yunzhupaas.flowable.model.task.FileModel;
import com.yunzhupaas.model.MergeChunkDto;
import com.yunzhupaas.model.document.*;
import com.yunzhupaas.permission.entity.UserEntity;
import com.yunzhupaas.permission.service.UserService;
import com.yunzhupaas.service.DocumentLogService;
import com.yunzhupaas.service.DocumentService;
import com.yunzhupaas.util.*;
import com.yunzhupaas.util.treeutil.SumTree;
import com.yunzhupaas.util.treeutil.newtreeutil.TreeDotUtils;
import com.yunzhupaas.workflow.service.TaskApi;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 文档管理
 *
 * @author 云筑产品开发平台组
 * @version V3.1.0
 * @copyright 深圳市乐程软件有限公司（http://www.szlecheng.cn）
 * @date 2024-09-26 上午9:18
 */
@Slf4j
@Tag(name = "知识管理", description = "Document")
@RestController
@RequestMapping("/api/extend/Document")
public class DocumentController extends SuperController<DocumentService, DocumentEntity> implements DocumentApi {

    @Autowired
    private DocumentService documentService;
    @Autowired
    private ConfigValueUtil configValueUtil;
    @Autowired
    private UserService userService;
    
    @Autowired
    private DocumentLogService documentLogService;
    @Autowired
    private TaskApi taskApi;

    /**
     * 列表
     *
     * @param id 主键
     * @return
     */
    @Operation(summary = "列表")
    @GetMapping("/{id}")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
    })
    public ActionResult<DocumentInfoVO> info(@PathVariable("id") String id) throws DataException {
        DocumentEntity entity = documentService.getInfo(id);
        DocumentInfoVO vo = JsonUtil.getJsonToBean(entity, DocumentInfoVO.class);
        //截取后缀
        String[] fullName = vo.getFullName().split("\\.");
        if (fullName.length > 1) {
            String fullNames = "";
            for (int i = 0; i < fullName.length - 1; i++) {
                if (i > 0) {
                    fullNames += "." + fullName[i];
                } else {
                    fullNames += fullName[i];
                }
            }
            vo.setFullName(fullNames);
        }
        return ActionResult.success(vo);
    }

    /**
     * 新建
     *
     * @param documentCrForm 新建模型
     * @return
     */
    @Operation(summary = "新建")
    @PostMapping
    @Parameters({
            @Parameter(name = "documentCrForm", description = "知识模型", required = true),
    })
    public ActionResult create(@RequestBody @Valid DocumentCrForm documentCrForm) {
        DocumentEntity entity = JsonUtil.getJsonToBean(documentCrForm, DocumentEntity.class);
        if (documentService.isExistByFullName(documentCrForm.getFullName(), entity.getId(), documentCrForm.getParentId())) {
            return ActionResult.fail(MsgCode.EXIST004.get());
        }
        entity.setEnabledMark(1);
        documentService.create(entity);
        return ActionResult.success(MsgCode.SU001.get());
    }

    /**
     * 修改
     *
     * @param id             主键
     * @param documentUpForm 修改模型
     * @return
     */
    @Operation(summary = "修改")
    @PutMapping("/{id}")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
            @Parameter(name = "documentUpForm", description = "知识模型", required = true),
    })
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid DocumentUpForm documentUpForm) {
        DocumentEntity entity = JsonUtil.getJsonToBean(documentUpForm, DocumentEntity.class);
        if (documentService.isExistByFullName(documentUpForm.getFullName(), id, documentUpForm.getParentId())) {
            return ActionResult.fail(MsgCode.EXIST004.get());
        }
        DocumentEntity info = documentService.getInfo(id);
        //获取后缀名
        String[] fullName = info.getFullName().split("\\.");
        if (fullName.length > 1) {
            entity.setFullName(entity.getFullName() + "." + fullName[fullName.length - 1]);
        }
        boolean flag = documentService.update(id, entity);
        if (flag == false) {
            return ActionResult.fail(MsgCode.FA002.get());
        }
        return ActionResult.success(MsgCode.SU004.get());
    }

    /**
     * 删除
     *
     * @param id 主键
     * @return
     */
    @Operation(summary = "删除")
    @DeleteMapping("/{id}")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
    })
    public ActionResult delete(@PathVariable("id") String id) {
        DocumentEntity entity = documentService.getInfo(id);
        if (entity != null) {
            List<DocumentEntity> allList = documentService.getAllList(entity.getId());
            if (allList.size() > 0) {
                return ActionResult.fail(MsgCode.FA016.get());
            }
            documentService.delete(entity);
            return ActionResult.success(MsgCode.SU003.get());
        }
        return ActionResult.fail(MsgCode.FA003.get());
    }

    /**
     * 列表
     *
     * @return
     */
    @Operation(summary = "获取知识管理列表（文件夹树）")
    @PostMapping("/FolderTree")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
    })
    public ActionResult<ListVO<DocumentFolderTreeVO>> folderTree(@RequestBody DocumentShareForm form) {
        List<DocumentEntity> data = documentService.getFolderList();
        if (StringUtil.isNotEmpty(form.getIds())) {
            form.getIds().forEach(t -> data.remove(documentService.getInfo(t)));
        }
        List<DocumentFolderTreeModel> treeList = new ArrayList<>();
        DocumentFolderTreeModel model = new DocumentFolderTreeModel();
        model.setId("-1");
        model.setFullName("全部文档");
        model.setParentId("0");
        model.setIcon("0");
        treeList.add(model);
        for (DocumentEntity entity : data) {
            DocumentFolderTreeModel treeModel = new DocumentFolderTreeModel();
            treeModel.setId(entity.getId());
            treeModel.setFullName(entity.getFullName());
            treeModel.setParentId(entity.getParentId());
            treeModel.setIcon("fa fa-folder");
            treeList.add(treeModel);
        }
        List<SumTree<DocumentFolderTreeModel>> trees = TreeDotUtils.convertListToTreeDotFilter(treeList);
        List<DocumentFolderTreeVO> listVO = JsonUtil.getJsonToList(trees, DocumentFolderTreeVO.class);
        ListVO vo = new ListVO();
        vo.setList(listVO);
        return ActionResult.success(vo);
    }

    /**
     * 列表（全部文档）
     *
     * @param page 分页模型
     * @return
     */
    @Operation(summary = "获取知识管理列表（全部文档）")
    @GetMapping
    public ActionResult<ListVO<DocumentListVO>> allList(PageDocument page) {
        List<DocumentEntity> data = documentService.getAllList(page.getParentId());
        if (StringUtil.isNotEmpty(page.getKeyword())) {
            data = documentService.getSearchAllList(page.getKeyword());
        }
        List<DocumentListVO> list = JsonUtil.getJsonToList(data, DocumentListVO.class);
        //读取允许文件预览类型
        String allowPreviewType = configValueUtil.getAllowPreviewFileType();
        String[] fileType = allowPreviewType.split(",");
        for (DocumentListVO documentListVO : list) {
            //文件预览类型检验
            String s = Arrays.asList(fileType).stream().filter(type -> type.equals(documentListVO.getFileExtension())).findFirst().orElse(null);
            documentListVO.setIsPreview(s);
        }

        ListVO vo = new ListVO();
        vo.setList(list);
        return ActionResult.success(vo);
    }

    /**
     * 列表（我的分享）
     *
     * @param page 分页模型
     * @return
     */
    @Operation(summary = "知识管理（我的共享列表）")
    @GetMapping("/Share")
    public ActionResult<ListVO<DocumentListVO>> shareOutList(PageDocument page) {
        List<DocumentEntity> data = documentService.getShareOutList();
        if (StringUtil.isNotEmpty(page.getKeyword())) {
            List<DocumentEntity> dataSearch = new ArrayList<>();
            for (DocumentEntity datum : data) {
                if (Objects.equals(datum.getType(), 0)) {
                    List<DocumentEntity> childList = new ArrayList<>();
                    documentService.getChildSrcList(datum.getId(), childList, 1);
                    List<DocumentEntity> collect = childList.stream().filter(t -> !Objects.equals(t.getType(), 0)).collect(Collectors.toList());
                    dataSearch.addAll(collect);
                } else {
                    dataSearch.add(datum);
                }

            }
            data = dataSearch.stream().distinct().filter(t -> t.getFullName().contains(page.getKeyword())).collect(Collectors.toList());
        } else if (StringUtil.isNotEmpty(page.getParentId()) && !"0".equals(page.getParentId())) {
            data = documentService.getAllList(page.getParentId());
        }
        List<DocumentListVO> list = JsonUtil.getJsonToList(data, DocumentListVO.class);
        ListVO vo = new ListVO();
        vo.setList(list);
        return ActionResult.success(vo);
    }

    /**
     * 列表（共享给我）
     *
     * @param page 分页模型
     * @return
     */
    @Operation(summary = "获取知识管理列表（共享给我）")
    @GetMapping("/ShareTome")
    public ActionResult<ListVO<DocumentListVO>> shareTomeList(PageDocument page) {
        List<DocumentShareEntity> shareTomeList = documentService.getShareTomeList();
        List<String> ids = shareTomeList.stream().map(DocumentShareEntity::getDocumentId).collect(Collectors.toList());
        List<DocumentEntity> list = documentService.getInfoByIds(ids);

        List<String> userIds = list.stream().map(t -> t.getCreatorUserId()).collect(Collectors.toList());
        List<UserEntity> userNames = userService.getUserName(userIds);
        List<DocumentListVO> dataRes = new ArrayList<>();
        if (StringUtil.isNotEmpty(page.getParentId()) && !"0".equals(page.getParentId())) {
            list = documentService.getChildList(page.getParentId(), true);
            DocumentShareEntity documentShareEntity = documentService.getShareByParentId(page.getParentId());
            for (DocumentEntity item : list) {
                DocumentListVO documentListVO = BeanUtil.copyProperties(item, DocumentListVO.class);
                if (documentShareEntity != null) {
                    documentListVO.setShareTime(documentShareEntity.getShareTime());
                    UserEntity userEntity = userNames.stream().filter(t -> t.getId().equals(documentShareEntity.getCreatorUserId())).findFirst().orElse(null);
                    documentListVO.setCreatorUserId(userEntity != null ? userEntity.getRealName() + "/" + userEntity.getAccount() : "");
                }
                dataRes.add(documentListVO);
            }
        } else {
            for (DocumentEntity datum : list) {
                if (StringUtil.isNotEmpty(page.getKeyword())) {
                    DocumentShareEntity documentShareEntity = shareTomeList.stream().filter(t -> t.getDocumentId().equals(datum.getId())).findFirst().orElse(null);
                    if (documentShareEntity != null) {
                        if (Objects.equals(datum.getType(), 0)) {
                            List<DocumentEntity> childList = new ArrayList<>();
                            documentService.getChildSrcList(datum.getId(), childList, 1);
                            for (DocumentEntity item : childList) {
                                DocumentListVO documentListVO = BeanUtil.copyProperties(item, DocumentListVO.class);
                                if (item.getFullName().contains(page.getKeyword()) && Objects.equals(item.getEnabledMark(), 1) && !Objects.equals(item.getType(), 0)) {
                                    documentListVO.setShareTime(documentShareEntity.getShareTime());
                                    UserEntity userEntity = userNames.stream().filter(t -> t.getId().equals(documentShareEntity.getCreatorUserId())).findFirst().orElse(null);
                                    documentListVO.setCreatorUserId(userEntity != null ? userEntity.getRealName() + "/" + userEntity.getAccount() : "");
                                    dataRes.add(documentListVO);
                                }
                            }
                        }
                    }
                } else {
                    DocumentShareEntity documentShareEntity = shareTomeList.stream().filter(t -> t.getDocumentId().equals(datum.getId())).findFirst().orElse(null);
                    if (documentShareEntity != null) {
                        DocumentListVO documentListVO = BeanUtil.copyProperties(datum, DocumentListVO.class);
                        documentListVO.setShareTime(documentShareEntity.getShareTime());
                        UserEntity userEntity = userNames.stream().filter(t -> t.getId().equals(documentShareEntity.getCreatorUserId())).findFirst().orElse(null);
                        documentListVO.setCreatorUserId(userEntity != null ? userEntity.getRealName() + "/" + userEntity.getAccount() : "");
                        dataRes.add(documentListVO);
                    }
                }
            }
        }

        ListVO vo = new ListVO();
        vo.setList(dataRes);
        return ActionResult.success(vo);
    }

    /**
     * 列表（回收站）
     *
     * @param page 分页模型
     * @return
     */
    @Operation(summary = "获取知识管理列表（回收站）")
    @GetMapping("/Trash")
    public ActionResult<ListVO<DocumentTrashListVO>> trashList(Page page) {
        List<DocumentTrashListVO> data = documentService.getTrashList(page.getKeyword());
        ListVO vo = new ListVO();
        vo.setList(data);
        return ActionResult.success(vo);
    }

    /**
     * 列表（共享人员）
     *
     * @param documentId 文档主键
     * @return
     */
    @Operation(summary = "获取知识管理列表（共享人员）")
    @GetMapping("/ShareUser/{documentId}")
    @Parameters({
            @Parameter(name = "documentId", description = "文档主键", required = true),
    })
    public ActionResult<ListVO<DocumentSuserListVO>> shareUserList(@PathVariable("documentId") String documentId) {
        List<DocumentShareEntity> data = documentService.getShareUserList(documentId);
        List<DocumentSuserListVO> list = JsonUtil.getJsonToList(data, DocumentSuserListVO.class);
        ListVO vo = new ListVO();
        vo.setList(list);
        return ActionResult.success(vo);
    }

    /**
     * app上传文件
     *
     * @param documentUploader 上传模型
     * @return
     */
    @Operation(summary = "知识管理上传文件")
    @PostMapping("/Uploader")
    public ActionResult uploader(DocumentUploader documentUploader) throws DataException {
        String fileType = UpUtil.getFileType(documentUploader.getFile());
        //验证类型
        if (!OptimizeUtil.fileType(configValueUtil.getAllowUploadFileType(), fileType)) {
            return ActionResult.fail(MsgCode.FA017.get());
        }

        //上传
        uploaderVO(documentUploader);
        return ActionResult.success(MsgCode.SU015.get());
    }

    /**
     * 分片组装
     *
     * @param mergeChunkDto 合并模型
     * @return
     */
    @Operation(summary = "分片组装")
    @PostMapping("/merge")
    public ActionResult merge(MergeChunkDto mergeChunkDto) {
        String identifier = XSSEscape.escapePath(mergeChunkDto.getIdentifier());
        String path = FileUploadUtils.getLocalBasePath() + configValueUtil.getTemporaryFilePath();
        String filePath = XSSEscape.escapePath(path + identifier);
        String partFile = XSSEscape.escapePath(path + mergeChunkDto.getFileName());
        try {
            List<File> mergeFileList = FileUtil.getFile(new File(filePath));
            @Cleanup FileOutputStream destTempfos = new FileOutputStream(partFile, true);
            for (int i = 0; i < mergeFileList.size(); i++) {
                String chunkName = identifier.concat("-") + (i + 1);
                File files = new File(filePath, chunkName);
                if (files.exists()) {
                    FileUtils.copyFile(files, destTempfos);
                }
            }
            File partFiles = new File(partFile);
            if (partFiles.exists()) {
                MultipartFile multipartFile = FileUtil.createFileItem(partFiles);
                uploaderVO(new DocumentUploader(multipartFile, mergeChunkDto.getParentId()));
                FileUtil.deleteTmp(multipartFile);
            }
        } catch (Exception e) {
            log.error("合并分片失败: {}", e.getMessage());
            throw new DataException(MsgCode.FA033.get());
        } finally {
            FileUtils.deleteQuietly(new File(filePath));
            FileUtils.deleteQuietly(new File(partFile));
        }
        return ActionResult.success(MsgCode.SU015.get());
    }

    @Operation(summary = "流程归档文件上传接口")
    @PostMapping("/UploadBlob")
    public ActionResult UploadBlob(DocumentUploader dub) throws DataException {
        uploaderVO(dub);
        taskApi.updateIsFile(dub.getTaskId());
        return ActionResult.success(MsgCode.SU015.get());
    }

    /**
     * 获取下载文件链接
     *
     * @param id 主键
     * @return
     */
    @Operation(summary = "获取下载文件链接")
    @PostMapping("/Download/{id}")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
    })
    public ActionResult download(@PathVariable("id") String id) {
        UserInfo userInfo = UserProvider.getUser();
        DocumentEntity entity = documentService.getInfo(id);
        if (entity != null) {
            String name = entity.getFilePath();
            String fileName = name + "#" + "document#" + entity.getFullName() + "." + entity.getFileExtension();
            DownloadVO vo = DownloadVO.builder().name(entity.getFullName()).url(UploaderUtil.uploaderFile(fileName)).build();
            return ActionResult.success(vo);
        }
        return ActionResult.fail(MsgCode.FA018.get());
    }

    /**
     * 获取全部下载文件链接（打包下载）
     *
     * @return
     */
    @Operation(summary = "打包下载")
    @PostMapping("/PackDownload")
    public ActionResult packDownloadUrl(@RequestBody DocumentShareForm obj) {
        //单个文件直接下载
        if (obj.getIds().size() == 1) {
            DocumentEntity entity = documentService.getInfo(obj.getIds().get(0));
            if (entity != null && !Objects.equals(entity.getType(), 0)) {
                String name = entity.getFilePath();
                String fileName = name + "#" + "document#" + entity.getFullName() + "." + entity.getFileExtension();
                DownloadVO vo = DownloadVO.builder().name(entity.getFullName()).url(UploaderUtil.uploaderFile(fileName)).build();
                return ActionResult.success(vo);
            }
        }
        String tempFilePath = FileUploadUtils.getLocalBasePath() + FilePathUtil.getFilePath(FileTypeConstant.FILEZIPDOWNTEMPPATH);
        String zipFileSrc = "我的文档" + RandomUtil.uuId();
        String zipFileName = zipFileSrc + ".zip";
        String mainPath = tempFilePath + zipFileSrc;
        new File(mainPath).mkdirs();
        //递归生成文件夹下的文件
        createdFiles(obj.getIds(), mainPath);

        String filePath = tempFilePath + zipFileName;
        //打包
        FileUtil.toZip(filePath, true, tempFilePath + zipFileSrc);
        //删除源文件
        FileUtil.deleteFileAll(new File(tempFilePath + zipFileSrc));

        //上传压缩包到服务器
        MultipartFile multipartFile = FileUtil.createFileItem(new File(XSSEscape.escapePath(filePath)));
        FileInfo fileInfo = FileUploadUtils.uploadFile(multipartFile, FilePathUtil.getFilePath(FileTypeConstant.FILEZIPDOWNTEMPPATH), zipFileName);
        // 删除压缩包
        FileUtil.deleteFileAll(new File(tempFilePath + zipFileName));

        //获取服务器下载路径
        DownloadVO vo = DownloadVO.builder()
                .name(zipFileName)
                .url(UploaderUtil.uploaderFile(fileInfo.getFilename() + "#" + FileTypeConstant.FILEZIPDOWNTEMPPATH))
                .build();
        return ActionResult.success(vo);
    }

    /**
     * 递归获取文件夹下的文件
     *
     * @param fileIdList
     * @param mainPath
     */
    private void createdFiles(List<String> fileIdList, String mainPath) {
        for (String id : fileIdList) {
            DocumentEntity info = documentService.getInfo(id);
            if (info != null) {
                String fileId = StringUtil.isNotEmpty(info.getFilePath()) ? XSSEscape.escape(info.getFilePath()).trim() : "";
                String fileName = XSSEscape.escapePath(info.getFullName()).trim();
                if (Objects.equals(info.getType(), 0)) {
                    //文件夹
                    File file = new File(mainPath + "/" + fileName);
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    List<DocumentEntity> allList = documentService.getChildList(id, true);
                    List<String> collect = allList.stream().map(DocumentEntity::getId).collect(Collectors.toList());
                    createdFiles(collect, mainPath + "/" + fileName);
                } else {
                    try {
                        //文件
                        byte[] bytes = FileUploadUtils.downloadFileByte(FilePathUtil.getFilePath(FileTypeConstant.DOCUMENT), fileId, false);
                        FileUtils.writeByteArrayToFile(new File(mainPath + "/" + fileName), bytes);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }


    /**
     * 批量删除
     */
    @Operation(summary = "批量删除")
    @PostMapping("/BatchDelete")
    @Parameters({
            @Parameter(name = "ids", description = "主键", required = true),
    })
    public ActionResult BatchDelete(@RequestBody DocumentShareForm obj) {
        for (String id : obj.getIds()) {
            DocumentEntity entity = documentService.getInfo(id);
            if (entity != null) {
                List<DocumentEntity> allList = new ArrayList<>();
                documentService.getChildSrcList(entity.getId(), allList, 1);
                allList.add(entity);
                //添加删除记录
                DocumentLogEntity logent = new DocumentLogEntity();
                logent.setDocumentId(id);
                List<String> collect = allList.stream().map(DocumentEntity::getId).collect(Collectors.toList());
                logent.setChildDocument(collect.stream().collect(Collectors.joining(",")));
                documentLogService.save(logent);
                for (DocumentEntity item : allList) {
                    documentService.delete(item);
                }
            }
        }
        return ActionResult.success(MsgCode.SU003.get());
    }

    /**
     * 回收站（彻底删除）
     *
     * @return
     */
    @Operation(summary = "回收站（彻底删除）")
    @PostMapping("/Trash")
    @Parameters({
            @Parameter(name = "ids", description = "主键数组", required = true),
    })
    public ActionResult trashdelete(@RequestBody DocumentShareForm obj) {
        documentService.trashdelete(obj.getIds());
        return ActionResult.success(MsgCode.SU003.get());
    }

    /**
     * 回收站（还原文件）
     *
     * @return
     */
    @Operation(summary = "回收站（还原文件）")
    @PostMapping("/Trash/Actions/Recovery")
    @Parameters({
            @Parameter(name = "ids", description = "主键数组", required = true),
    })
    @Transactional
    public ActionResult trashRecovery(@RequestBody DocumentShareForm obj) {
        documentService.trashRecoveryConstainSrc(obj.getIds());
        return ActionResult.success(MsgCode.SU010.get());
    }

    /**
     * 共享文件（创建）
     *
     * @param documentShareForm 分享模型
     * @return
     */
    @Operation(summary = "分享文件/文件夹")
    @PostMapping("/Actions/Share")
    @Parameters({
            @Parameter(name = "documentShareForm", description = "分享模型", required = true),
    })
    public ActionResult shareCreate(@RequestBody DocumentShareForm documentShareForm) {
        documentService.sharecreate(documentShareForm);
        return ActionResult.success(MsgCode.SU005.get());
    }

    /**
     * 取消共享
     *
     * @param obj 主键值
     * @return
     */
    @Operation(summary = "取消分享文件/文件夹")
    @PostMapping("/Actions/CancelShare")
    @Parameters({
            @Parameter(name = "ids", description = "主键", required = true),
    })
    public ActionResult shareCancel(@RequestBody DocumentShareForm obj) {
        documentService.shareCancel(obj.getIds());
        return ActionResult.success(MsgCode.SU005.get());
    }


    @Operation(summary = "共享用户调整")
    @PostMapping("/Actions/ShareAdjustment/{id}")
    @Parameters({
            @Parameter(name = "id", description = "文档主键", required = true),
            @Parameter(name = "userIds", description = "共享用户组", required = true),
    })
    public ActionResult shareAdjustment(@PathVariable("id") String id, @RequestBody DocumentShareForm obj) {
        if (obj.getUserIds().size() > 0) {
            documentService.shareAdjustment(id, obj.getUserIds());
        }
        return ActionResult.success(MsgCode.SU005.get());
    }

    @Operation(summary = "移动文件/文件夹")
    @PutMapping("/Actions/MoveTo/{toId}")
    @Parameters({
            @Parameter(name = "ids", description = "主键", required = true),
            @Parameter(name = "toId", description = "将要移动到Id", required = true),
    })
    @Transactional
    public ActionResult moveTo(@RequestBody DocumentShareForm obj, @PathVariable("toId") String toId) {
        List<String> allIds = new ArrayList<>();
        allIds.addAll(obj.getIds());
        List<DocumentEntity> childList = new ArrayList<>();
        for (String oneId : obj.getIds()) {
            documentService.getChildSrcList(oneId, childList, 1);
        }
        allIds.addAll(childList.stream().map(DocumentEntity::getId).collect(Collectors.toList()));
        if (allIds.contains(toId)) {
            return ActionResult.fail(MsgCode.ETD103.get());
        }

        for (String id : obj.getIds()) {
            boolean flag = documentService.moveTo(id, toId);
            if (flag == false) {
                return ActionResult.fail(MsgCode.FA002.get());
            }
        }

        return ActionResult.success(MsgCode.SU004.get());
    }

    /**
     * 封装上传附件
     * 流程归档-文件上传
     *
     * @return
     */
    private void uploaderVO(DocumentUploader documentUploader) {
        MultipartFile file = documentUploader.getFile();
        String parentId = documentUploader.getParentId();
        String taskId = documentUploader.getTaskId();
        String fileName = StringUtil.isNotEmpty(documentUploader.getTaskId()) ? documentUploader.getTaskId() :
                StringUtil.isNotEmpty(documentUploader.getFileName()) ? documentUploader.getFileName() : file.getOriginalFilename();
        String fileType = UpUtil.getFileType(file);
        String creatorUserId = "";
        List<String> userList = new ArrayList<>();
        if (StringUtil.isNotEmpty(taskId)) {
            try { //获取流程信息
                FileModel fileModel = taskApi.getFileModel(taskId);
                fileName = fileModel.getFilename();
                creatorUserId = fileModel.getUserId();
                userList.addAll(fileModel.getUserList());
                fileType = "pdf";

                List<DocumentEntity> allList = documentService.getAllList("0", creatorUserId);
                DocumentEntity documentEntity = allList.stream().filter(t -> Objects.equals(t.getType(), 0) && FileModel.FOLDER_NAME.equals(t.getFullName())).findFirst().orElse(null);
                if (Objects.isNull(documentEntity)) {
                    documentEntity = new DocumentEntity();
                    documentEntity.setFullName(FileModel.FOLDER_NAME);
                    documentEntity.setType(0);
                    documentEntity.setParentId("0");
                    documentEntity.setCreatorUserId(creatorUserId);
                    documentService.create(documentEntity);
                }
                parentId = documentEntity.getId();
            } catch (Exception e) {
                throw new DataException(MsgCode.FA001.get());
            }
        }

        String filePath = configValueUtil.getDocumentFilePath();
        List<DocumentEntity> data = documentService.getAllList(parentId);
        String finalFileName = fileName;
        data = data.stream().filter(t -> finalFileName.equals(t.getFullName())).collect(Collectors.toList());
        if (data.size() > 0) {
            fileName = fileName.substring(0, fileName.lastIndexOf(".")) + "副本" + UUID.randomUUID().toString().substring(0, 5) + fileName.substring(fileName.lastIndexOf("."));
        }
        //上传
        FileInfo fileInfo = null;
        try {
            fileInfo = FileUploadUtils.uploadFile(file.getBytes(), filePath, fileName);
        } catch (IOException e) {
            throw new DataException(MsgCode.FA033.get());
        }
        DocumentEntity entity = new DocumentEntity();
        entity.setType(1);
        entity.setFullName(fileName);
        entity.setParentId(parentId);
        entity.setFileExtension(fileType);
        entity.setFilePath(fileInfo.getFilename());
        entity.setFileSize(String.valueOf(file.getSize()));
        entity.setCreatorUserId(creatorUserId);
        entity.setEnabledMark(1);
        String desc = null;
        TaskEntity taskEntity = taskApi.getInfoSubmit(taskId, TaskEntity::getId, TaskEntity::getTemplateId);
        if (null != taskEntity) {
            desc = taskId + "-" + taskEntity.getTemplateId();
        }
        entity.setDescription(desc);
        entity.setUploaderUrl(UploaderUtil.uploaderImg("/api/file/Image/document/", fileInfo.getFilename()));
        documentService.create(entity);
        if (StringUtil.isNotEmpty(taskId)) {
            DocumentShareForm documentShareForm = new DocumentShareForm();
            documentShareForm.setUserIds(userList);
            documentShareForm.setIds(new ArrayList() {{
                add(entity.getId());
            }});
            documentShareForm.setCreatorUserId(creatorUserId);
            documentService.sharecreate(documentShareForm);
        }
    }

    /**
     * 判断是否存在归档文件
     *
     * @param taskId 流程任务主键
     */
    public Boolean checkFlowFile(String taskId) {
        QueryWrapper<DocumentEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().like(DocumentEntity::getDescription, taskId);
        return documentService.count(wrapper) < 1;
    }

    /**
     * 获取归档文件
     *
     * @param model 参数
     */
    public List<Map<String, Object>> getFlowFile(FlowFileModel model) {
        return documentService.getFlowFile(model);
    }
}

