export default {
  translate2Rows(roots) {
    const entryArray = Array.isArray(roots) ? roots : [roots]
    const { deep } = this.setLevelLeaf(entryArray)
    const result = []
    entryArray.forEach(i => {
      result.push(this.getRows(i, deep))
    })

    if (result.length === 1) {
      return result[0]
    }
    return result
  },
  getNodeById(data, id) {
    if (data.id === id) {
      return data
    }
    const children = data.children || []
    for (var i = 0, len = children.length; i < len; i++) {
      const res = this.getNodeById(children[i], id)
      if (res) {
        return res
      }
    }
    return null
  },
  getParentByChildId(data, id, parent) {
    if (data.id === id) {
      return parent
    }
    const children = data.children || []
    for (let i = 0; i < children.length; i++) {
      const result = this.getParentByChildId(children[i], id, data)
      if (result) {
        return result
      }
    }
    return null
  },
  hasChildren(item) {
    return this._hasChildren(item)
  },
  _hasChildren(item) {
    if (item && item.children && item.children.length) {
      return true
    } else {
      return false
    }
  },
  getRows(data, deep) {
    // 先序遍历到尽头
    const stack = []
    const RowsResult = []
    let result = []
    stack.push(data)
    while (stack.length) {
      const top = stack.pop()
      // 保存到结果集内
      const item = {
        ...top,
        children: null,
        rowSpan: top.merge ? top.rowspan : top.leafCount
      }
      if (this._hasChildren(top)) {
        // 叶子结点
        item.colSpan = 1
        // 非叶子节点
      } else {
        item.colSpan = deep - top.level + 1
      }
      result.push(item)
      const children = top.children
      if (children && children.length > 0) {
        for (let i = children.length - 1; i >= 0; i--) {
          stack.push(children[i])
        }
      } else {
        // 叶子节点，划分割线，新数组开始
        RowsResult.push(result)
        result = []
      }
    }
    return RowsResult
  },
  /**
   * 递归建立以下内容：
   * 树的每个节点的深度（根节点深度为1）;
   * 每个节点下属所有的叶子（包括孙子和所有后代）个数;
   * 节点是否是leaf
   *
   * @param {*} arr
   * @param {*} parentLevel
   * 返回，有效内容为当前节点的所有后代叶子个数，所有后代节点中，最深的节点的深度
   */
  setLevelLeaf(arr, parentLevel = 0) {
    let count = 0
    let deep = parentLevel + 1
    arr.forEach(item => {
      item.level = parentLevel + 1
      item.leafCount = 0
      if (this._hasChildren(item)) {
        const { count: c, deep: d } = this.setLevelLeaf(item.children, item.level)
        item.leafCount += c
        item.isLeaf = false
        count += c
        deep = Math.max(deep, d)
      } else {
        item.isLeaf = true
        item.leafCount = 1
        count += 1
      }
    })
    return {
      count,
      deep
    }
  }
}
