import { queryAcountListByInstitutionID } from '@/services/api/institution'
import { queryInstitutionRoleList } from '@/services/api/project'
import consts from '@/utils/consts'
import { isArray, isString } from '@/utils/is'
import { useRequest } from '@umijs/max'
import { Select, TreeSelect } from 'antd'
import { useState } from 'react'

enum AuditType {
  ACCOUNT = 'account',
  INSTITUTION = 'institutionRole',
  ROLE = 'role'
}

const auditTypeOptions = [
  { label: '用户', value: AuditType.ACCOUNT },
  { label: '单位角色', value: AuditType.INSTITUTION }
  // { label: '审批角色', value: 'role'}
]

type MemberItemProps = {
  value?: {
    type?: AuditType
    value?: string | string[]
  }
  onChange: (value?: { type: AuditType; value: string[] }) => void
}

type iState = {
  auditType: AuditType
  memberOptions: string[]
  members: {
    type: AuditType
    value: string | string[]
  }
}

const filterTreeNodes = (mode: AuditType, tree: string[]) =>
  tree.map(item => {
    const newItem = { title: item.name || item.institutionName }
    // 重新拼装id， 根据AuditType加上不同的前缀(后端同步前缀格式)
    switch (mode) {
      case AuditType.ACCOUNT:
        newItem.value = item.ID
        newItem.key = item.ID
        break
      case AuditType.INSTITUTION:
        newItem.value = item.institutionID
        break
      default:
        newItem.value = item.ID
        break
    }
    if (isArray(item.children)) {
      newItem.disabled = true
      newItem.children = filterTreeNodes(mode, item.children)
      return newItem
    }
    return newItem
  })
const MemberItem: React.FC<MemberItemProps> = ({ value, onChange }) => {
  const [state, setState] = useState<iState>({
    auditType: value?.type || AuditType.ACCOUNT,
    memberOptions: [],
    members: value
  })

  useRequest(
    () => {
      let requestFn: Nullable<() => Promise<void>> = null
      switch (state.auditType) {
        case AuditType.ACCOUNT:
          requestFn = () => queryAcountListByInstitutionID({ pageSize: consts.MAX_PAGE_SIZE })
          break
        case AuditType.INSTITUTION:
          requestFn = () => queryInstitutionRoleList({ pageSize: consts.MAX_PAGE_SIZE })
          break
        default:
          break
      }
      return requestFn?.()
    },
    {
      refreshDeps: [state.auditType],
      onSuccess(data: { items: any[] }) {
        setState({
          ...state,
          memberOptions: filterTreeNodes(
            state.auditType,
            state.auditType === AuditType.ACCOUNT ? data : data.items
          )
        })
      }
    }
  )
  const toggleChange = value => {
    let val = value
    if (!isArray(val)) {
      val = [value]
    }
    if (value) {
      onChange?.({ type: state.auditType, value: val })
    }
    setState({ ...state, members: { ...state.members, value: val } })
  }
  const toggleAuditType = (value: AuditType) =>
    setState({ ...state, auditType: value, members: { type: value, value: [] } })

  return (
    <div className="flex flex-row">
      <Select
        value={state.auditType}
        options={auditTypeOptions}
        onChange={toggleAuditType}
        style={{ width: '30%' }}
      />
      {state.auditType === AuditType.ACCOUNT ? (
        <TreeSelect
          value={state.members?.value.map(item => {
            if (isString(item)) return item
            return item.ID
          })}
          placeholder="请选择"
          treeData={state.memberOptions}
          onChange={toggleChange}
          multiple
          maxTagCount="responsive"
          style={{ width: '70%', marginLeft: '4px' }}
        />
      ) : (
        <Select
          value={state.members?.value?.[0]?.ID || state.members?.value?.[0]}
          options={state.memberOptions}
          onChange={toggleChange}
          fieldNames={{ label: 'title' }}
          style={{ width: '70%', marginLeft: '4px' }}
        />
      )}
    </div>
  )
}

export default MemberItem
