import { http } from "@/utils/http";
import { ref } from "vue";
// 部门
type addDept = {
  code: number;
  msg: string;
  data: boolean;
};
type addDeptList = {
  code: number;
  msg: string;
  data: Array<any>;
};

export const postAddDept = data => {
  return http.request<addDept>("post", "/sysDept/addDept", { data });
};
export const postDelDept = data => {
  return http.request<addDept>("post", "/sysDept/delDept", { data });
};
export const postListTree = () => {
  return http.request<addDeptList>("post", "/sysDept/listTree");
};
export const postUpdateDept = data => {
  return http.request<addDept>("post", "/sysDept/updateDept", { data });
};
// 部门下新建人员
export const postDeptUserAdd = data => {
  return http.request<addDept>("post", "/sysDept/deptUserAdd", { data });
};
// 部门下树（包含用户信息）
export const postListTreeWithUser = () => {
  return http.request<addDeptList>("post", "/sysDept/listTreeWithUser");
};
export const treeDept = ref([]);
export const postListTreeWithUserApi = async () => {
  const res = await postListTreeWithUser();
  let treeList = res.data.map(item => {
    return {
      childrenRes: item.childrenRes,
      childrenUserRes: item.childrenUserRes,
      userCodeNew: item.deptCode,
      userNameNew: item.deptName
    };
  });
  treeDept.value = transformData(treeList);
  // console.log("treeDept.value", transformData(treeList));
  // console.log("treeDept", res.data);
};
function transformData(
  data,
  newDeptCodeKey = "userCodeNew",
  newDeptNameKey = "userNameNew"
) {
  return data.map(item => {
    const newItem = { ...item };

    // 合并 childrenUserRes 和 childrenRes，并添加类型标识
    newItem.children = [
      ...(newItem.childrenUserRes || []).map(child => ({
        ...child,
        type: "user"
      })),
      ...(newItem.childrenRes || []).map(child => ({ ...child, type: "dept" }))
    ];
    delete newItem.childrenUserRes;
    delete newItem.childrenRes;

    // 重命名属性
    newItem.children = newItem.children.map(child => {
      const newChild = { ...child };
      if (child.type === "user") {
        newChild.userNameNew = child.realName;
        newChild.userCodeNew = child.userCode;
      } else if (child.type === "dept") {
        newChild[newDeptCodeKey] = child.deptCode;
        newChild[newDeptNameKey] = child.deptName;
      }
      return newChild;
    });

    // 递归处理子节点
    if (newItem.children && newItem.children.length) {
      newItem.children = transformData(
        newItem.children,
        newDeptCodeKey,
        newDeptNameKey
      );
    }

    return newItem;
  });
}
