import { useEffect, useState } from 'react'
import { useSelector } from 'react-redux'
import Picker from '@/components/Picker'
import { fetch } from '@/utils/request'
import { API_GET_AGENT_BUILDINGS, API_ITEMS_LIST } from '@/constants/api'
import { ROLE_CODE } from '@/constants/user'

export default (props) => {

  const { type = '', change = () => {} } = props
  const city = useSelector(state => state.city)
  const [dicts, setDicts] = useState([])

  useEffect(() => {
    if (type !== ROLE_CODE.CUSTOMER && type !== ROLE_CODE.DRIFT) {
      fetch({ url: API_GET_AGENT_BUILDINGS }).then((res) => {
        setDicts(res || [])
      })
    } else {
      fetch({ url: API_ITEMS_LIST, payload: { pageNumber: 1, pageSize: 1000, cityId: city.curCity.id } }).then((res) => {
        setDicts(res.records || [])
      })
    }
  }, [])

  const BuildingChange = (value) => {
    change(value)
  }

  return (
    <Picker kv={['buildingName', 'buildingId']} dicts={dicts} {...props} onChange={BuildingChange} />
  )
}
