import React, { Key, memo, useEffect, useMemo, useState } from 'react'
import { fetchTree } from '@/api/services/dept'
import { Input, Tree } from 'antd'
import type { TreeDataNode } from 'antd'

interface DeptTreeSelectProps {
  onSelect: (id: Key[]) => void
}

const { Search } = Input

let defaultData: TreeDataNode[] = []

const dataList: { key: React.Key; title: string }[] = []
const generateList = (data: TreeDataNode[]) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i]
    const { key, title } = node
    dataList.push({ key, title: title as string })
    if (node.children) {
      generateList(node.children)
    }
  }
}

const getParentKey = (keys: React.Key[], tree: TreeDataNode[]): React.Key[] => {
  const parentKey: React.Key[] = []
  const getMatchParentKeyInTree = (key: React.Key, tree: TreeDataNode[]) => {
    tree.forEach((treeNode) => {
      if (treeNode.children && treeNode.children.length) {
        if (treeNode.children.some((child) => child.key === key)) {
          parentKey.push(treeNode.key)
        }
        getMatchParentKeyInTree(key, treeNode.children)
      } else if (treeNode.key === key) {
        parentKey.push(key)
      }
    })
  }
  keys.forEach((key) => {
    getMatchParentKeyInTree(key, tree)
  })
  return parentKey
}

const initDeptData = (originDeptData: API.DeptTreeResult): TreeDataNode[] => {
  return originDeptData.map((ele) => {
    return {
      ...ele,
      key: ele.id,
      title: ele.name,
      children: (ele.children && ele.children.length && initDeptData(ele.children)) || []
    }
  })
}

export default memo(({ onSelect }: DeptTreeSelectProps) => {
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([])
  const [searchValue, setSearchValue] = useState('')
  const [autoExpandParent, setAutoExpandParent] = useState(true)
  const [_isLoading, setIsLoading] = useState(false)
  const [_originDeptData, setOriginDeptData] = useState<API.DeptTreeResult>([])

  const getDeptTree = () => {
    setIsLoading(true)
    // tableData.value = []
    fetchTree().then((res) => {
      if (res) {
        const data = res.data || []
        setOriginDeptData(data)
        defaultData = initDeptData(data)
        generateList(defaultData)
      }
      setIsLoading(false)
    })
  }

  useEffect(() => {
    getDeptTree()
  }, [])

  const onSelectFn = (ids: Key[]) => {
    onSelect(ids)
  }
  const onExpand = (newExpandedKeys: React.Key[]) => {
    setExpandedKeys(newExpandedKeys)
    setAutoExpandParent(false)
  }

  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target
    let newExpandedKeys: React.Key[] = []
    if (value.trim() === '') {
      newExpandedKeys = []
    } else {
      // 获取匹配的节点的父节点, 设置为展开节点
      const matchKey = dataList
        .filter((item) => item.title.indexOf(value) > -1)
        .map((ele) => ele.key)
      newExpandedKeys = getParentKey(matchKey, defaultData)
    }
    setExpandedKeys(newExpandedKeys)
    setSearchValue(value)
    setAutoExpandParent(true)
  }

  const treeData = useMemo(() => {
    const loop = (data: TreeDataNode[]): TreeDataNode[] =>
      data.map((item) => {
        const strTitle = item.title as string
        const index = strTitle.indexOf(searchValue)
        const beforeStr = strTitle.substring(0, index)
        const afterStr = strTitle.slice(index + searchValue.length)
        const title =
          index > -1 ? (
            <span key={item.key}>
              {beforeStr}
              <span className='site-tree-search-value text-[#f50]'>{searchValue}</span>
              {afterStr}
            </span>
          ) : (
            <span key={item.key}>{strTitle}</span>
          )
        if (item.children) {
          return { title, key: item.key, children: loop(item.children) }
        }

        return {
          title,
          key: item.key
        }
      })

    return loop(defaultData)
  }, [searchValue, defaultData])

  return (
    <div>
      <Search style={{ marginBottom: 8 }} placeholder='请输入部门名称' onChange={onChange} />
      <Tree
        onSelect={onSelectFn}
        onExpand={onExpand}
        expandedKeys={expandedKeys}
        autoExpandParent={autoExpandParent}
        treeData={treeData}
      />
    </div>
  )
})
