import React, { useState, useEffect } from 'react'
import { TreeSelect } from 'antd'
import { useRequest } from 'umi'
import { queryAcountInstitutionList } from '@/services/api/institution'

const { TreeNode } = TreeSelect

const TreeNodeSelect = ({ onChange, placeholder = '请选择', ...otherProps }) => {
  const [list, setList] = useState([])
  const { run: tryAcountInstitutionList } = useRequest(() => queryAcountInstitutionList(), {
    manual: true,
    onSuccess: result => {
      setList(result)
    }
  })

  useEffect(() => {
    tryAcountInstitutionList()
  }, [])
  const onNodeChange = (value, labelList) => {
    console.log('labelList', labelList)

    onChange(value, { value, label: labelList[0] })
  }
  const renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        item.disabled = true
        return (
          <TreeNode {...item} disabled={item.disabled}>
            {renderTreeNodes(item.children)}
          </TreeNode>
        )
      }
      return <TreeNode {...item} />
    })
  return (
    list?.length && (
      <TreeSelect
        {...otherProps}
        showSearch
        style={{ width: '100%' }}
        placeholder={placeholder}
        treeNodeFilterProp="label"
        allowClear
        treeDefaultExpandAll
        onChange={(value, labelList, extra) => onNodeChange(value, labelList, extra)}
      >
        {renderTreeNodes(list)}
      </TreeSelect>
    )
  )
}

export default TreeNodeSelect
