export function getNodesByLevel(treeData, level) {
  const nodes = []
  if (!treeData || !treeData.length || !level) {
    return nodes
  }
  const loop = (data, lv) => {
    if (lv >= level) {
      return
    }
    if (!data) {
      return
    }
    data.forEach(v => {
      nodes.push(v)
      if (v.children) {
        loop(v.children, lv + 1)
      }
    })
  }
  loop(treeData, 0)
  return nodes
}

export function getParentsNode(key, data, idField) {
  const rs = []
  if (!key || !data) {
    return rs
  }
  const loop = (data) => {
    if (!data || !data.length) {
      return
    }
    return data.some(v => {
      if (v[idField] === key) {
        return true
      } else if (v.children) {
        if (loop(v.children)) {
          rs.push(v)
          return true
        }
      }
    })
  }
  loop(data)
  return rs
}

export function findNode(key, data, idField) {
  let rs = null
  if (!key || !data) {
    return rs
  }
  const loop = (data) => {
    if (!data || !data.length) {
      return
    }
    return data.some(v => {
      if (v[idField] === key) {
        rs = v
        return true
      } else if (v.children) {
        return loop(v.children)
      }
    })
  }
  loop(data)
  return rs
}

export function getChildrensNode(key, data, idField) {
  if (!key || !data) {
    return []
  }
  const node = findNode(key, data, idField)
  if (!node) {
    return []
  }
  const loop = (nodes) => {
    let rs = []
    if (nodes && nodes.length) {
      nodes.forEach(v => {
        rs.push(v)
        rs = rs.concat(loop(v.children))
      })
    }
    return rs
  }
  return loop(node.children)
}

/**
 * 获取保留父级节点后的节点集合
*/
export function getCheckLeastFatherNodes(node, checkedList, data, idField) {
  if (!node) {
    return
  }
  const checkedMap = (checkedList || []).reduce((rs, v) => {
    rs[v] = true
    return rs
  }, {})
  const childrens = getChildrensNode(node.data[idField], data, idField)
  childrens.forEach(v => {
    if (node.checked) {
      checkedMap[v[idField]] = true
    } else {
      checkedMap[v[idField]] = false
    }
  })
  const parents = getParentsNode(node.data[idField], data, idField)
  parents.forEach(v => {
    if (!v[idField]) {
      return
    }
    if (v.children.some(vv => checkedMap[vv[idField]])) {
      checkedMap[v[idField]] = true
    } else {
      // checkedMap[v[idField]] = false
    }
  })
  return Object.keys(checkedMap).filter(v => checkedMap[v])
}
