package cn.iocoder.yudao.module.inspection.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.constant.InspectionConstants;
import cn.iocoder.yudao.module.constant.InspectionFileEnum;
import cn.iocoder.yudao.module.inspection.entity.*;
import cn.iocoder.yudao.module.inspection.mapper.InspectionFileMapper;
import cn.iocoder.yudao.module.inspection.service.IInspectionFileService;
import cn.iocoder.yudao.module.inspection.service.IWarnMessageService;
import cn.iocoder.yudao.module.inspection.service.InspectionFileRecordService;
import cn.iocoder.yudao.module.inspection.service.InspectionFileUserService;
import cn.iocoder.yudao.util.FileTypeUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * inspectionFileService业务层处理
 *
 * @author zcy
 * @date 2023-10-13
 */
@Service
public class InspectionFileServiceImpl extends ServiceImpl<InspectionFileMapper, InspectionFile> implements IInspectionFileService {
    @Autowired
    private IWarnMessageService messageService;

    @Autowired
    private InspectionFileUserService inspectionFileUserService;

    @Autowired
    private InspectionFileRecordService fileRecordService;

    /**
     * 查询inspectionFile
     *
     * @param id inspectionFile主键
     * @return inspectionFile
     */
    @Override
    public InspectionFile selectInspectionFileById(Long id) {
        return baseMapper.selectInspectionFileById(id);
    }


    /**
     * 新增inspectionFile
     *
     * @param inspectionFile inspectionFile
     * @return 结果
     */
    @Override
    public InspectionFile insertInspectionFile(InspectionFile inspectionFile) {

        int insert = baseMapper.insert(inspectionFile);
        if (ObjectUtil.isEmpty(inspectionFile.getFatherId())) {
            inspectionFile.setFileCode(inspectionFile.getId() + ",");
        } else {
            InspectionFile faFile = this.getById(inspectionFile.getFatherId());

            inspectionFile.setFileCode(faFile.getFileCode() + inspectionFile.getId() + ",");
        }
        baseMapper.updateById(inspectionFile);
        if (ObjectUtil.isNotEmpty(inspectionFile.getWarnTime())) {
            //同时处理提醒信息
            WarnMessage warnMessage = new WarnMessage();
            warnMessage.setTitle("文件到期提醒");
            warnMessage.setContent("文件名为:" + inspectionFile.getFileName() + "即将过期,请及时处理相关事项！");
            warnMessage.setIsRead("0");
            warnMessage.setPartnerId(inspectionFile.getPartnerId());
            warnMessage.setType("file");
            warnMessage.setObjectId(inspectionFile.getId());
            warnMessage.setWarnTime(inspectionFile.getWarnTime());
            messageService.save(warnMessage);
        }
        return inspectionFile;
    }

    /**
     * 新增inspectionFile
     *
     * @param inspectionFiles inspectionFile
     * @return 结果
     */
    @Override
    public boolean insertBatchInspectionFile(List<InspectionFile> inspectionFiles) {
        for (InspectionFile inspectionFile : inspectionFiles) {
            int insert = baseMapper.insert(inspectionFile);
            if (ObjectUtil.isEmpty(inspectionFile.getFatherId())) {
                inspectionFile.setFileCode(inspectionFile.getId() + ",");
            } else {
                InspectionFile faFile = this.getById(inspectionFile.getFatherId());

                inspectionFile.setFileCode(faFile.getFileCode() + inspectionFile.getId() + ",");
            }
            baseMapper.updateById(inspectionFile);
            if (ObjectUtil.isNotEmpty(inspectionFile.getWarnTime())) {
                //同时处理提醒信息
                WarnMessage warnMessage = new WarnMessage();
                warnMessage.setTitle("文件到期提醒");
                warnMessage.setContent("文件名为:" + inspectionFile.getFileName() + "即将过期,请及时处理相关事项！");
                warnMessage.setIsRead("0");
                warnMessage.setPartnerId(inspectionFile.getPartnerId());
                warnMessage.setType("file");
                warnMessage.setObjectId(inspectionFile.getId());
                warnMessage.setWarnTime(inspectionFile.getWarnTime());
                messageService.save(warnMessage);
            }
        }
//        return this.saveBatch(inspectionFiles);
        return true;
    }

    /**
     * 修改inspectionFile
     *
     * @param inspectionFile inspectionFile
     * @return 结果
     */
    @Override
    @Transactional
    public int updateInspectionFile(InspectionFile inspectionFile) {
        LambdaQueryWrapper<WarnMessage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WarnMessage::getType, "file").eq(WarnMessage::getObjectId, inspectionFile.getId());
        WarnMessage one = messageService.getOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(one)) {
            //更新处理
            messageService.removeById(one.getId());
        }
        if (ObjectUtil.isNotEmpty(inspectionFile.getWarnTime())) {
            //同时处理提醒信息
            WarnMessage warnMessage = new WarnMessage();
            warnMessage.setTitle("文件到期提醒");
            warnMessage.setContent("文件名为:" + inspectionFile.getFileName() + "即将过期,请及时处理相关事项！");
            warnMessage.setIsRead("0");
            warnMessage.setPartnerId(inspectionFile.getPartnerId());
            warnMessage.setType("file");
            warnMessage.setObjectId(inspectionFile.getId());
            warnMessage.setWarnTime(inspectionFile.getWarnTime());
            messageService.save(warnMessage);
        }
        InspectionFile file = this.selectInspectionFileById(inspectionFile.getId());

        if ((ObjectUtil.isNotEmpty(inspectionFile.getFilePath()) && ObjectUtil.isNotEmpty(file.getFilePath()) && !file.getFilePath().equals(inspectionFile.getFilePath()))
                || (ObjectUtil.isNotEmpty(inspectionFile.getFileName()) && !file.getFileName().equals(inspectionFile.getFileName()))
                || (ObjectUtil.isNotEmpty(inspectionFile.getWarnTime()) && !file.getWarnTime().equals(inspectionFile.getWarnTime()))) {

            //查询出之前的文件路径
            InspectionFileRecord inspectionFileRecord = new InspectionFileRecord();
            inspectionFileRecord.setFileId(file.getId());
            inspectionFileRecord.setFileName(file.getFileName());
            inspectionFileRecord.setFilePath(file.getFilePath());
            inspectionFileRecord.setType(file.getType());
            inspectionFileRecord.setWarnTime(file.getWarnTime());

            //保存记录
            fileRecordService.save(inspectionFileRecord);
        }
        return baseMapper.update(Wrappers.lambdaUpdate(InspectionFile.class).set(InspectionFile::getUpdateTime, new Date())
                .set(InspectionFile::getFileName, inspectionFile.getFileName())
                .set(ObjectUtil.isNotEmpty(inspectionFile.getFilePath()), InspectionFile::getFilePath, inspectionFile.getFilePath())
                .set(ObjectUtil.isNotEmpty(inspectionFile.getWarnTime()), InspectionFile::getWarnTime, inspectionFile.getWarnTime())
                .set(InspectionFile::getFatherId, inspectionFile.getFatherId())
                .eq(InspectionFile::getId, inspectionFile.getId()));
    }

    /**
     * 批量删除inspectionFile
     *
     * @param ids 需要删除的inspectionFile主键
     * @return 结果
     */
    @Override
    public int deleteInspectionFileByIds(Long[] ids) {
        return baseMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除inspectionFile信息
     *
     * @param id inspectionFile主键
     * @return 结果
     */
    @Override
    public int deleteInspectionFileById(Long id) {
        InspectionFile file = this.getById(id);
        if (file.getType().equals("2")) {
            LambdaQueryWrapper<WarnMessage> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WarnMessage::getType, "file").eq(WarnMessage::getObjectId, id);
            WarnMessage one = messageService.getOne(queryWrapper);
            if (ObjectUtil.isNotEmpty(one)) {
                //更新处理
                messageService.removeById(one.getId());
            }
            baseMapper.deleteById(id);
        } else if (file.getType().equals("1")) {
            LambdaQueryWrapper<InspectionFile> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.likeLeft(InspectionFile::getFileCode, file.getFileCode());
            List<InspectionFile> list = this.list(queryWrapper);
            for (InspectionFile inspectionFile : list) {
                LambdaQueryWrapper<WarnMessage> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(WarnMessage::getType, "file").eq(WarnMessage::getObjectId, inspectionFile.getId());
                WarnMessage one = messageService.getOne(queryWrapper1);
                if (ObjectUtil.isNotEmpty(one)) {
                    //更新处理
                    messageService.removeById(one.getId());
                }
            }
            baseMapper.delete(queryWrapper);
        }

        return 1;
    }

    @Override
    public List<InspectionFile> selectInspectionFileList(InspectionFile inspectionFile) {
        // 创建一个空的 QueryWrapper
        LambdaQueryWrapper<InspectionFile> queryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotEmpty(inspectionFile.getFatherId())) {
            queryWrapper.eq(InspectionFile::getFatherId, inspectionFile.getFatherId());
        } else {
            queryWrapper.isNull(InspectionFile::getFatherId);
        }
        queryWrapper.eq(InspectionFile::getServicePackageId, inspectionFile.getServicePackageId());
        queryWrapper.orderByAsc(InspectionFile::getType);
        queryWrapper.orderByDesc(InspectionFile::getCreateTime);
        if (ObjectUtil.isNotEmpty(inspectionFile.getFileName())) {
            queryWrapper.like(InspectionFile::getFileName, inspectionFile.getFileName());
        }
        queryWrapper.orderBy(false, false, InspectionFile::getCreateTime);
        List<InspectionFile> fileList = this.list(queryWrapper);
        //判断文件是否是图片
        fileList.forEach(file -> {
            if (StrUtil.isNotEmpty(file.getFilePath())) {
                boolean image = FileTypeUtils.isImage(file.getFilePath());
                String fileType = FileTypeUtils.getFileType(file.getFilePath());
                file.setIsImage(image);
                file.setFileType(fileType);
            }
        });
        return fileList;
    }

    /**
     * 根据id统计数量
     *
     * @param ids ids
     * @author 小李
     * @date 14:30 2024/12/14
     **/
    @Override
    public Map<Long, Long> getCountByIds(List<Long> ids) {
        List<InspectionFile> inspectionFiles = baseMapper.selectList(new LambdaQueryWrapper<InspectionFile>().in(InspectionFile::getFatherId, ids));
        return inspectionFiles.stream().collect(Collectors.groupingBy(
                InspectionFile::getFatherId,
                Collectors.counting()
        ));
    }

    /**
     * 分配权限
     *
     * @param userIds 用户id集合
     * @param fileId  文件id
     * @return
     */
    @Override
    public Object assignAuthority(List<Long> userIds, Long fileId) {
        // 如果选择的文件 ID为空，直接返回
        if (ObjectUtil.isEmpty(fileId)) {
            return null;
        }

        // 1. 删除这些文件的用户权限
        inspectionFileUserService.remove(new LambdaQueryWrapper<InspectionFileUser>()
                .eq(InspectionFileUser::getFileId, fileId));

        // 2. 为每个用户和文件合赋予权限
        List<InspectionFileUser> inspectionFileUsers = new ArrayList<>();
        for (Long userId : userIds) {
            InspectionFileUser inspectionFileUser = new InspectionFileUser();
            inspectionFileUser.setUserId(userId);
            inspectionFileUser.setFileId(fileId);
            inspectionFileUser.setCreateTime(DateUtil.date().toLocalDateTime());
            inspectionFileUser.setUpdateTime(DateUtil.date().toLocalDateTime());
            inspectionFileUsers.add(inspectionFileUser);
        }

        // 3. 批量保存新权限
        inspectionFileUserService.saveBatch(inspectionFileUsers);

        return null;
    }

    /**
     * 根据文件id获取有权限的用户id集合
     *
     * @param fileId
     * @return
     */
    @Override
    public List<Long> getUserIdsByFileId(Integer fileId) {
        List<InspectionFileUser> inspectionFileUsers = inspectionFileUserService.list(new LambdaQueryWrapper<InspectionFileUser>().eq(InspectionFileUser::getFileId, fileId));
        if (ObjectUtil.isNotEmpty(inspectionFileUsers)) {
            return inspectionFileUsers.stream().map(InspectionFileUser::getUserId).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public Set<InspectionFile> selectInspectionFileListByPermissio(InspectionFile inspectionFile, Long userId) {
        Set<InspectionFile> resultFiles = new HashSet<>();

        // 1. 获取用户有权限的所有文件
        List<Long> accessibleFileIds = inspectionFileUserService
                .list(new LambdaQueryWrapper<InspectionFileUser>()
                        .eq(InspectionFileUser::getUserId, userId))
                .stream()
                .map(InspectionFileUser::getFileId)
                .collect(Collectors.toList());

        // 如果用户没有文件权限，则返回空
        if (accessibleFileIds.isEmpty()) {
            return resultFiles;
        }

        // 2. 获取所有文件及文件夹信息（避免多次查询数据库）
        // 1. 查询所有文件信息，确保只查询必要的字段，并通过索引优化文件名的like查询
        List<InspectionFile> fileList = this.list(Wrappers.lambdaQuery(InspectionFile.class)
                .eq(InspectionFile::getServicePackageId, inspectionFile.getServicePackageId())
                .select(InspectionFile::getId, InspectionFile::getFileName, InspectionFile::getFatherId, InspectionFile::getFilePath, InspectionFile::getType)  // 仅查询必要字段
//                .like(ObjectUtil.isNotEmpty(inspectionFile.getFileName()), InspectionFile::getFileName, inspectionFile.getFileName())
                .orderBy(false, false, InspectionFile::getCreateTime));

        Map<Long, InspectionFile> fileCache = fileList.stream()
                .collect(Collectors.toMap(InspectionFile::getId, file -> file));

        // 3. 判断是否传递了fatherId参数（即点击了文件夹）
        Long fatherId = inspectionFile.getFatherId();  // 获取传递的文件夹ID

        if (fatherId != null) {
            // 4. 如果传递了fatherId，则查询该文件夹下所有有权限的文件，包括子文件夹及其内容
            resultFiles.addAll(getFilesInFolder(fatherId, accessibleFileIds, fileCache));
        } else {
            // 5. 如果没有传递fatherId，遍历用户有权限的文件
            for (Long fileId : accessibleFileIds) {
                InspectionFile file = fileCache.get(fileId);
                if (file != null) {
                    // 获取当前文件的父文件夹（递归获取最顶级父文件夹）
                    List<InspectionFile> parentFiles = getParentFiles(file.getFatherId(), fileCache);

                    // 如果有父文件，则将最顶级的父文件加入返回结果，否则返回当前文件
                    if (!parentFiles.isEmpty()) {
                        resultFiles.add(parentFiles.get(parentFiles.size() - 1));  // 只添加最顶级父文件
                    } else {
                        resultFiles.add(file);  // 当前文件没有父文件，直接返回当前文件
                    }
                }
            }
        }

        // 去重操作，优化查询时已经进行了判断，可以删除重复文件
//        List<InspectionFile> collect = resultFiles.stream().distinct().collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(inspectionFile.getFileName())) {
            //模糊匹配对应名称
            resultFiles = resultFiles.stream().filter(file -> file.getFileName().contains(inspectionFile.getFileName())).collect(Collectors.toSet());
        }

        //判断文件是否是图片
        resultFiles.forEach(file -> {
            if (StrUtil.isNotEmpty(file.getFilePath())) {
                boolean image = FileTypeUtils.isImage(file.getFilePath());
                String fileType = FileTypeUtils.getFileType(file.getFilePath());
                file.setIsImage(image);
                file.setFileType(fileType);
            }
        });
        return resultFiles;
    }

    /**
     * 新增文件夹
     *
     * @param folderName 文件夹名称
     * @return 文件夹id
     */
    @Override
    public Long addFolder(String folderName, String key) {
        //根据key找到对应的文件夹id
        InspectionFile fatherFolder = baseMapper.selectOne(new LambdaQueryWrapper<InspectionFile>().eq(InspectionFile::getDefaultKey, key));

        //如果默认文件夹为空就新建
        if (fatherFolder == null) {
            fatherFolder = new InspectionFile();
            fatherFolder.setFileName(InspectionFileEnum.getDescByType(key));
            fatherFolder.setType(InspectionConstants.INSPECTION_FOLDER);
            fatherFolder.setDefaultKey(key);
            baseMapper.insert(fatherFolder);
            fatherFolder.setFileCode(fatherFolder.getId() + ",");
            baseMapper.updateById(fatherFolder);
        }

        InspectionFile inspectionFile = new InspectionFile();
        inspectionFile.setFatherId(fatherFolder.getId());
        inspectionFile.setFileName(folderName + InspectionConstants.INSPECTION_FOLDER_SUFFIX);
        inspectionFile.setType(InspectionConstants.INSPECTION_FOLDER);
        inspectionFile.setIsStaffFile(InspectionConstants.INSPECTION_IS_STAFF_FILE);
        baseMapper.insert(inspectionFile);
        inspectionFile.setFileCode(inspectionFile.getId() + ",");
        baseMapper.updateById(inspectionFile);

        return inspectionFile.getId();
    }

    @Override
    public Long addFolderForJx(String folderName, String key) {
        //根据key找到对应的文件夹id
        InspectionFile fatherFolder = baseMapper.selectOne(new LambdaQueryWrapper<InspectionFile>().eq(InspectionFile::getDefaultKey, key));

        //如果默认文件夹为空就新建
        if (fatherFolder == null) {
            fatherFolder = new InspectionFile();
            fatherFolder.setFileName(InspectionFileEnum.getDescByType(key));
            fatherFolder.setType(InspectionConstants.INSPECTION_FOLDER);
            fatherFolder.setDefaultKey(key);
            fatherFolder.setServicePackageId("jiaxiao");
            baseMapper.insert(fatherFolder);
            fatherFolder.setFileCode(fatherFolder.getId() + ",");
            baseMapper.updateById(fatherFolder);
        }

        InspectionFile inspectionFile = new InspectionFile();
        inspectionFile.setFatherId(fatherFolder.getId());
        inspectionFile.setFileName(folderName + InspectionConstants.INSPECTION_FOLDER_SUFFIX);
        inspectionFile.setType(InspectionConstants.INSPECTION_FOLDER);
        inspectionFile.setIsStaffFile(InspectionConstants.INSPECTION_IS_STAFF_FILE);
        inspectionFile.setServicePackageId("jiaxiao");
        baseMapper.insert(inspectionFile);
        inspectionFile.setFileCode(inspectionFile.getId() + ",");
        baseMapper.updateById(inspectionFile);

        return inspectionFile.getId();
    }

    /**
     * 查询文件夹树
     *
     * @return 文件夹树
     */
    @Override
    public List<TreeCommonResult> queryTreeFolder() {
        //查询出所有文件夹
        List<InspectionFile> inspectionFiles = baseMapper.selectList(new LambdaQueryWrapper<InspectionFile>()
                .eq(InspectionFile::getType, InspectionConstants.INSPECTION_FOLDER)
                .orderBy(false, false, InspectionFile::getCreateTime));

        //组成属性结构
        return buildTree(inspectionFiles);
    }

    @Override
    public List<TreeCommonResult> queryTreeFolderForJx() {
        //查询出所有文件夹
        List<InspectionFile> inspectionFiles = baseMapper.selectList(new LambdaQueryWrapper<InspectionFile>()
                .eq(InspectionFile::getType, InspectionConstants.INSPECTION_FOLDER).eq(InspectionFile::getServicePackageId,"jiaxiao")
                .orderBy(false, false, InspectionFile::getCreateTime));

        //组成属性结构
        return buildTree(inspectionFiles);
    }

    /**
     * 构建树形结构
     *
     * @param files
     * @return
     */
    public static List<TreeCommonResult> buildTree(List<InspectionFile> files) {
        // 1. 先创建一个 Map，方便查找每个节点
        Map<Long, TreeCommonResult> nodeMap = files.stream().collect(Collectors.toMap(
                InspectionFile::getId,
                file -> {
                    TreeCommonResult node = new TreeCommonResult();
                    node.setValue(file.getId());
                    node.setLabel(file.getFileName());
                    return node;
                }
        ));

        List<TreeCommonResult> rootNodes = new ArrayList<>();

        // 2. 遍历文件列表，找到每个节点的父节点
        for (InspectionFile file : files) {
            TreeCommonResult node = nodeMap.get(file.getId());
            Long parentId = file.getFatherId();

            if (parentId == null || !nodeMap.containsKey(parentId)) {
                // 根节点（父ID为空或不存在于Map）
                rootNodes.add(node);
            } else {
                // 不是根节点，加入父节点的 children
                TreeCommonResult parentNode = nodeMap.get(parentId);
                if (parentNode.getChildren() == null) {
                    parentNode.setChildren(new ArrayList<>());
                }
                parentNode.getChildren().add(node);
            }
        }

        return rootNodes;
    }

    // 获取文件夹内的所有文件（包括子文件夹的内容）
    private List<InspectionFile> getFilesInFolder(Long folderId, List<Long> accessibleFileIds, Map<Long, InspectionFile> fileCache) {
        List<InspectionFile> filesInFolder = new ArrayList<>();
        // 获取该文件夹下的所有子文件
//        List<InspectionFile> folderFiles = this.list(new LambdaQueryWrapper<InspectionFile>()
//                .eq(InspectionFile::getFatherId, folderId));

        // 直接从 fileCache 过滤出当前 folderId 直接包含的子文件
        List<InspectionFile> folderFiles = fileCache.values().stream()
                .filter(file -> folderId.equals(file.getFatherId()))
                .collect(Collectors.toList());

        for (InspectionFile folderFile : folderFiles) {
            // 默认检查当前文件是否有权限
            boolean hasAccess = accessibleFileIds.contains(folderFile.getId());

            // 如果是文件夹，递归向下找子文件夹内是否有权限文件
            if (folderFile.getType().equals("1")) {  // 文件夹类型
                // 如果没有权限，递归检查该文件夹内是否有子文件或子文件夹有权限
                if (!hasAccess) {
                    hasAccess = (hasAccessToSubFiles(folderFile, accessibleFileIds, fileCache) || checkParentFolderPermission(folderFile, accessibleFileIds, fileCache));
                }
            } else {
                // 对于文件类型，检查父文件夹的权限
                if (!hasAccess) {
                    hasAccess = checkParentFolderPermission(folderFile, accessibleFileIds, fileCache);
                }
            }

            // 如果文件未处理且用户有权限
            if (hasAccess) {
                filesInFolder.add(folderFile);
            }
        }

        return filesInFolder;
    }

    // 检查当前文件夹下是否有权限的子文件或子文件夹
    private boolean hasAccessToSubFiles(InspectionFile folderFile, List<Long> accessibleFileIds, Map<Long, InspectionFile> fileCache) {
        // 获取文件夹内的所有子文件
//        List<InspectionFile> subFiles = this.list(new LambdaQueryWrapper<InspectionFile>()
//                .eq(InspectionFile::getFatherId, folderFile.getId()));

        List<InspectionFile> subFiles = fileCache.values().stream()
                .filter(file -> folderFile.getId().equals(file.getFatherId()))
                .collect(Collectors.toList());

        // 如果文件夹下有文件且其中一个文件有权限，则返回true
        for (InspectionFile subFile : subFiles) {
            if (accessibleFileIds.contains(subFile.getId())) {
                return true;
            }

            // 如果是文件夹，递归检查该文件夹是否有权限文件
            if (subFile.getType().equals("1") && hasAccessToSubFiles(subFile, accessibleFileIds, fileCache)) {
                return true;
            }
        }
        return false;
    }

    // 检查父文件夹的权限，直到找到用户有权限的文件夹
    private boolean checkParentFolderPermission(InspectionFile file, List<Long> accessibleFileIds, Map<Long, InspectionFile> fileCache) {
        Long fatherId = file.getFatherId();
        // 如果父文件夹存在且用户有权限，则返回true
        if (fatherId != null && accessibleFileIds.contains(fatherId)) {
            return true;
        }

        // 如果父文件夹没有权限，继续递归向上查找父文件夹
        if (fatherId != null) {
            InspectionFile parentFile = fileCache.get(fatherId);
            if (parentFile != null) {
                return checkParentFolderPermission(parentFile, accessibleFileIds, fileCache);
            }
        }

        return false;
    }

    // 递归获取文件夹的父文件夹，直到没有父文件夹为止
    private List<InspectionFile> getParentFiles(Long fatherId, Map<Long, InspectionFile> fileCache) {
        List<InspectionFile> parentFiles = new ArrayList<>();
        // 查找父文件
        InspectionFile parentFile = fileCache.get(fatherId);
        if (parentFile != null) {
            // 如果父文件有父级文件，继续递归查找
            if (parentFile.getFatherId() != null) {
                parentFiles.addAll(getParentFiles(parentFile.getFatherId(), fileCache));
            } else {
                parentFiles.add(parentFile);  // 添加父文件
            }
        }
        return parentFiles;
    }

}
