import React, {ReactNode} from 'react'
import TreeSelect from '../tree_select/index'
import Header from '../header/index'
import Button from '../button/index'
import Icon from '../icon'
import classnames from 'classnames'
import './index.less'

export type UserNode = {
  avatar: string
  id: number
  name: string
  wxUserId?: string
  visible?: boolean
}

type DepartNodes = {
  departNodes?: DepartNodes[]
  id?: number
  info?: {
    id?: number
    name?: string
  }
  departInfoList?: UserNode[]
  wxDepartId?: number
  visible?: boolean
}

type Props = {
  title?: string
  footer?: ReactNode
  data: DepartNodes[]
  isPcClient?: boolean
  multi: boolean
  selectedIds: number[]
  onConfirm?(): void
  onCancel?(): void
  handleSelect?(selected: boolean, value: number, type?: 'department' | 'userName'): void
  renderNode(itemNode: UserNode, type: string): ReactNode
}

const SelectPeople: React.FC<Props> = (props: Props) => {
  const {title, multi, footer, data, isPcClient, selectedIds} = props

  // 数据处理
  const setDepartNode = (nodesData: any[]): any[] => {
    return nodesData.map(itemNode => ({
      title: props?.renderNode(itemNode, 'departmentName'), // <Node openid={itemNode.wxDepartId} type="departmentName" />,
      value: itemNode.info?.id || itemNode.id,
      type: 'department',
      children: setDepartNode(itemNode.departNodes),
      departInfoList:
        itemNode.userList &&
        itemNode.userList.map((userItem: any) => ({
          title: props?.renderNode(userItem, 'userName'), // <Node openid={userItem.wxUserId} type="userName" />,
          value: userItem.id,
          type: 'user',
          ...userItem,
        })),
    }))
  }
  const newData = setDepartNode(data)
  const leftIcons = isPcClient ? '' : 'arrow-left'
  return (
    <div className={classnames(isPcClient && 'pc')} id="contact-selector">
      {!isPcClient && (
        <Header
          left={<Icon className="left-icon" name={leftIcons} />}
          onLeftClick={() => window.history.back()}>
          {title}
        </Header>
      )}
      <div className={classnames('contact-body', isPcClient && 'pc')}>
        <TreeSelect
          data={newData}
          multi={multi}
          onSelect={props?.handleSelect!}
          selected={selectedIds}
        />
      </div>
      {footer ? (
        footer
      ) : (
        <div className={classnames('contact-footer', isPcClient && 'pc')}>
          <Button className="footer-but" onClick={() => props?.onCancel?.()}>
            取消
          </Button>
          <Button className="footer-but" onClick={() => props?.onConfirm?.()} type="primary">
            确定
          </Button>
        </div>
      )}
    </div>
  )
}

export default SelectPeople
