// 生成树形
export function generateTree(data, id, parentId, children) {
  const idMap = {}
  const jsonTree = []
  data.forEach((v) => {
    v.key = v.id
    idMap[v[id]] = v
  })
  data.forEach((v) => {
    const parent = idMap[v[parentId]]
    if (parent) {
      !parent[children] && (parent[children] = [])
      parent[children].push(v)
    } else {
      jsonTree.push(v)
    }
  })
  return jsonTree
}

// 根据id获取树形结构的所有父级
export function getTreeIds(tree, nodeId, config) {
  const { children = 'children', id = 'id' } = config || {}
  const toFlatArray = (tree, parentId) => {
    return tree.reduce((t, _) => {
      const child = _[children]
      return [
        ...t,
        parentId ? { ..._, parentId } : _,
        ...(child && child.length ? toFlatArray(child, _[id]) : []),
      ]
    }, [])
  }
  const getIds = (flatArray) => {
    let ids = [nodeId]
    let child = flatArray.find((_) => _[id] === nodeId)
    while (child && child.parentId) {
      ids = [child.parentId, ...ids]
      child = flatArray.find((_) => _[id] === child.parentId)
    }
    const isFlag = flatArray.find((_) => _[id] === 0)
    if (isFlag && ids[0] !== 0) {
      ids = [0, ...ids]
    }
    return ids
  }
  return getIds(toFlatArray(tree))
}
