import { computed, ref } from 'vue'

const searchData = (val: string | undefined, data: any[]): any[] => {
  if (!val) {
    return data
  }
  const result: any[] = []
  data.forEach((item) => {
    if (item.name.toLowerCase().indexOf(val.toLowerCase()) > -1) {
      result.push({ ...item })
    } else if (item.children) {
      const filterSearchData = searchData(val, item.children)
      if (filterSearchData.length) {
        result.push({
          ...item,
          children: filterSearchData
        })
      }
    }
  })
  return result
}

const filterData = (tree: any[], ignoreIds: string[]) => {
  const traverse = (nodes: any) => {
    const result: any[] = []
    nodes.forEach((node: any) => {
      if (!ignoreIds.includes(node.id)) {
        const children = traverse(node.children)
        result.push({
          ...node,
          children: children || []
        })
      }
    })
    return result
  }

  return traverse(tree)
}

export default (ignoreIds?: string[]) => {
  const searchKey = ref('')

  const treeData = ref([])
  const searchTreeData = computed(() => searchData(searchKey.value, treeData.value))
  const realTreeData = computed(() => filterData(searchTreeData.value, ignoreIds || []))

  let timeout: any
  const inputChange = (val: string) => {
    if (timeout) clearTimeout(timeout)
    timeout = setTimeout(() => {
      searchKey.value = val
    }, 300)
  }
  return {
    searchKey,
    treeData,
    realTreeData,
    inputChange
  }
}
