package com.youlai.boot.system.controller;


import cn.hutool.core.util.StrUtil;
import com.youlai.boot.common.result.Result;
import com.youlai.boot.system.model.entity.SysFolder;
import com.youlai.boot.system.service.SysFolderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/api/folders")
public class FolderController {

    @Autowired
    private SysFolderService folderService;

    @GetMapping("/tree/{type}")
    public Result getFolderTree(@PathVariable("type") String type) {
        List<SysFolder> folderTree = folderService.getFolderTree(type);
        return Result.success(folderTree);
    }

    @GetMapping("/{parentId}/subtree")
    public Result getSubFolderTree(@PathVariable Integer parentId) {
        List<SysFolder> subTree = folderService.getSubFolderTree(parentId);

        return Result.success(subTree);
    }

    @GetMapping("/ancestors/{id}")
    public Result getAncestors(@PathVariable("id") Integer id) {
        SysFolder sysFolder = folderService.getById(id);
        String ancestorIds = sysFolder.getAncestorIds();
        ArrayList<SysFolder> list = new ArrayList<>();
        if (StrUtil.isNotBlank(ancestorIds)) {
            List<SysFolder> sysFolders = folderService.getBaseMapper().selectBatchIds(Arrays.stream(ancestorIds.split(",")).toList());
            list.addAll(sysFolders);
        }
        list.add(sysFolder);
        return Result.success(list);
    }

    @PostMapping
    public Result createFolder(@RequestBody SysFolder folder) {
        boolean success = folderService.createFolder(folder);
        return Result.success(success);
    }

    @DeleteMapping("/{folderId}")
    public Result deleteFolder(@PathVariable Integer folderId) {
        boolean success = folderService.deleteFolder(folderId);
        if (success) {
            return Result.success(success);
        } else {
            return Result.failed("删除失败，该文件夹下存在子文件");
        }
    }

    @PutMapping("/{folderId}/{newName}")
    public Result renameFolder(@PathVariable Integer folderId,
                               @PathVariable String newName) {
        boolean success = folderService.renameFolder(folderId, newName);
        if (success) {
            return Result.success(success);
        } else {
            return Result.failed("重命名失败");
        }

    }
}    