function getAllPath(tree, childrenKey) {
  const paths = []
  for (let i = 0; i < tree.length; i++) {
    if (tree[i][childrenKey] && tree[i][childrenKey].length > 0) {
      const res = getAllPath(tree[i][childrenKey], childrenKey) // 如果有子节点便继续深入，直到到达叶子节点
      for (let j = 0; j < res.length; j++) {
        paths.push([tree[i], ...res[j]]) // 子节点返回后将其返回的路径与自身拼接
      }
    } else {
      paths.push([tree[i]])
    }
  }
  return paths
}
function getAllList(list, formatColumn = []) {
  const result = []
  list.forEach((item, index) => {
    const row = {}
    formatColumn.forEach(column => {
      row[column.prop] = item[column.treeIndex][column.treeKey]
    })
    result.push(row)
  })
  return result
}

function groupBy(data, params) {
  const groups = {}
  data.forEach(v => {
    const group = JSON.stringify(v[params])
    groups[group] = groups[group] || []
    groups[group].push(v)
  })

  return Object.values(groups)
}
function getSpanArr(data, params) {
  let arr = [] // 接收重构数组
  const spanArr = [] // 控制合并的数组
  let pos = 0 // 设置索引
  // 排序
  groupBy(data, params).map(v => (arr = arr.concat(v)))
  arr.map(res => { // 双向绑定 把源数据改为arr
    data.shift()
    data.push(res)
  })
  const redata = arr.map(v => v[params])
  redata.reduce((old, cur, i) => {
    if (cur === old) {
      spanArr[pos] += 1
      spanArr.push(0)
    } else {
      spanArr.push(1)
      pos = i
    }
    return cur
  }, {})
  return spanArr
}

export function formatTree(tree, { spanKey = [], childrenKey = 'children', formatColumn = [] }) {
  const allPath = getAllPath(tree, childrenKey)
  const tableData = [...getAllList(allPath, formatColumn)]
  const spanArr = {}
  spanKey.forEach(key => {
    spanArr[key] = getSpanArr(tableData, key)
  })
  return {
    spanArr,
    tableData
  }
}
