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

const CommunitySelect = props => {
  const [value, setValue] = useState()
  const inited = useRef(false)

  const { communityList, user, dispatch, autoInited, ...selectProps } = props

  const dataList = ((user || {}).isAdmin ? communityList : (user || {}).communityList) || []

  const handleChange = val => {
    if (props.onChange) {
      props.onChange(val)
    } else {
      setValue(val)
    }
  }

  useEffect(() => {
    if (!user || !user.userId) {
      return
    }

    // 初始化逻辑
    if (!inited.current) {
      // 如果有默认值, 则使用默认值
      if (props.value) {
        setValue(props.value)
        inited.current = true
      } else if (autoInited) {
        // 如果没有默认值, 但是需要设置默认值
        // 那么默认使用第一个
        const first = (dataList[0] || {}).id
        if (first) {
          handleChange(props.mode === 'multiple' ? [first] : first)
        }

        inited.current = true
      }
    } else {
      setValue(props.value)
    }
  }, [user, autoInited, dataList, props.value])

  return (
    <Select {...selectProps} value={value} onChange={handleChange}>
      {
        dataList.map(community => (<Select.Option key={community.id} value={community.id}>{community.name}</Select.Option>))
      }
    </Select>
  )
}

export default connect(s => ({ communityList: (s.user || {}).communityList, user: (s.user || {}).currentUser }))(CommunitySelect)
