/*
  单个父节点以及其递归子节点的选择器
*/
import React, {useState, useCallback} from 'react'
import Selector from '../selector'
import Icon from '../icon/index'
import {SelectorProps} from './interface'
import {ContactList} from './index'
import './index.less'

const TreeSelector: React.FC<SelectorProps> = (props: SelectorProps) => {
  const {itemNode, multi, selected, level, isShowFold, levelPadding = 24} = props
  const [folded, setFolded] = useState(level !== 1)
  const handleFold = useCallback(() => {
    setFolded(!folded)
  }, [folded])
  const foldedNodeRender = () => {
    if (folded) return <div />
    return (
      <>
        {!!itemNode?.departInfoList?.length && (
          <ContactList
            data={itemNode.departInfoList}
            isShowFold={false}
            level={level}
            levelPadding={levelPadding}
            multi={multi}
            onSelect={props?.onSelect}
            selected={selected}
          />
        )}
        {!!itemNode?.children?.length && (
          <ContactList
            data={itemNode.children}
            isShowFold
            level={level + 1}
            levelPadding={levelPadding}
            multi={multi}
            onSelect={props?.onSelect}
            selected={selected}
          />
        )}
      </>
    )
  }
  return (
    <div className="contact-list" key={itemNode.value}>
      <Selector
        className="contact-item"
        // disabled={!multi}
        multi={multi}
        onSelect={props?.onSelect}
        selected={selected.includes(itemNode.value)}
        type={itemNode?.type}
        value={itemNode.value}>
        <div className="contact-group" style={{paddingLeft: Math.max(0, level - 1) * levelPadding}}>
          <div>{itemNode.title}</div>
          {isShowFold && (
            <div className={`fold-button${!folded ? ' unfold' : ''}`} onClick={handleFold}>
              <Icon className="fold-icon" name="fold" />
            </div>
          )}
        </div>
      </Selector>
      {/* folded折叠不仅折叠子节点数据，还折叠组织下的departList数据 */}
      {foldedNodeRender()}
    </div>
  )
}
export default TreeSelector
