package com.zxdmy.excite.admin.controller.cloud.space;


import cn.dev33.satoken.stp.StpUtil;
import com.zxdmy.excite.common.base.BaseResult;
import com.zxdmy.excite.common.entity.PageList;
import com.zxdmy.excite.framework.aop.AnnotationSaveReLog;
import com.zxdmy.excite.system.entity.cloud.role.CloudRole;
import com.zxdmy.excite.system.entity.cloud.space.CloudFile;
import com.zxdmy.excite.system.entity.cloud.space.CloudFileRole;
import com.zxdmy.excite.system.entity.dto.FileTreeDTO;
import com.zxdmy.excite.system.entity.req.space.ReqCloudFile;
import com.zxdmy.excite.system.entity.vo.space.*;
import com.zxdmy.excite.system.service.cloud.role.ICloudRoleUserService;
import com.zxdmy.excite.system.service.cloud.space.ICloudFileRoleService;
import com.zxdmy.excite.system.service.cloud.space.ICloudFileService;
import lombok.AllArgsConstructor;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import com.zxdmy.excite.common.base.BaseController;

import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 文件表 前端控制器
 * </p>
 *
 * @author ss
 * @since 2026-01-28
 */
@Controller
@AllArgsConstructor
@RequestMapping("/cloud/space")
public class CloudFileController extends BaseController {


    private ICloudFileService iCloudFileService;
    private ICloudRoleUserService iCloudRoleUserService;
    private ICloudFileRoleService iCloudFileRoleService;
    @RequestMapping("index")
    public String index() {
        return "cloud/space/file/index";
    }


    @GetMapping("/list")
    @ResponseBody
    public BaseResult getPageList(Integer page, Integer limit, ReqCloudFile data) {
        try {
            CloudRole cloudRole = iCloudRoleUserService.getCloudShareRole(StpUtil.getLoginIdAsInt());
            PageList<CloudFileVo> dataPage = iCloudFileService.queryByPage(page, limit, data);
            if(null!=cloudRole){
                if (cloudRole.getRoleDown()>0) {
                    for (CloudFileVo cloudFileVo:dataPage.getList()) {
                        cloudFileVo.setRoleDown(1);
                    }
                }
                if (cloudRole.getRoleUpload()>0) {
                    for (CloudFileVo cloudFileVo:dataPage.getList()) {
                        cloudFileVo.setRoleUpload(1);
                    }
                }
                if (cloudRole.getRoleDelete()>0) {
                    for (CloudFileVo cloudFileVo:dataPage.getList()) {
                        cloudFileVo.setRoleDelete(1);
                    }
                }
            }
            return success("获取数据成功", dataPage.getList(), (int) dataPage.getTotal());
        } catch (Exception e) {
            return error(500, "发生错误:" + e.getMessage());
        }
    }

    @RequestMapping("add")
    public String add() {
        return "cloud/space/file/add";
    }

    @PostMapping("/addSave")
    @ResponseBody
    @AnnotationSaveReLog
    public BaseResult addSave(@Validated ReqCloudFile data) {
        try {
            if(null == iCloudFileService.getByData(data)){
                if(iCloudFileService.saveData(data)==1){
                    return success("操作成功");
                }else{
                    return error(400, "操作失败，系统错误");
                }
            }else{
                return error(400, "操作失败，数据已存在");
            }
        } catch (Exception e) {
            return error(500, "发生错误:" + e.getMessage());
        }
    }

    @GetMapping("/getData")
    @ResponseBody
    public BaseResult getData(String id) {
        try {
            CloudFileVo data = new CloudFileVo();
            CloudFile cloudFile = iCloudFileService.getById(id);
            if(null!=cloudFile){
                BeanUtils.copyProperties(data, cloudFile);
            }
            if(null!=cloudFile){
                return success("获取数据成功",data);
            }else{
                return error(400, "数据不存在！");
            }


        } catch (Exception e) {
            return error(500, "发生错误:" + e.getMessage());
        }
    }

    @RequestMapping("edit/{id}")
    public String edit(@PathVariable String id, ModelMap map) throws InvocationTargetException, IllegalAccessException {

        CloudFileVo data = new CloudFileVo();
        CloudFile cloudFile = iCloudFileService.getById(id);
        if(null!=cloudFile){
            BeanUtils.copyProperties(data, cloudFile);
        }
        // 加载至前端
        if (cloudFile == null) {
            map.put("code", 404);
            map.put("msg", "数据不存在！");
            return "error/error";
        }
        map.put("id", id);
        return "cloud/space/file/edit";
    }

    @PostMapping("/editSave")
    @ResponseBody
    @AnnotationSaveReLog
    public BaseResult editSave(@Validated ReqCloudFile data) {
        try {
            CloudFileVo cloudFileVo = iCloudFileService.getByData(data);
            CloudFile cloudFile = iCloudFileService.getById(data.getId());
            if(cloudFileVo==null){
                if(iCloudFileService.updateData(data)==1){
                    return success(200,"操作成功");
                }else{
                    return error(400, "操作失败，系统错误");
                }
            }else{
                if (cloudFile.getFileName().equals(data.getFileName())) {
                    if(iCloudFileService.updateData(data)==1){
                        return success(200,"操作成功");
                    }else{
                        return error(400, "操作失败，系统错误");
                    }
                }else{
                    return error(400, "操作失败，数据已存在");
                }
            }

        } catch (Exception e) {
            return error(500, "发生错误:" + e.getMessage());
        }
    }


    @PostMapping("/delete")
    @ResponseBody
    @AnnotationSaveReLog
    public BaseResult delete(String id) {
        try {
            int result = iCloudFileService.deleteById(id);
            if (result == 1) {
                return success(200, "删除成功！");
            }else{
                return error("删除失败！");
            }
        } catch (Exception e) {
            return error("发生错误:" + e.getMessage());
        }
    }


    @GetMapping("/getFileRole")
    @ResponseBody
    public BaseResult getFileRole(String id) {
        try {
            CloudFilleUserVo cloudFilleUserVo = new CloudFilleUserVo();
            List<CloudFileRoleVo> dataPage = iCloudFileRoleService.getFileRole(id);

            List<Integer> ids = dataPage.stream()
                    .map(CloudFileRoleVo::getUserId)
                    .collect(Collectors.toList());
            cloudFilleUserVo.setIds(ids);

            String names = dataPage.stream()
                    .map(CloudFileRoleVo::getUserName)
                    .collect(Collectors.joining(", "));

            String userIDs = dataPage.stream()
                    .map(CloudFileRoleVo -> String.valueOf(CloudFileRoleVo.getId()))
                    .collect(Collectors.joining(", "));
            cloudFilleUserVo.setUserId(userIDs);
            cloudFilleUserVo.setName(names);
            return success("获取数据成功", cloudFilleUserVo);
        } catch (Exception e) {
            return error(500, "发生错误:" + e.getMessage());
        }
    }



    @GetMapping("/getRoleFile")
    @ResponseBody
    public BaseResult getRoleFile(String id) {
        try {
            CloudRoleFolderVo cloudRoleFolderVo = new CloudRoleFolderVo();
            List<CloudRoleFileVo> dataPage = iCloudFileRoleService.getRoleFile(id);

            List<Long> ids = dataPage.stream()
                    .map(CloudRoleFileVo::getFileId)
                    .collect(Collectors.toList());
            cloudRoleFolderVo.setIds(ids);

            String names = dataPage.stream()
                    .map(CloudRoleFileVo::getFileName)
                    .collect(Collectors.joining(", "));

            String userIDs = dataPage.stream()
                    .map(CloudRoleFileVo -> String.valueOf(CloudRoleFileVo.getId()))
                    .collect(Collectors.joining(", "));
            cloudRoleFolderVo.setRoleId(userIDs);
            cloudRoleFolderVo.setName(names);
            return success("获取数据成功", cloudRoleFolderVo);
        } catch (Exception e) {
            return error(500, "发生错误:" + e.getMessage());
        }
    }

    @GetMapping("/getRoleFileCheck")
    @ResponseBody
    public BaseResult getRoleFileCheck(String id) {
        try {
            CloudRoleFolderVo cloudRoleFolderVo = new CloudRoleFolderVo();
            List<CloudRoleFileVo> dataPage = iCloudFileRoleService.getRoleFileCheck(id);

            List<Long> ids = dataPage.stream()
                    .map(CloudRoleFileVo::getFileId)
                    .collect(Collectors.toList());
            cloudRoleFolderVo.setIds(ids);

            String names = dataPage.stream()
                    .map(CloudRoleFileVo::getFileName)
                    .collect(Collectors.joining(", "));

            String userIDs = dataPage.stream()
                    .map(CloudRoleFileVo -> String.valueOf(CloudRoleFileVo.getId()))
                    .collect(Collectors.joining(", "));
            cloudRoleFolderVo.setRoleId(userIDs);
            cloudRoleFolderVo.setName(names);
            return success("获取数据成功", cloudRoleFolderVo);
        } catch (Exception e) {
            return error(500, "发生错误:" + e.getMessage());
        }
    }
    @PostMapping(value = "/changeDeleteStatus/{status}")
    @ResponseBody
    public BaseResult changeDeleteStatus(@PathVariable String status, String[] ids) {
        try {
            int[] result = iCloudFileService.changeDeleteStatus(Integer.parseInt(status), ids);
            // 没有失败
            if (result[0] != 0 && result[1] == 0) {
                return success(200, "修改成功！");
            }
            // 有成功的
            else if (result[0] != 0) {
                return success(200, result[0] + "个更新成功，" + result[1] + "个失败！");
            } else {
                return success(500, "修改失败，请重试！");
            }
        } catch (Exception e) {
            return error(500, "发生错误:" + e.getMessage());
        }
    }



    @GetMapping("/queryByIndexPage")
    @ResponseBody
    public BaseResult queryByIndexPage(Integer page, Integer limit, ReqCloudFile data) {
        try {
            page=1;
            limit=15;
            List<CloudFileRole> list = iCloudFileRoleService.getFileRoleByUseId(StpUtil.getLoginIdAsInt());

            List<Long> ids = list.stream()
                    .map(CloudFileRole::getFileId)
                    .collect(Collectors.toList());
            data.setFileIds(ids);

            PageList<CloudFileVo> dataPage = iCloudFileService.queryByIndexPage(page, limit, data);

            return success("获取数据成功", dataPage.getList(), (int) dataPage.getTotal());
        } catch (Exception e) {
            return error(500, "发生错误:" + e.getMessage());
        }
    }



    @RequestMapping("authFile")
    public String authFile() {
        return "cloud/space/file/authFile";
    }
    @RequestMapping("updateAuthFile/{id}")
    public String updateAuthFile(@PathVariable String id, ModelMap map) {
        map.put("id",id);
        return "cloud/space/file/updateAuthFile";
    }
    @GetMapping("/query")
    @ResponseBody
    public BaseResult query() {
        try {
            ReqCloudFile data = new ReqCloudFile();
            List<CloudFileVo> dataPage = iCloudFileService.queryFileByData(data);
            List<FileTreeDTO> department = buildDepartmentTree(dataPage);
            return success(200, "获取数据成功！",department);
        } catch (Exception e) {
            return error(500, "发生错误:" + e.getMessage());
        }
    }


    public List<FileTreeDTO> buildDepartmentTree(List<CloudFileVo> departments) {
        // 1. 按parentId分组
        Map<Long, List<FileTreeDTO>> parentMap = new HashMap<>();
        // 2. 创建所有节点的映射
        Map<Long, FileTreeDTO> nodeMap = new HashMap<>();
        // 3. 转换并分组
        for (CloudFileVo dept : departments) {
            FileTreeDTO node = new FileTreeDTO();
            org.springframework.beans.BeanUtils.copyProperties(dept, node);
            node.setChildren(new ArrayList<>());
            nodeMap.put(dept.getId(), node);

            Long parentId = dept.getFileParentId();
            if (parentId == null) {
                parentId = 0L; // 将null转换为0，作为根节点的父ID
            }

            parentMap.computeIfAbsent(parentId, k -> new ArrayList<>())
                    .add(node);
        }

        // 4. 构建树形结构
        List<FileTreeDTO> rootList = parentMap.getOrDefault(0L, new ArrayList<>());

        // 5. 递归构建子节点
        for (Long parentId : parentMap.keySet()) {
            if (parentId.equals(0L)) continue;

            FileTreeDTO parentNode = nodeMap.get(parentId);
            if (parentNode != null) {
                parentNode.setChildren(parentMap.get(parentId));
            }
        }

        // 6. 排序（按department_sort）
        sortTreeNodes(rootList);

        return rootList;
    }

    private void sortTreeNodes(List<FileTreeDTO> nodes) {
        if (nodes == null || nodes.isEmpty()) return;

        // 按排序字段排序
        nodes.sort(Comparator.comparing(FileTreeDTO::getFileSort));

        // 递归排序子节点
        for (FileTreeDTO node : nodes) {
            if (node.getChildren() != null && !node.getChildren().isEmpty()) {
                sortTreeNodes(node.getChildren());
            }
        }
    }

}
