
export function uuid() {
  let d = Date.now()
  if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
    d += performance.now() // use high-precision timer if available
  }
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    const r = (d + Math.random() * 16) % 16 | 0
    d = Math.floor(d / 16)
    return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16)
  })
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {string} id id字段 默认 'id'
 * @param {string} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 * @param {string | number} rootId 根Id 默认 0
 */
export function handleTree(data: ExtraObj[], id?: string, parentId?: string, children?:  string, rootId?: number | string) {
  const reNameId = id || 'id'
  const reNameParentId = parentId || 'parentId'
  const reNameChildren = children || 'children'
  const reNameRootId =
    rootId ||
    Math.min.apply(
      Math,
      data.map(item => {
        return item[reNameParentId]
      })
    ) ||
    0
  // 对源数据深度克隆
  const cloneData = JSON.parse(JSON.stringify(data))
  // 循环所有项
  const treeData = cloneData.filter((father: ExtraObj) => {
    var branchArr = cloneData.filter((child: ExtraObj) => {
      // 返回每一项的子级数组
      return father[reNameId] === child[reNameParentId]
    })
    if (branchArr.length > 0) {
      father[reNameChildren] = branchArr
    } else {
      father[reNameChildren] = ''
    }
    // 返回第一层
    return father[reNameParentId] == reNameRootId
  })
  return treeData !== '' ? treeData : data
}












