import React, { useEffect, useMemo, useRef, useState } from 'react'
import { TreeSelect } from 'antd'
import { connect } from 'dva'

const getTreeFrom = (arr) => {
  const copy = (arr || []).map((it) => ({ ...it, children: undefined }))

  const tree = []
  for (let inx in copy) {
    const it = copy[inx]
    const key = it.institutionCode
    const node = {
      key,
      value: it.institutionId,
      title: it.institutionName,
      children: it.children,
      parent: it.parent,
    }
    const parent = key.length === 2 ? undefined : key.substring(0, key.length - 2)

    if (parent) {
      for (let cur of copy) {
        if ((cur.institutionCode || cur.key) === parent) {
          node.parent = cur
          cur.children = [
            ...(cur.children || []),
            node,
          ]
          break
        }
      }
    }

    copy[inx] = node
    tree.push(node)
  }
  return tree.filter(x => !x.parent)
}

const InstitutionSelect = React.forwardRef((props, ref) => {

  const { user, ...leftProps } = props

  const [expandedKeys, setExpandedKeys] = useState([])

  const treeData = useMemo(() => {
    return getTreeFrom(user.institutionList) || []
  }, [user.institutionList])

  useEffect(() => {
    setExpandedKeys((user.institutionList || []).map((x) => x.institutionCode))
  }, [user.institutionList])

  return (
    <TreeSelect allowClear treeExpandedKeys={expandedKeys} onTreeExpand={setExpandedKeys} {...leftProps} treeData={treeData} />
  )
})

export default connect(({ user }) => ({
  user: user.currentUser,
}))(InstitutionSelect)
