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

import com.zxdmy.excite.common.base.BaseController;
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.account.CloudCompany;
import com.zxdmy.excite.system.entity.cloud.account.CloudDepartment;
import com.zxdmy.excite.system.entity.dto.DepartmentTreeDTO;
import com.zxdmy.excite.system.entity.dto.DepartmentUserTreeNode;
import com.zxdmy.excite.system.entity.req.account.ReqDepartment;
import com.zxdmy.excite.system.entity.vo.account.DepartmentVo;
import com.zxdmy.excite.system.service.cloud.account.ICloudCompanyService;
import com.zxdmy.excite.system.service.cloud.account.ICloudDepartmentService;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Controller
@AllArgsConstructor
@RequestMapping("/cloud/account/department/")
public class AccountDepartmentController extends BaseController {

    private ICloudDepartmentService iCloudDepartmentService;
    private ICloudCompanyService iCloudCompanyService;
    @RequestMapping("index")
    public String index() {
        return "cloud/account/department/index";
    }


    @GetMapping("/list")
    @ResponseBody
    public BaseResult getPageList(Integer page, Integer limit, ReqDepartment data) {
        try {
            PageList<DepartmentVo> dataPage = iCloudDepartmentService.queryByPage(page, limit, data);
            return success("获取数据成功", dataPage.getList(), (int) dataPage.getTotal());
        } catch (Exception e) {
            return error(500, "发生错误:" + e.getMessage());
        }
    }


    @RequestMapping("add")
    public String add() {
        return "cloud/account/department/add";
    }

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

    @RequestMapping("edit/{id}")
    public String edit(@PathVariable String id, ModelMap map) {
        CloudDepartment data = iCloudDepartmentService.getById(id);
        // 加载至前端
        if (data == null) {
            map.put("code", 404);
            map.put("msg", "数据不存在！");
            return "error/error";
        }
        map.put("id", id);
        return "cloud/account/department/edit";
    }

    @GetMapping("/getData")
    @ResponseBody
    public BaseResult getData(ReqDepartment req) {
        try {
            DepartmentVo data = iCloudDepartmentService.getByData(req);
            if(null!=data){
                return success("获取数据成功",data);
            }else{
                return error(400, "数据不存在！");
            }


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

    @PostMapping("/editSave")
    @ResponseBody
    @AnnotationSaveReLog
    public BaseResult editSave(@Validated ReqDepartment data) {
        try {
            if(null == iCloudDepartmentService.getByData(data)){
                if(iCloudDepartmentService.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 = iCloudDepartmentService.deleteById(id);
            if (result == 1) {
                return success(200, "删除成功！");
            }else{
                return error("删除失败！");
            }
        } catch (Exception e) {
            return error("发生错误:" + e.getMessage());
        }
    }


    @GetMapping("/query")
    @ResponseBody
    public BaseResult query() {
        try {
            List<DepartmentTreeDTO> data = new ArrayList<>();
            List<CloudCompany> company = iCloudCompanyService.getList();
            for (CloudCompany cloudCompany :company) {
                DepartmentTreeDTO departmentTreeDTO = new DepartmentTreeDTO();
                departmentTreeDTO.setId(cloudCompany.getId());
                departmentTreeDTO.setTitle(cloudCompany.getCompanyName());
                departmentTreeDTO.setSpread(true);
                List<CloudDepartment> dataPage = iCloudDepartmentService.getList(cloudCompany.getId());
                List<DepartmentTreeDTO> department = buildDepartmentTree(dataPage);
                departmentTreeDTO.setChildren(department);
                data.add(departmentTreeDTO);
            }

            return success(200, "获取数据成功！",data);
        } catch (Exception e) {
            return error(500, "发生错误:" + e.getMessage());
        }
    }
    @GetMapping("/query1")
    @ResponseBody
    public BaseResult query1() {
        try {
            List<DepartmentUserTreeNode> data = new ArrayList<>();
            List<CloudCompany> company = iCloudCompanyService.getList();
            for (CloudCompany cloudCompany :company) {
                CloudDepartment cloudDepartment = new CloudDepartment();
                cloudDepartment.setId(cloudCompany.getId());
                cloudDepartment.setDepartmentName(cloudCompany.getCompanyName());
                DepartmentUserTreeNode departmentTreeDTO = new DepartmentUserTreeNode(cloudDepartment);
                List<DepartmentUserTreeNode> tree = iCloudDepartmentService.buildDepartmentUserTree(cloudCompany.getId());
                departmentTreeDTO.setChildren(tree);
                data.add(departmentTreeDTO);
                System.out.println(tree);
            }

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

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

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

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

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

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

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

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

        return rootList;
    }

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

        // 按排序字段排序
        nodes.sort(Comparator.comparing(DepartmentTreeDTO::getDepartmentSort));

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