/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2024-09-09 10:07:01
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-12-10 11:00:43
 * @FilePath: /MediResourceManaSys/src/utils/format.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

// 示例方法，没有实际意义
export function trim(str: string) {
  return str.trim();
}

//金额数字转换
export function formatMoneyNumber(num: number) {
  if (typeof num !== 'number' || isNaN(num)) {
    return num;
  }
  return new Intl.NumberFormat('en-US', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  }).format(num);
}


export function formatToPercentage(num: number) {
  if (typeof num !== 'number' || isNaN(num)) {
    return num;
  }
  return new Intl.NumberFormat('en-US', {
    style: 'percent',
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  }).format(num);
}



interface TreeNode {
  id: number | string;
  parentId: number | string | null;
  [key: string]: any; // 允许有任意其它属性
}

interface TreeItem extends TreeNode {
  children: TreeItem[];
}

/**
 * 根据 parentId 将平铺的数据组装成树状结构
 * @param data 平铺的数据，每项需包含 id 和 parentId 属性
 * @param rootParentId 作为根节点标识的 parentId 值，通常为0或null
 * @returns 树状结构的数组
 */
export function buildTree<T extends TreeNode>(
  data: T[],
  rootParentId: number | string | null = 0
): TreeItem[] {
  const map: Record<string | number, TreeItem> = {};

  // 初始化 map，每个节点都拥有 children 字段
  data.forEach((item) => {
    map[item.id] = { ...item, children: [] };
  });

  const tree: TreeItem[] = [];

  data.forEach((item) => {
    const node = map[item.id];
    if (item.parentId === rootParentId) {
      tree.push(node);
    } else {
      const parent = map[item.parentId as string | number];
      if (parent) {
        parent.children.push(node);
      }
    }
  });

  return tree;
}


