package com.yushu.system.service.impl;

import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yushu.common.utils.DateUtils;
import com.yushu.common.utils.SecurityUtils;
import com.yushu.system.mapper.SysFolderMapper;
import com.yushu.system.mapper.SysFileMapper;
import com.yushu.system.domain.SysFolder;
import com.yushu.system.service.ISysFolderService;
import com.yushu.common.exception.ServiceException;

/**
 * 文件夹Service业务层处理
 * 
 * @author yushu
 * @date 2024-11-15
 */
@Service
public class SysFolderServiceImpl implements ISysFolderService 
{
    @Autowired
    private SysFolderMapper sysFolderMapper;
    
    @Autowired
    private SysFileMapper sysFileMapper;

    /**
     * 查询文件夹
     * 
     * @param folderId 文件夹主键
     * @return 文件夹
     */
    @Override
    public SysFolder selectSysFolderByFolderId(Long folderId)
    {
        return sysFolderMapper.selectSysFolderByFolderId(folderId);
    }

    /**
     * 查询文件夹列表
     * 
     * @param sysFolder 文件夹
     * @return 文件夹
     */
    @Override
    public List<SysFolder> selectSysFolderList(SysFolder sysFolder)
    {
        return sysFolderMapper.selectSysFolderList(sysFolder);
    }

    /**
     * 新增文件夹
     * 
     * @param sysFolder 文件夹
     * @return 结果
     */
    @Override
    public int insertSysFolder(SysFolder sysFolder)
    {
        sysFolder.setUserId(SecurityUtils.getUserId());
        sysFolder.setCreateBy(SecurityUtils.getUsername());
        sysFolder.setCreateTime(DateUtils.getNowDate());
        return sysFolderMapper.insertSysFolder(sysFolder);
    }

    /**
     * 修改文件夹
     * 
     * @param sysFolder 文件夹
     * @return 结果
     */
    @Override
    public int updateSysFolder(SysFolder sysFolder)
    {
        sysFolder.setUpdateTime(DateUtils.getNowDate());
        return sysFolderMapper.updateSysFolder(sysFolder);
    }

    /**
     * 批量删除文件夹（递归删除）
     * 
     * @param folderIds 需要删除的文件夹主键
     * @return 结果
     */
    @Override
    public int deleteSysFolderByFolderIds(Long[] folderIds)
    {
        int count = 0;
        // 递归删除每个文件夹
        for (Long folderId : folderIds)
        {
            deleteRecursive(folderId);
            count += sysFolderMapper.deleteSysFolderByFolderId(folderId);
        }
        return count;
    }

    /**
     * 删除文件夹信息（递归删除）
     * 
     * @param folderId 文件夹主键
     * @return 结果
     */
    @Override
    public int deleteSysFolderByFolderId(Long folderId)
    {
        // 递归删除所有子文件夹和文件
        deleteRecursive(folderId);
        
        // 删除当前文件夹
        return sysFolderMapper.deleteSysFolderByFolderId(folderId);
    }
    
    /**
     * 递归删除文件夹及其所有内容
     * 
     * @param folderId 文件夹ID
     */
    private void deleteRecursive(Long folderId)
    {
        // 1. 删除该文件夹下的所有文件
        sysFileMapper.deleteFilesByFolderId(folderId);
        
        // 2. 查找所有子文件夹
        SysFolder query = new SysFolder();
        query.setParentId(folderId);
        List<SysFolder> children = sysFolderMapper.selectSysFolderList(query);
        
        // 3. 递归删除每个子文件夹
        for (SysFolder child : children)
        {
            deleteRecursive(child.getFolderId());
            sysFolderMapper.deleteSysFolderByFolderId(child.getFolderId());
        }
    }
    
    /**
     * 构建文件夹树
     * 
     * @param folders 文件夹列表
     * @return 树结构列表
     */
    @Override
    public List<SysFolder> buildFolderTree(List<SysFolder> folders)
    {
        List<SysFolder> returnList = new ArrayList<>();
        List<Long> tempList = folders.stream().map(SysFolder::getFolderId).collect(Collectors.toList());
        
        for (SysFolder folder : folders)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(folder.getParentId()))
            {
                recursionFn(folders, folder);
                returnList.add(folder);
            }
        }
        
        if (returnList.isEmpty())
        {
            returnList = folders;
        }
        return returnList;
    }
    
    /**
     * 递归列表
     */
    private void recursionFn(List<SysFolder> list, SysFolder t)
    {
        // 得到子节点列表
        List<SysFolder> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysFolder tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }
    
    /**
     * 得到子节点列表
     */
    private List<SysFolder> getChildList(List<SysFolder> list, SysFolder t)
    {
        List<SysFolder> tlist = new ArrayList<>();
        for (SysFolder n : list)
        {
            if (n.getParentId() != null && n.getParentId().longValue() == t.getFolderId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }
    
    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysFolder> list, SysFolder t)
    {
        return getChildList(list, t).size() > 0;
    }
    
    /**
     * 复制文件夹
     * 
     * @param folderId 文件夹ID
     * @param targetFolderId 目标文件夹ID
     * @return 结果
     */
    @Override
    public int copyFolder(Long folderId, Long targetFolderId)
    {
        // 查询原文件夹
        SysFolder originalFolder = sysFolderMapper.selectSysFolderByFolderId(folderId);
        if (originalFolder == null)
        {
            throw new ServiceException("文件夹不存在");
        }
        
        // 创建新文件夹
        SysFolder newFolder = new SysFolder();
        newFolder.setParentId(targetFolderId);
        newFolder.setFolderName(generateCopyFolderName(originalFolder.getFolderName(), targetFolderId));
        newFolder.setUserId(SecurityUtils.getUserId());
        newFolder.setCreateTime(DateUtils.getNowDate());
        
        int result = sysFolderMapper.insertSysFolder(newFolder);
        
        if (result > 0)
        {
            // 递归复制子文件夹和文件
            copyFolderContents(folderId, newFolder.getFolderId());
        }
        
        return result;
    }
    
    /**
     * 复制文件夹内容（递归）
     */
    private void copyFolderContents(Long sourceFolderId, Long targetFolderId)
    {
        // 复制子文件夹
        SysFolder query = new SysFolder();
        query.setParentId(sourceFolderId);
        List<SysFolder> subFolders = sysFolderMapper.selectSysFolderList(query);
        
        for (SysFolder subFolder : subFolders)
        {
            copyFolder(subFolder.getFolderId(), targetFolderId);
        }
        
        // 复制文件（需要注入SysFileService）
        // 暂时简化处理，只复制文件夹结构
    }
    
    /**
     * 生成复制文件夹名
     */
    private String generateCopyFolderName(String originalName, Long targetFolderId)
    {
        // 检查目标文件夹中是否存在同名文件夹
        String newName = originalName;
        int copyNum = 1;
        while (folderNameExists(newName, targetFolderId))
        {
            newName = originalName + " (" + copyNum + ")";
            copyNum++;
        }
        
        return newName;
    }
    
    /**
     * 检查文件夹名是否存在
     */
    private boolean folderNameExists(String folderName, Long parentId)
    {
        SysFolder query = new SysFolder();
        query.setFolderName(folderName);
        query.setParentId(parentId);
        List<SysFolder> folders = sysFolderMapper.selectSysFolderList(query);
        return folders != null && !folders.isEmpty();
    }
}
