package com.vctgo.file.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.vctgo.common.core.constant.RoleConstants;
import com.vctgo.common.core.constant.ServiceNameConstants;
import com.vctgo.common.core.domain.R;
import com.vctgo.common.core.text.Convert;
import com.vctgo.common.core.utils.ServletUtils;
import com.vctgo.common.core.utils.StrUtils;
import com.vctgo.common.mybatisplus.constant.MybatisPageConstants;
import com.vctgo.common.redis.service.RedisService;
import com.vctgo.common.security.utils.SecurityUtils;
import com.vctgo.file.domain.FileAshInfo;
import com.vctgo.file.domain.FileAuthGroup;
import com.vctgo.file.domain.FileReUserOperate;
import com.vctgo.file.domain.dto.FileInfoAuthDto;
import com.vctgo.file.mapper.FileAshInfoMapper;
import com.vctgo.file.mapper.FileAuthGroupMapper;
import com.vctgo.file.mapper.FileInfoMapper;
import com.vctgo.file.mapper.FileReUserOperateMapper;
import com.vctgo.file.service.IDistributedFileSystemService;
import com.vctgo.file.service.IFileCommonService;
import com.vctgo.file.service.IFileInfoService;
import com.vctgo.file.utils.ConstantUtils;
import com.vctgo.file.utils.FileInfoTreeUtils;
import com.vctgo.file.utils.FileUtils;
import com.vctgo.system.api.domain.FileInfo;
import com.vctgo.system.api.domain.SysRole;
import com.vctgo.system.api.domain.SysUserTempalte;
import com.vctgo.system.api.domain.dto.FileInfoDto;
import com.vctgo.system.api.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j

@Service
public class FileInfoServiceImpl implements IFileInfoService {
    @Autowired
    private IDistributedFileSystemService iDistributedFileSystemService;

    @Autowired
    private FileInfoMapper fileInfoMapper;

    @Autowired
    private FileAuthGroupMapper fileAuthGroupMapper;

    @Autowired
    private FileReUserOperateMapper fileReUserOperateMapper;

    @Autowired
    private FileAshInfoMapper fileAshInfoMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private IFileCommonService fileCommonService;

    @Override
    public FileInfoAuthDto findFileManagePage(FileInfo fileInfo) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Page page = new Page(Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_NUM), 1L), Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_SIZE), 50L));
        /**
         *   模糊搜索文件管理全部文件名称的文件、文件夹
         */
        if (StrUtils.isNotEmpty(fileInfo.getFileName())) {
            fileInfo.setFileParentId(null);
        }
        /**
         *  非超管/文件资源管理员的角色时，
         *      1.FileParentId == null      获取与当前人有关系的 && 文件名匹配的文件夹、文件
         *      2.FileParentId == 0         获取根目录与当前人有关系的文件夹、文件
         *      3.FileParentId == (具体值)   获取当前目录下与当前人有关系的文件夹、文件
         */
        List<String> roleKeyList = loginUser.getSysRolesList().stream().map(SysRole::getRoleKey).collect(Collectors.toList());
        if (!roleKeyList.contains(RoleConstants.ROLE_KEY_ADMIN) && !roleKeyList.contains(RoleConstants.ROLE_KEY_FILE_RESOURCE_USER)) {
            List<Long> fileIdList = new ArrayList<>();
            if (fileInfo.getFileParentId() == null) {
                List<FileInfo> fileInfoList = fileReUserOperateMapper.selectAncestorsByUserIdAndFileId(SecurityUtils.getUserId().toString(), SecurityUtils.getTenantId().toString());
                List<String> excludeFileIdList = fileInfoList.stream().filter(fileInfoTmp -> "2".equals(fileInfoTmp.getFileName())).map(FileInfo::getId).map(String::valueOf).collect(Collectors.toList());
                ArrayList<String> fileRootIdList = new ArrayList<>();
                fileInfoList.stream().filter(fileInfoTmp -> "1".equals(fileInfoTmp.getFileName())).forEach(fileInfoTmp -> {
                    List<String> ancestorList = Splitter.on(",").splitToStream(fileInfoTmp.getAncestors()).collect(Collectors.toList());
                    if (ancestorList.size() > 1) {
                        fileRootIdList.add(ancestorList.get(1));
                    } else if (ancestorList.size() == 1) {
                        fileRootIdList.add(fileInfoTmp.getId().toString());
                    }
                });
                if (CollectionUtils.isEmpty(fileRootIdList)) {
                    return FileInfoAuthDto.builder().build();
                }
                fileIdList = fileReUserOperateMapper.selectFileByParentIdListAndTenantId(SecurityUtils.getTenantId().toString(),
                        fileRootIdList,
                        excludeFileIdList);
                fileIdList = fileIdList.stream().distinct().collect(Collectors.toList());
            } else if (ConstantUtils.FILE_ANCESTORS.equals(fileInfo.getFileParentId().toString())) {
                fileIdList = fileReUserOperateMapper.selectFileIdListByUserIdAndTenantId(SecurityUtils.getUserId().toString(), SecurityUtils.getTenantId().toString());
            } else {
                fileIdList = fileReUserOperateMapper.selectFileIdByFileParentIdAndTenantId(SecurityUtils.getTenantId().toString(), fileInfo.getFileParentId().toString(), SecurityUtils.getUserId().toString());
            }
            if (CollectionUtils.isEmpty(fileIdList)) {
                return FileInfoAuthDto.builder().build();
            }
            fileInfo.setFileIdList(fileIdList);
        }
        //其他必要参数
        fileInfo.setTenantId(SecurityUtils.getTenantId());
        fileInfo.setFileIsHide(ConstantUtils.IS_DELETED_0);
        fileInfo.setIsDeleted(ConstantUtils.IS_DELETED_0);
        //获取数据
        IPage<FileInfo> fileIPage = fileInfoMapper.selectFileManagePage(page, fileInfo);
        if (CollectionUtils.isNotEmpty(fileIPage.getRecords())) {
            fileIPage.getRecords().forEach(fileInfoTmp -> fileInfoTmp
                    .setFileSizeBytes(Objects.nonNull(fileInfoTmp.getFileSize()) ? FileUtils.convertBytes(fileInfoTmp.getFileSize()) : ""));
            /**
             *  填充创建人、更新人昵称
             */
            List<SysUserTempalte> sysUserTempalteList = fileCommonService.selectSysUserTemplateListByTenantId(SecurityUtils.getTenantId());
            if (CollectionUtils.isNotEmpty(sysUserTempalteList)) {
                Map<Long, List<SysUserTempalte>> userTempalteMap = sysUserTempalteList.stream().collect(Collectors.groupingBy(SysUserTempalte::getUserId));
                fileIPage.getRecords().forEach(fileInfoTmp -> {

                    // 创建人
                    List<SysUserTempalte> sysUserTempalteCreateList = userTempalteMap.get(fileInfoTmp.getCreateById());
                    if (CollectionUtils.isNotEmpty(sysUserTempalteCreateList)) {
                        fileInfoTmp.setCreateBy(sysUserTempalteCreateList.get(0).getNickName());
                    }

                    // 更新人
                    List<SysUserTempalte> sysUserTempalteUpdateList = userTempalteMap.get(fileInfoTmp.getCreateById());
                    if (CollectionUtils.isNotEmpty(sysUserTempalteUpdateList)) {
                        fileInfoTmp.setUpdateBy(sysUserTempalteUpdateList.get(0).getNickName());
                    }
                });
            }
        }

        FileInfoAuthDto.FileInfoAuthDtoBuilder fileInfoAuthDtoBuilder = FileInfoAuthDto.builder();

        // 超级管理员/文件资源管理员
        if (roleKeyList.contains(RoleConstants.ROLE_KEY_ADMIN) || roleKeyList.contains(RoleConstants.ROLE_KEY_FILE_RESOURCE_USER)) {
            // 页面按钮权限字符设置,没有办法区别出哪些角色是文件资源管理的, 将所有的权限字符一并返回
            // 页面按钮不仅是角色过来的静态权限，还有动态分配的权限

            // 获取文件/文件夹的权限管理权限字符
            LambdaQueryWrapper<FileAuthGroup> fileAuthGroupWrapper = Wrappers.lambdaQuery(FileAuthGroup.class)
                    .eq(FileAuthGroup::getIsDeleted, ConstantUtils.IS_DELETED_0)
                    .and(fileAuthGroupLambdaQueryWrapper -> fileAuthGroupLambdaQueryWrapper.eq(FileAuthGroup::getGroupCode, ConstantUtils.DOC_AUTH_GROUP_AUTH_MANAGE)
                            .or().eq(FileAuthGroup::getGroupCode, ConstantUtils.FILE_AUTH_GROUP_AUTH_MANAGE));
            String permissions = Joiner.on(",").join(fileAuthGroupMapper.selectList(fileAuthGroupWrapper).stream().map(FileAuthGroup::getGroupPermissions).collect(Collectors.toSet()));
            List<String> permissionList = Lists.newArrayList(Splitter.on(",").splitToList(permissions));

            // 操作按钮
            List<String> permissionListTmp = new ArrayList<>(permissionList);
            permissionListTmp.removeIf(permissionsTmp -> permissionsTmp.equals(ConstantUtils.CLOUD_STORAGE_INFO_DOWNLOAD));
            permissionListTmp.removeIf(permissionsTmp -> permissionsTmp.equals(ConstantUtils.FILE_MANAGE_HIDE));
            permissionListTmp.removeIf(permissionsTmp -> permissionsTmp.equals(ConstantUtils.FILE_MANAGE_MOVE));
            fileIPage.getRecords().forEach(fileInfoTmp -> {
                if (ConstantUtils.SHOW_STATUS_FIX_1 == fileInfoTmp.getFileStatus()) {
                    fileInfoTmp.setFilePermissions(permissionListTmp);
                } else {
                    fileInfoTmp.setFilePermissions(permissionList);
                }
            });
            fileInfoAuthDtoBuilder.fileInfoIPage(fileIPage);

            // 页面按钮
            permissionList.addAll(new ArrayList<>(loginUser.getPermissions()));
            fileInfoAuthDtoBuilder.pagePermissionSet(new HashSet<>(permissionList));
        } else {
            // 非超级管理员/文件资源管理员页面按钮权限
            fileInfoAuthDtoBuilder.pagePermissionSet(loginUser.getPermissions());

            // 文件/文件夹操作权限
            if (CollectionUtils.isNotEmpty(fileIPage.getRecords())) {
                // 文件夹 ---->  再分配 > 继承
                //  文件  ---->  再分配 > 创建人
                List<String> fileIdList = fileIPage.getRecords().stream().map(FileInfo::getId).map(String::valueOf).collect(Collectors.toList());
                List<FileReUserOperate> fileReUserOperateList = fileReUserOperateMapper.selectGroupPermissionListByUserIdAndFileId(fileIdList, String.valueOf(SecurityUtils.getUserId()));
                List<String> havePermissionsList = fileReUserOperateList.stream().map(FileReUserOperate::getFileId).map(String::valueOf).distinct().collect(Collectors.toList());
                fileIPage.getRecords().forEach(fileInfoTmp -> {
                    Optional<FileReUserOperate> fileReUserOperateOptional = fileReUserOperateList.stream().filter(fileReUserOperate -> fileReUserOperate.getFileId().toString().equals(fileInfoTmp.getId().toString())).findFirst();
                    if (fileReUserOperateOptional.isPresent()) {
                        FileReUserOperate fileReUserOperate = fileReUserOperateOptional.get();
                        List<String> permissionList = Lists.newArrayList(Splitter.on(",").splitToList(fileReUserOperate.getGroupPermissions()));
                        if (!Objects.equals(fileInfoTmp.getCreateById().toString(), SecurityUtils.getUserId().toString()) && fileReUserOperate.getFileUserAuthCode().equals(ConstantUtils.DOC_AUTH_GROUP_UP_DOWN)) {
                            permissionList.remove(ConstantUtils.FILE_MANAGE_HIDE);
                        }
                        fileInfoTmp.setFilePermissions(permissionList);
                    }
                });

                //  文件  ---->  继承
                //  需要对文件继承文件夹的权限时，做映射
                List<String> fileAncestorsList = fileIPage.getRecords().stream().filter(fileInfoTmp -> !havePermissionsList.contains(fileInfoTmp.getId().toString())).map(FileInfo::getAncestors).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(fileAncestorsList)) {
                    List<String> fileAncestorList = Splitter.on(",").splitToList(Joiner.on(",").join(fileAncestorsList));
                    List<FileReUserOperate> fileReUserOperateRetainList = fileReUserOperateMapper.selectGroupPermissionListByUserIdAndFileId(fileAncestorList, String.valueOf(SecurityUtils.getUserId()));
                    List<FileAuthGroup> fileAuthGroups = new ArrayList<>();
                    List<String> fileInfoIsFileList = fileIPage.getRecords().stream().filter(fileInfoTmp -> !havePermissionsList.contains(fileInfoTmp.getId().toString()) && "0".equals(fileInfoTmp.getFileIsDirectory())).map(FileInfo::getId).map(String::valueOf).collect(Collectors.toList());
                    if (!fileInfoIsFileList.isEmpty()) {
                        fileAuthGroups = fileAuthGroupMapper.selectList();
                    }
                    List<FileAuthGroup> finalFileAuthGroups = fileAuthGroups;
                    fileIPage.getRecords().stream().filter(fileInfoTmp -> !havePermissionsList.contains(fileInfoTmp.getId().toString())).forEach(fileInfoTmp -> {
                        String ancestors = fileInfoTmp.getAncestors();
                        List<String> ancestorsFileIdList = Splitter.on(",").splitToStream(ancestors).collect(Collectors.toList());
                        Collections.reverse(ancestorsFileIdList);
                        for (String fileId : ancestorsFileIdList) {
                            Optional<FileReUserOperate> fileReUserOperateOptional = fileReUserOperateRetainList.stream().filter(fileReUserOperate -> fileReUserOperate.getFileId().toString().equals(fileId)).findFirst();
                            if (fileReUserOperateOptional.isPresent()) {
                                if (fileInfoIsFileList.contains(fileInfoTmp.getId().toString())) {
                                    Optional<FileAuthGroup> fileAuthGroupOptional = null;
                                    switch (fileReUserOperateOptional.get().getFileUserAuthCode()) {
                                        case ConstantUtils.FILE_AUTH_GROUP_MANAGE:
                                            fileAuthGroupOptional = finalFileAuthGroups.stream().filter(fileAuthGroup -> fileAuthGroup.getGroupCode().equals(ConstantUtils.DOC_AUTH_GROUP_MANAGE)).findFirst();
                                            break;
                                        case ConstantUtils.FILE_AUTH_GROUP_AUTH_MANAGE:
                                            fileAuthGroupOptional = finalFileAuthGroups.stream().filter(fileAuthGroup -> fileAuthGroup.getGroupCode().equals(ConstantUtils.DOC_AUTH_GROUP_AUTH_MANAGE)).findFirst();
                                            break;
                                        case ConstantUtils.FILE_AUTH_GROUP_SHOW_DOWN:
                                            fileAuthGroupOptional = finalFileAuthGroups.stream().filter(fileAuthGroup -> fileAuthGroup.getGroupCode().equals(ConstantUtils.DOC_AUTH_GROUP_SHOW_DOWN)).findFirst();
                                            break;
                                        case ConstantUtils.FILE_AUTH_GROUP_UP_DOWN:
                                            fileAuthGroupOptional = finalFileAuthGroups.stream().filter(fileAuthGroup -> fileAuthGroup.getGroupCode().equals(ConstantUtils.DOC_AUTH_GROUP_UP_DOWN)).findFirst();
                                            break;
                                        case ConstantUtils.FILE_AUTH_GROUP_SHOW:
                                            fileAuthGroupOptional = finalFileAuthGroups.stream().filter(fileAuthGroup -> fileAuthGroup.getGroupCode().equals(ConstantUtils.DOC_AUTH_GROUP_SHOW)).findFirst();
                                            break;
                                    }
                                    if (Objects.nonNull(fileAuthGroupOptional) && fileAuthGroupOptional.isPresent()) {
                                        FileAuthGroup fileAuthGroup = fileAuthGroupOptional.get();
                                        List<String> permissionList = Lists.newArrayList(Splitter.on(",").splitToList(fileAuthGroup.getGroupPermissions()));
                                        if (!fileInfoTmp.getCreateById().toString().equals(SecurityUtils.getUserId().toString()) && fileAuthGroup.getGroupCode().equals(ConstantUtils.DOC_AUTH_GROUP_UP_DOWN)) {
                                            permissionList.remove(ConstantUtils.FILE_MANAGE_HIDE);
                                            permissionList.remove(ConstantUtils.FILE_MANAGE_RENAME);
                                        }
                                        fileInfoTmp.setFilePermissions(permissionList);
                                    }
                                } else {
                                    fileInfoTmp.setFilePermissions(Splitter.on(",").splitToList(fileReUserOperateOptional.get().getGroupPermissions()));
                                }
                                break;
                            }
                        }
                    });
                }
            }
            // 固定文件夹--租户名称对应的文件夹    操作按钮
            fileIPage.getRecords().stream().filter(fileInfoTmp -> ConstantUtils.SHOW_STATUS_FIX_1 == fileInfoTmp.getFileStatus()).forEach(fileInfoTmp -> {
                List<String> filePermissions = fileInfoTmp.getFilePermissions();
                if (CollectionUtils.isNotEmpty(filePermissions)) {
                    filePermissions.remove(ConstantUtils.CLOUD_STORAGE_INFO_DOWNLOAD);
                    filePermissions.remove(ConstantUtils.FILE_MANAGE_HIDE);
                    filePermissions.remove(ConstantUtils.FILE_MANAGE_MOVE);
                    fileInfoTmp.setFilePermissions(filePermissions);
                }
            });

            fileInfoAuthDtoBuilder.fileInfoIPage(fileIPage);
        }

        // 富力桃园  学习视频  文件夹特殊处理
        fileIPage.getRecords().stream().filter(fileInfoTmp -> ConstantUtils.SHOW_STATUS_FIX_2 == fileInfoTmp.getFileStatus()).forEach(fileInfoTmp -> {
            fileInfoTmp.setFilePermissions(Arrays.asList(ConstantUtils.CLOUD_STORAGE_INFO_OPEN, ConstantUtils.FILE_MANAGE_PAGE));
        });
        fileInfoAuthDtoBuilder.fileInfoIPage(fileIPage);
        //文件路径拼接
        for (FileInfo fileInfoTmp : fileIPage.getRecords()) {
            fileInfoTmp.setAncestorsDtoList(fileInfoMapper.selectAncestorsListById(fileInfoTmp.getAncestors()));
        }
        return fileInfoAuthDtoBuilder.build();
    }

    /**
     * 富力桃园定制化文件资源-分页
     *
     * @param fileInfo
     * @return
     */
    @Override
    public FileInfoAuthDto findFileManagePageV2(FileInfo fileInfo) {

        if (102L == SecurityUtils.getTenantId()) {

            if (Objects.isNull(fileInfo.getFileParentId())) {
                throw new SecurityException("接口参数有误");
            }

            LambdaQueryWrapper<FileInfo> fileInfoWrapper = new LambdaQueryWrapper<>();
            fileInfoWrapper.eq(FileInfo::getIsDeleted, ConstantUtils.IS_DELETED_0);
            fileInfoWrapper.eq(FileInfo::getFileIsHide, ConstantUtils.IS_DELETED_0);
            fileInfoWrapper.eq(FileInfo::getFileType, "0");
            fileInfoWrapper.eq(FileInfo::getFileParentId, "0");
            fileInfoWrapper.eq(FileInfo::getFileName, "学习视频");
            fileInfoWrapper.eq(FileInfo::getTenantId, "102");
            FileInfo fileInfoTmp = fileInfoMapper.selectOne(fileInfoWrapper);
            if (Objects.isNull(fileInfoTmp)) {
                throw new SecurityException("没有该文件权限");
            }

            //其他必要参数
            fileInfo.setTenantId(SecurityUtils.getTenantId());
            fileInfo.setFileIsHide(ConstantUtils.IS_DELETED_0);
            fileInfo.setIsDeleted(ConstantUtils.IS_DELETED_0);
            //获取数据
            Page page = new Page(Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_NUM), 1L), Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_SIZE), 50L));
            IPage<FileInfo> fileIPage = fileInfoMapper.selectFileManagePage(page, fileInfo);
            if (CollectionUtils.isNotEmpty(fileIPage.getRecords())) {
                fileIPage.getRecords().forEach(fileInfoResult -> fileInfoResult
                        .setFileSizeBytes(Objects.nonNull(fileInfoResult.getFileSize()) ? FileUtils.convertBytes(fileInfoResult.getFileSize()) : ""));
                /**
                 *  填充创建人、更新人昵称
                 */
                List<SysUserTempalte> sysUserTempalteList = fileCommonService.selectSysUserTemplateListByTenantId(SecurityUtils.getTenantId());
                if (CollectionUtils.isNotEmpty(sysUserTempalteList)) {
                    Map<Long, List<SysUserTempalte>> userTempalteMap = sysUserTempalteList.stream().collect(Collectors.groupingBy(SysUserTempalte::getUserId));
                    fileIPage.getRecords().forEach(fileInfoResult -> {

                        fileInfoResult.setFileStatus(2);

                        // 创建人
                        List<SysUserTempalte> sysUserTempalteCreateList = userTempalteMap.get(fileInfoResult.getCreateById());
                        if (CollectionUtils.isNotEmpty(sysUserTempalteCreateList)) {
                            fileInfoResult.setCreateBy(sysUserTempalteCreateList.get(0).getNickName());
                        }

                        // 更新人
                        List<SysUserTempalte> sysUserTempalteUpdateList = userTempalteMap.get(fileInfoResult.getCreateById());
                        if (CollectionUtils.isNotEmpty(sysUserTempalteUpdateList)) {
                            fileInfoResult.setUpdateBy(sysUserTempalteUpdateList.get(0).getNickName());
                        }
                    });
                }
            }
            return FileInfoAuthDto.builder().fileInfoIPage(fileIPage).build();
        }

        return FileInfoAuthDto.builder().build();
    }

    @Override
    public List<FileInfo> selectByIds(String ids) {
        return fileInfoMapper.selectList(FileInfo::getId, Arrays.asList(ids.split(",")));
    }

    @Override
    public FileInfo selectById(Long id) {
        return fileInfoMapper.selectOne(new QueryWrapper<FileInfo>().lambda().eq(FileInfo::getId, id));
    }

    @Override
    @Transactional
    public void initMkdirByTenantId(Long tenantId, String serviceName, String fileName) {
        List<FileInfo> fixFileList = fileInfoMapper.selectList(new QueryWrapper<FileInfo>().lambda()
                .eq(FileInfo::getTenantId, tenantId)
                .eq(FileInfo::getServiceName, serviceName)
                .eq(FileInfo::getFileStatus, ConstantUtils.SHOW_STATUS_FIX_1));
        if (CollectionUtils.isEmpty(fixFileList)) {
            FileInfo fileInfo = new FileInfo();
            LoginUser loginUser = SecurityUtils.getLoginUser();
            fileInfo.setTenantId(tenantId);
            fileInfo.setFileName(fileName);
            fileInfo.setFileFullName(fileName);
            fileInfo.setFileParentId(0L);
            fileInfo.setServiceName(serviceName);
            fileInfo.setFileIsDirectory(ConstantUtils.IS_DIRECTORY_FILE_1);
            fileInfo.setFileIsHide(ConstantUtils.IS_DELETED_0);
            fileInfo.setFileStatus(ConstantUtils.SHOW_STATUS_FIX_1);
            fileInfo.setAncestors(ConstantUtils.FILE_ANCESTORS);
            fileInfo.setIsDeleted(ConstantUtils.IS_DELETED_0);
            doSetFileInfo(fileInfo, loginUser);
            fileInfoMapper.insert(fileInfo);
        }
    }

    @Transactional
    @Override
    public R<FileInfo> uploadByUploadTag(String uploadTag, MultipartFile file) {
        try {
            // 上传并返回访问地址
            String originalFilename = Objects.requireNonNull(file.getOriginalFilename()).substring(0, file.getOriginalFilename().indexOf("."));
            String url = iDistributedFileSystemService.uploadFile(file);
            FileInfo fileInfo = getFileInfo(file, url);
            addFile(fileInfo);
            synchronized (uploadTag.intern()) {
                Map<String, FileInfo> cacheMap = redisService.getCacheMap(uploadTag);
                if (null != cacheMap && !cacheMap.isEmpty()) {
                    if (!cacheMap.containsKey(originalFilename)) {
                        cacheMap.put(originalFilename, fileInfo);
                    }
                } else {
                    cacheMap = new HashMap<>();
                    cacheMap.put(originalFilename, fileInfo);
                }
                redisService.setCacheMap(uploadTag, cacheMap);
                redisService.expire(uploadTag, 30, TimeUnit.MINUTES);
            }
            return R.ok(fileInfo);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 添加文件对象
     *
     * @param fileInfo 文件信息对象
     * @return
     */
    @Override
    public int addFile(FileInfo fileInfo) {
        return fileInfoMapper.insert(fileInfo);
    }

    @Override
    public R<FileInfoDto> upload(MultipartFile file) {
        try {
            // 文件访问地址
            String url = iDistributedFileSystemService.uploadFile(file);
            // 文件信息
            FileInfo fileInfo = getFileInfo(file, url);
            // 存储文件
            fileInfoMapper.insert(fileInfo);
            // 文件信息实体幻化
            FileInfoDto fileInfoDto = new FileInfoDto();
            BeanUtils.copyProperties(fileInfo, fileInfoDto);
            return R.ok(fileInfoDto);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * fastdfs下载文件
     *
     * @param filePath 文件路径
     * @return
     */
    @Override
    public void fastdfsDownLoad(String filePath) {
        //http://ip:8888/group1/M00/00/00/rBoX5mR0ulSAIukOAASzmDL13HM352.jpg
        byte[] bytes = null;
        try {
            //返回"/"第四次出现的位置
            int index1 = StringUtils.ordinalIndexOf(filePath, "/", 4);
            int index2 = StringUtils.ordinalIndexOf(filePath, "/", 5);
            String group = filePath.substring(index1 + 1, index2);
            String filepath = filePath.substring(filePath.lastIndexOf(group + "/") + 7);
//            DownloadByteArray callback = new DownloadByteArray();
//            bytes = storageClient.downloadFile(group, filepath,callback);

            //文件输出流
            FileOutputStream fileOutputStream = new FileOutputStream("E:\\file\\test\\a.jpg");
            fileOutputStream.write(bytes);
            fileOutputStream.flush();
            fileOutputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 更新文件状态信息
     *
     * @param serviceName 业务名称
     * @param status      状态 0/1
     * @param serviceId   服务对应的记录Id
     * @return
     */
    @Override
    public int updateFileStatusByServiceIdAndServiceName(String serviceName, String status, String serviceId) {
        return fileInfoMapper.updateFileStatusByServiceIdAndServiceName(serviceName, status, serviceId);
    }

    @Override
    public int updateFileServiceIdAndServiceNameByIds(String serviceName, String serviceId, String ids) {
        return fileInfoMapper.updateFileServiceIdAndServiceNameByIds(serviceName, serviceId, ids);
    }

    @Override
    public int updateFileServiceIdAndServiceNameAndStatusByIds(String serviceName, String serviceId, String status, String ids) {
        return fileInfoMapper.updateFileServiceIdAndServiceNameAndStatusByIds(serviceName, serviceId, status, ids);
    }

    @Override
    public List<FileInfo> selectUrlByIds(String ids) {
        LambdaQueryWrapper<FileInfo> fileInfoWrapper = new LambdaQueryWrapper<>();
        fileInfoWrapper.eq(FileInfo::getIsDeleted, ConstantUtils.IS_DELETED_0);
        fileInfoWrapper.in(FileInfo::getId, Arrays.asList(ids.split(",")));
        return fileInfoMapper.selectList(fileInfoWrapper);
    }

    @Override
    public List<FileInfo> selectPointTenantUrlByIds(Long tenantId, String ids) {
        String[] idArr = ids.split(",");
        return fileInfoMapper.selectPointTenantUrlByIds(tenantId, idArr);
    }

    @Override
    public void doReFileName(Long id, String rename) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        FileInfo fileInfo = fileInfoMapper.selectOne(new QueryWrapper<FileInfo>().lambda().eq(FileInfo::getId, id));
        if (fileInfo != null) {
            //文件
            if (ConstantUtils.IS_DIRECTORY_FILE_0.equals(fileInfo.getFileIsDirectory())) {
                fileInfo.setFileName(rename.replace("." + fileInfo.getFileExtension(), ""));
                fileInfo.setFileFullName(rename);
            }
            //文件夹
            if (ConstantUtils.IS_DIRECTORY_FILE_1.equals(fileInfo.getFileIsDirectory())) {
                fileInfo.setFileName(rename);
                fileInfo.setFileFullName(rename);
            }
            fileInfo.setUpdateById(loginUser.getUserid());
            fileInfo.setUpdateTime(new Date());
            fileInfoMapper.updateById(fileInfo);

            //父文件夹修改时间变更
            FileInfo parentFileInfo = fileInfoMapper.selectOne(FileInfo::getId, fileInfo.getFileParentId());
            if (Objects.nonNull(parentFileInfo)) {
                parentFileInfo.setUpdateById(SecurityUtils.getUserId());
                parentFileInfo.setUpdateTime(new Date());
                fileInfoMapper.updateById(parentFileInfo);
            }
        }
    }

    @Override
    public void doBatchHideFile(String ids) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //全部文件、文件夹
        List<FileInfo> fileInfoRootList = fileInfoMapper.selectList(new LambdaQueryWrapper<FileInfo>().in(FileInfo::getId, Arrays.asList(ids.split(","))));
        if (CollectionUtils.isNotEmpty(fileInfoRootList)) {
            for (FileInfo fileInfoRoot : fileInfoRootList) {
                //文件
                if (ConstantUtils.IS_DIRECTORY_FILE_0.equals(fileInfoRoot.getFileIsDirectory())) {
                    //文件设置为隐藏
                    fileInfoRoot.setFileIsHide(ConstantUtils.IS_DELETED_1);
                    fileInfoRoot.setUpdateById(loginUser.getUserid());
                    fileInfoRoot.setUpdateTime(new Date());
                    fileInfoMapper.updateById(fileInfoRoot);
                    //文件与用户权限关系设置为隐藏
                    List<FileReUserOperate> deletedOperateList = fileReUserOperateMapper.selectList(new QueryWrapper<FileReUserOperate>().lambda().eq(FileReUserOperate::getFileId, fileInfoRoot.getId()));
                    for (FileReUserOperate userOperate : deletedOperateList) {
                        userOperate.setIsDeleted(ConstantUtils.IS_DELETED_1);
                        userOperate.setUpdateById(SecurityUtils.getUserId());
                        userOperate.setUpdateTime(new Date());
                        fileReUserOperateMapper.updateById(userOperate);
                    }
                }
                //文件夹
                if (ConstantUtils.IS_DIRECTORY_FILE_1.equals(fileInfoRoot.getFileIsDirectory())) {
                    //当前文件夹
                    FileInfo fileInfo = fileInfoMapper.selectOne(new QueryWrapper<FileInfo>().lambda()
                            .eq(FileInfo::getId, fileInfoRoot.getId()));
                    if (fileInfo != null) {
                        fileInfo.setFileIsHide(ConstantUtils.IS_DELETED_1);
                        fileInfo.setUpdateById(loginUser.getUserid());
                        fileInfo.setUpdateTime(new Date());
                        fileInfoMapper.updateById(fileInfo);
                        //当前文件夹与用户权限关系设置为隐藏
                        List<FileReUserOperate> deletedOperateList = fileReUserOperateMapper.selectList(new QueryWrapper<FileReUserOperate>().lambda()
                                .eq(FileReUserOperate::getFileId, fileInfo.getId()));
                        for (FileReUserOperate userOperate : deletedOperateList) {
                            userOperate.setIsDeleted(ConstantUtils.IS_DELETED_1);
                            userOperate.setUpdateById(SecurityUtils.getUserId());
                            userOperate.setUpdateTime(new Date());
                            fileReUserOperateMapper.updateById(userOperate);
                        }
                    }
                    //子文件、文件夹
                    List<FileInfo> fileInfoChildList = fileInfoMapper.selectListByParentId(fileInfoRoot.getId());
                    if (CollectionUtils.isNotEmpty(fileInfoChildList)) {
                        for (FileInfo fileInfoChild : fileInfoChildList) {
                            fileInfoChild.setFileIsHide(ConstantUtils.IS_DELETED_1);
                            fileInfoChild.setUpdateById(loginUser.getUserid());
                            fileInfoChild.setUpdateTime(new Date());
                            fileInfoMapper.updateById(fileInfoChild);
                            //子文件、文件夹与用户权限关系设置为隐藏
                            List<FileReUserOperate> deletedOperateList = fileReUserOperateMapper.selectList(new QueryWrapper<FileReUserOperate>().lambda().eq(FileReUserOperate::getFileId, fileInfoChild.getId()));
                            for (FileReUserOperate userOperate : deletedOperateList) {
                                userOperate.setIsDeleted(ConstantUtils.IS_DELETED_1);
                                userOperate.setUpdateById(SecurityUtils.getUserId());
                                userOperate.setUpdateTime(new Date());
                                fileReUserOperateMapper.updateById(userOperate);
                            }
                        }
                    }
                }
                //父文件夹修改时间变更
                FileInfo parentFileInfo = fileInfoMapper.selectOne(FileInfo::getId, fileInfoRoot.getFileParentId());
                if (Objects.nonNull(parentFileInfo)) {
                    parentFileInfo.setUpdateById(SecurityUtils.getUserId());
                    parentFileInfo.setUpdateTime(new Date());
                    fileInfoMapper.updateById(parentFileInfo);
                }
            }

            //直接删除文件、文件夹迁移回收站表
            for (FileInfo fileInfoRoot : fileInfoRootList) {
                List<FileAshInfo> ashInfoList = fileAshInfoMapper.selectList(new QueryWrapper<FileAshInfo>().lambda()
                        .eq(FileAshInfo::getIsDeleted, ConstantUtils.IS_DELETED_0)
                        .eq(FileAshInfo::getFileId, fileInfoRoot.getId()));
                if (CollectionUtils.isEmpty(ashInfoList)) {
                    FileAshInfo fileAshInfo = new FileAshInfo();
                    fileAshInfo.setFileId(fileInfoRoot.getId());
                    fileAshInfo.setFileType(fileInfoRoot.getFileType());
                    fileAshInfo.setFileExtension(fileInfoRoot.getFileExtension());
                    fileAshInfo.setFileName(fileInfoRoot.getFileName());
                    fileAshInfo.setFileFullName(fileInfoRoot.getFileFullName());
                    fileAshInfo.setFileSize(fileInfoRoot.getFileSize());
                    fileAshInfo.setFileUrl(fileInfoRoot.getFileUrl());
                    fileAshInfo.setFileIsDirectory(fileInfoRoot.getFileIsDirectory());
                    fileAshInfo.setIsDeleted(ConstantUtils.IS_DELETED_0);
                    fileAshInfo.setCreateById(loginUser.getUserid());
                    fileAshInfo.setCreateTime(new Date());
                    fileAshInfo.setUpdateById(loginUser.getUserid());
                    fileAshInfo.setUpdateTime(new Date());
                    fileAshInfoMapper.insert(fileAshInfo);
                }
            }
        }
    }

    @Override
    public List<FileInfo> doMoveFileTree() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<String> roleKeyList = loginUser.getSysRolesList().stream().map(SysRole::getRoleKey).collect(Collectors.toList());
        List<FileInfo> fileInfoList = new ArrayList<>();
        // 超级管理员/文件资源管理员
        if (roleKeyList.contains(RoleConstants.ROLE_KEY_ADMIN) || roleKeyList.contains(RoleConstants.ROLE_KEY_FILE_RESOURCE_USER)) {
            fileInfoList = fileInfoMapper.selectList(new QueryWrapper<FileInfo>().lambda()
                    .eq(FileInfo::getIsDeleted, ConstantUtils.IS_DELETED_0)
                    .eq(FileInfo::getFileIsHide, ConstantUtils.IS_DELETED_0)
                    .eq(FileInfo::getTenantId, SecurityUtils.getTenantId())
                    .eq(FileInfo::getFileIsDirectory, ConstantUtils.IS_DELETED_1)
                    .eq(FileInfo::getServiceName, ServiceNameConstants.FILE_SERVICE)
                    .orderByAsc(FileInfo::getFileStatus).orderByDesc(FileInfo::getUpdateTime));
            fileInfoList = FileInfoTreeUtils.getFileInfoTreeList(fileInfoList, 0L);
        } else {
            fileInfoList = fileInfoMapper.selectOperateFileList(SecurityUtils.getTenantId(), SecurityUtils.getUserId().toString());
            if (CollectionUtils.isNotEmpty(fileInfoList)) {
                List<String> fileIdList = fileInfoList.stream().map(FileInfo::getId).map(String::valueOf).collect(Collectors.toList());
                List<FileInfo> fileInfoAndList = fileInfoMapper.selectListByAncestors(fileIdList);
                fileInfoList = FileInfoTreeUtils.getFileInfoTreeList(fileInfoAndList, 0L);
            }
        }
        fileInfoList.removeIf(fileInfo -> "2".equals(fileInfo.getFileStatus().toString()));
        return fileInfoList;
    }

    @Override
    public void doBatchMoveFile(String fileParentId, String ids) {
        //目标文件夹
        FileInfo parentFileInfo = fileInfoMapper.selectOne(FileInfo::getId, fileParentId);
        //被移动直接文件、文件夹最终目录
        String targetNewAncestors = parentFileInfo.getAncestors() + "," + parentFileInfo.getId();
        //被移动直接文件、文件夹
        List<FileInfo> fileInfoList = fileInfoMapper.selectList(new QueryWrapper<FileInfo>().lambda().in(FileInfo::getId, Arrays.asList(ids.split(","))));
        if (CollectionUtils.isNotEmpty(fileInfoList)) {
            for (FileInfo fileInfoRoot : fileInfoList) {
                //文件
                if (ConstantUtils.IS_DIRECTORY_FILE_0.equals(fileInfoRoot.getFileIsDirectory())) {
                    //同目录下、相同文件类型下、文件名称不可重复,如果重复文件名增加后缀
                    List<FileInfo> fileNameRepeatList = selectListByFileInfo(FileInfo.builder()
                            .tenantId(SecurityUtils.getTenantId())
                            .fileParentId(Long.valueOf(fileParentId))
                            .fileName(fileInfoRoot.getFileName())
                            .fileExtension(fileInfoRoot.getFileExtension())
                            .fileIsDirectory(ConstantUtils.IS_DIRECTORY_FILE_0)
                            .isDeleted(ConstantUtils.IS_DELETED_0)
                            .fileIsHide(ConstantUtils.IS_DELETED_0).build());
                    if (CollectionUtils.isNotEmpty(fileNameRepeatList)) {
                        for (FileInfo info : fileNameRepeatList) {
                            if (!(fileInfoRoot.getId() + "").equals(info.getId() + "")) {
                                fileInfoRoot.setFileName(fileInfoRoot.getFileName() + "_" + System.currentTimeMillis());
                                fileInfoRoot.setFileFullName(fileInfoRoot.getFileName() + "." + fileInfoRoot.getFileExtension());
                            }
                        }
                    }
                    fileInfoRoot.setFileParentId(parentFileInfo.getId());
                    fileInfoRoot.setAncestors(targetNewAncestors);
                    fileInfoRoot.setUpdateById(SecurityUtils.getUserId());
                    fileInfoRoot.setUpdateTime(new Date());
                    fileInfoMapper.updateById(fileInfoRoot);
                }
                //文件夹
                if (ConstantUtils.IS_DIRECTORY_FILE_1.equals(fileInfoRoot.getFileIsDirectory())) {
                    //当前文件夹
                    List<FileInfo> fileNameRepeatList = selectListByFileInfo(FileInfo.builder()
                            .tenantId(SecurityUtils.getTenantId())
                            .fileParentId(Long.valueOf(fileParentId))
                            .fileName(fileInfoRoot.getFileName())
                            .fileIsDirectory(ConstantUtils.IS_DIRECTORY_FILE_1)
                            .isDeleted(ConstantUtils.IS_DELETED_0)
                            .fileIsHide(ConstantUtils.IS_DELETED_0).build());
                    if (CollectionUtils.isNotEmpty(fileNameRepeatList)) {
                        for (FileInfo info : fileNameRepeatList) {
                            if (!(fileInfoRoot.getId() + "").equals(info.getId() + "")) {
                                fileInfoRoot.setFileName(fileInfoRoot.getFileName() + "_" + System.currentTimeMillis());
                                fileInfoRoot.setFileFullName(fileInfoRoot.getFileName());
                            }
                        }
                    }
                    //被移动文件夹下的全部文件、文件夹
                    List<FileInfo> fileInfoChildList = fileInfoMapper.selectListByParentId(fileInfoRoot.getId());
                    if (CollectionUtils.isNotEmpty(fileInfoChildList)) {
                        for (FileInfo childFile : fileInfoChildList) {
                            childFile.setAncestors(targetNewAncestors + childFile.getAncestors().substring(fileInfoRoot.getAncestors().length()));
                            childFile.setUpdateById(SecurityUtils.getUserId());
                            childFile.setUpdateTime(new Date());
                        }
                        fileInfoMapper.updateBatch(fileInfoChildList);
                    }
                    fileInfoRoot.setFileParentId(parentFileInfo.getId());
                    fileInfoRoot.setAncestors(targetNewAncestors);
                    fileInfoRoot.setUpdateById(SecurityUtils.getUserId());
                    fileInfoRoot.setUpdateTime(new Date());
                    fileInfoMapper.updateById(fileInfoRoot);
                }
            }
        }
        //目标文件夹修改时间变更
        parentFileInfo.setUpdateById(SecurityUtils.getUserId());
        parentFileInfo.setUpdateTime(new Date());
        fileInfoMapper.updateById(parentFileInfo);

        // 修改权限,所有人对移动的所有文件/文件夹的权限都继承被移动到的文件/文件夹权限,继承关系不存表，那么只需要将原来的关系全部删掉即可
        fileReUserOperateMapper.updateFileByUserOperate(SecurityUtils.getUserId().toString(), Splitter.on(",").splitToList(ids));
    }

    @Override
    public void doBatchUserFileAuth(String fileId, List<FileReUserOperate> newFileReUserOperateList) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //文件、文件夹分配权限
        for (FileReUserOperate newOperate : newFileReUserOperateList) {
            //分配权限过滤当前操作账号，即自己不可以修改自己的权限
            if (newOperate.getUserId().toString().equals(SecurityUtils.getUserId() + "")) {
                continue;
            }
            if (Objects.nonNull(newOperate.getId())) {
                if (StrUtils.isEmpty(newOperate.getFileUserAuthCode())) {
                    newOperate.setFileUserAuthId(null);
                    newOperate.setFileUserAuthCode("");
                    newOperate.setFileUserAuthDesc("");
                } else {
                    FileAuthGroup fileAuthGroup = fileAuthGroupMapper.selectOne(FileAuthGroup::getGroupCode, newOperate.getFileUserAuthCode());
                    newOperate.setFileUserAuthId(fileAuthGroup.getId());
                    newOperate.setFileUserAuthCode(fileAuthGroup.getGroupCode());
                    newOperate.setFileUserAuthDesc(fileAuthGroup.getGroupDesc());
                }
                newOperate.setUpdateById(loginUser.getUserid());
                newOperate.setUpdateTime(new Date());
                fileReUserOperateMapper.updateById(newOperate);
            } else {
                if (StrUtils.isNotEmpty(newOperate.getFileUserAuthCode())) {
                    newOperate.setTenantId(SecurityUtils.getTenantId());
                    newOperate.setFileId(Long.valueOf(fileId));
                    FileAuthGroup fileAuthGroup = fileAuthGroupMapper.selectOne(FileAuthGroup::getGroupCode, newOperate.getFileUserAuthCode());
                    newOperate.setFileUserAuthId(fileAuthGroup.getId());
                    newOperate.setFileUserAuthCode(fileAuthGroup.getGroupCode());
                    newOperate.setFileUserAuthDesc(fileAuthGroup.getGroupDesc());
                    doSetFileReUserOperate(newOperate, loginUser);
                    fileReUserOperateMapper.insert(newOperate);
                } else {
                    newOperate.setTenantId(SecurityUtils.getTenantId());
                    newOperate.setFileId(Long.valueOf(fileId));
                    newOperate.setFileUserAuthId(null);
                    newOperate.setFileUserAuthCode("");
                    newOperate.setFileUserAuthDesc("");
                    doSetFileReUserOperate(newOperate, loginUser);
                    fileReUserOperateMapper.insert(newOperate);
                }
            }
        }
    }


    @Override
    public List<FileInfo> selectListByFileInfo(FileInfo fileInfo) {
        LambdaQueryWrapper<FileInfo> lambdaQueryWrapper = new QueryWrapper<FileInfo>().lambda();
        lambdaQueryWrapper.eq(StrUtils.isNotEmpty(fileInfo.getFileParentId() + ""), FileInfo::getFileParentId, fileInfo.getFileParentId());
        lambdaQueryWrapper.eq(StrUtils.isNotEmpty(fileInfo.getFileName()), FileInfo::getFileName, fileInfo.getFileName());
        lambdaQueryWrapper.eq(StrUtils.isNotEmpty(fileInfo.getFileExtension()), FileInfo::getFileExtension, fileInfo.getFileExtension());
        lambdaQueryWrapper.eq(StrUtils.isNotEmpty(fileInfo.getTenantId() + ""), FileInfo::getTenantId, fileInfo.getTenantId());
        lambdaQueryWrapper.eq(StrUtils.isNotEmpty(fileInfo.getServiceName()), FileInfo::getServiceName, fileInfo.getServiceName());
        lambdaQueryWrapper.eq(StrUtils.isNotEmpty(fileInfo.getFileIsDirectory()), FileInfo::getFileIsDirectory, fileInfo.getFileIsDirectory());
        lambdaQueryWrapper.eq(FileInfo::getFileIsHide, ConstantUtils.IS_DELETED_0);
        lambdaQueryWrapper.eq(FileInfo::getIsDeleted, ConstantUtils.IS_DELETED_0);
        return fileInfoMapper.selectList(lambdaQueryWrapper);
    }

    @Override
    public void logicalDeleteByFileIds(String fileIds) {
        fileInfoMapper.deleteFileByIds(fileIds, SecurityUtils.getUserId());
    }

    /**
     * 通过文件对象和文件url生成fileInfo对象
     *
     * @param file
     * @param url
     * @return
     */
    @NotNull
    private FileInfo getFileInfo(MultipartFile file, String url) {
        FileInfo fileInfo = new FileInfo();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        fileInfo.setFileExtension(FilenameUtils.getExtension(file.getOriginalFilename()));
        fileInfo.setFileName(file.getOriginalFilename().replace("." + fileInfo.getFileExtension(), ""));
        fileInfo.setFileFullName(file.getOriginalFilename());
        fileInfo.setFileUrl(url);
        fileInfo.setFilePreviewUrl(url);
        fileInfo.setFileStorageName(url.substring(url.lastIndexOf("/") + 1, url.length()));
        fileInfo.setFileParentId(Long.valueOf(ConstantUtils.FILE_ANCESTORS));
        fileInfo.setFileIsHide(ConstantUtils.IS_DELETED_0);
        fileInfo.setIsDeleted(ConstantUtils.IS_DELETED_0);
        fileInfo.setFileStatus(ConstantUtils.SHOW_STATUS_FIX_10);
        fileInfo.setFileIsDirectory(ConstantUtils.IS_DIRECTORY_FILE_0);
        fileInfo.setFileSize(file.getSize());
        fileInfo.setFileType(FileUtils.parseFileType(FilenameUtils.getExtension(file.getOriginalFilename()).toLowerCase()));
        doSetFileInfo(fileInfo, loginUser);
        fileInfo.setTenantId(SecurityUtils.getTenantId());
        return fileInfo;
    }

    /**
     * 设置文件对象默认值
     */
    private void doSetFileInfo(FileInfo fileInfo, LoginUser loginUser) {
        fileInfo.setCreateById(loginUser.getUserid());
        fileInfo.setCreateTime(new Date());
        fileInfo.setUpdateById(loginUser.getUserid());
        fileInfo.setUpdateTime(new Date());
    }

    /**
     * 设置件与用户的操作关系对象默认值
     */
    private void doSetFileReUserOperate(FileReUserOperate fileReUserOperate, LoginUser loginUser) {
        fileReUserOperate.setIsDeleted(ConstantUtils.IS_DELETED_0);
        fileReUserOperate.setCreateById(loginUser.getUserid());
        fileReUserOperate.setCreateTime(new Date());
        fileReUserOperate.setUpdateById(loginUser.getUserid());
        fileReUserOperate.setUpdateTime(new Date());
    }
}
