interface TreeNode {
  children?: TreeNode[];
  users?: {
    idtUserWorkNo: string;
    // 其他用户属性
  }[];
}

/**
 * 从树形结构数据中查找 idtUserWorkNo 相等的用户项
 * @param nodes 树形结构数据
 * @param workNo 要查找的工号
 * @returns 找到的用户项，如果未找到则返回 undefined
 */
export function findUserByWorkNo(nodes: TreeNode[], workNo: string) {
  for (const node of nodes) {
    if (node.users) {
      const foundUser = node.users.find((user) => user.idtUserWorkNo === workNo);
      if (foundUser) {
        return foundUser;
      }
    }
    if (node.children) {
      const result = findUserByWorkNo(node.children, workNo);
      if (result) {
        return result;
      }
    }
  }
  return undefined;
}

interface TreeNode {
  children?: TreeNode[];
  idtOrgId?: string;
  users?: {
    idtUserWorkNo: string;
  }[];
}

/**
 * 从树形结构数据中查找 idtUserWorkNo 相等的用户项，并返回其同级别的 idtOrgOrgCode
 * @param nodes 树形结构数据
 * @param workNo 要查找的工号
 * @returns 找到的 idtOrgId undefined
 */
export function findOrgCodeByWorkNo(nodes: TreeNode[], workNo: string): string | undefined {
  for (const node of nodes) {
    if (node.users) {
      const foundUser = node.users.find((user) => user.idtUserWorkNo === workNo);
      if (foundUser) {
        return node.deptId;
      }
    }
    if (node.children) {
      const result = findOrgCodeByWorkNo(node.children, workNo);
      if (result) {
        return result;
      }
    }
  }
  return undefined;
}

interface TreeNode {
  children?: TreeNode[];
  deptName?: string;
  deptId?: string;
  users?: {
    appAccountAccountName: string;
    idtUserWorkNo: string;
  }[];
}

export interface TransformedTreeNode {
  label: string;
  value: string;
  children?: TransformedTreeNode[];
}

/**
 * 将原始树形结构数据转换为指定格式的树形结构
 * @param nodes 原始树形结构数据
 * @returns 转换后的树形结构数据
 */
export const transformTreeData = (nodes: TreeNode[], isNeedUser = false): TransformedTreeNode[] => {
  return nodes.map((node) => {
    const { children, deptId, deptName, users } = node;
    const result: TransformedTreeNode = {
      label: deptName || '',
      value: deptId || '',
    };

    if (children && children.length > 0) {
      result.children = transformTreeData(children, isNeedUser);
    }

    if (isNeedUser && users && users.length > 0) {
      result.children = users.map((user) => ({
        label: `${user.idtUserWorkNo}(${user.appAccountAccountName})`,
        value: user.idtUserWorkNo,
      }));
    }
    return result;
  });
};

/**
 * 去除字符串中的括号及其内部内容
 * @param str 要处理的字符串
 * @returns 处理后的字符串
 */
export function removeParentheses(str: string) {
  return str.replace(/\(.*?\)/g, '');
}
