import { computed, ref } from 'vue';
import type { QueryUserFirstLevelTreeRes } from '@/types/person-group/type';
import type { TreeNode } from '@/views/disaster/types';
import { getUserFirstLevelTree } from '@/api/system/person-group';
import { useUserInfoHook as useUserHook } from '@/hooks/useUserInfoHook';

/**
 * 获取登录账户信息
 */
export const useUserInfoHook = () => {
  const { id, realname, permissions, staffNo } = useUserHook();
  const userFirstLevelTreeList = ref<QueryUserFirstLevelTreeRes>();
  const getUserFirstLevelTreeList = async () => {
    const res = await getUserFirstLevelTree();
    userFirstLevelTreeList.value = res;
  };
  // 将组织树数据转换为树形选择器所需的格式
  const treeData = computed<TreeNode[]>(() => {
    if (!userFirstLevelTreeList.value) return [];

    // 将组织树转换为树形选择器需要的格式
    const convertToTreeData = (tree: QueryUserFirstLevelTreeRes): TreeNode => {
      const node: TreeNode = {
        id: tree.id,
        label: tree.deptName,
        isUser: false,
        children: [],
      };

      // 添加部门下的用户
      if (tree.userList && tree.userList.length) {
        const userNodes: TreeNode[] = tree.userList.map((user) => ({
          id: user.id,
          label: `${user.realname}（${user.staffNo}）`,
          isUser: true,
          staffNo: user.staffNo,
        }));
        node.children = node.children || [];
        node.children = [...node.children, ...userNodes];
      }

      // 添加子部门
      if (tree.children && tree.children.length) {
        const childNodes = tree.children.map((child) => convertToTreeData(child));
        node.children = node.children || [];
        node.children = [...node.children, ...childNodes];
      }

      return node;
    };

    return [convertToTreeData(userFirstLevelTreeList.value)];
  });
  return {
    id,
    realname,
    permissions,
    staffNo,
    treeData,
    getUserFirstLevelTreeList,
  };
};
