import React, { useState, useEffect, useRef } from 'react';
import { Select } from 'antd';
import apis from '../../services/apis';
import request from '../../utils/request'

const { Option } = Select;

function usePrevious(props) {
  const ref = useRef();
  useEffect(() => {
    ref.current = props;
  });
  return ref.current;
}

/**
 *
 *
 * @param {*} props
 * @returns
 */
const BuildingSelect = (props) => {
  const [ data, setData ] = useState([])
  const [ value, setValue ] = useState('')
  // const preProps = usePrevious(props)

  // if ((!preProps) && props.value != value) {
  //   setValue(props.value)
  // }

  useEffect(() => {
    setValue(props.value)
  }, [props.value])

  useEffect(() => {
    getCityList();
  },[])

  const getCityList = (e) => {
    request({ ...apis.building.buildingSelect, params: {pageNum: 1,pageSize: 999}, }).then((data) => {
        setData(data.records)
        // 默认选中第一个
        if (props.checkFirst) {
          setValue(data.records[0].buildingId)
          props.onChange(data.records[0].buildingId)
        }
    })
  }

  const handleChange = (e) => {
    setValue(e)
    props.onChange(e)
  }
  // '' === value ? undefined : value
  return (
      <Select
      showSearch
      value={value}
      style={{ width: '180px' }} 
      placeholder="请选择项目" 
      onChange={handleChange}
      filterOption={(input, option) =>
        option.props.children && option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
      }>
          {data.map(building => (
            <Option key={building.buildingId} value={building.buildingId}>{building.buildingName}</Option>
          ))}
      </Select>
  )
}
export default BuildingSelect
