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 BuildingSelect2 = props => {
  const [data, setData] = useState([])
  const [loading, setLoading] = useState(true)
  const [value, setValue] = useState([])
  const {cityId,disabled=false} = props
  console.log('props', props.cityId);
  useEffect(() => {
    getBuildList();
  }, [props.cityId])


  const getBuildList = e => {
    request({ ...apis.building.buildingSelect, params: { cityId: props.cityId, pageNum: 1, pageSize: 999 } }).then(data => {
      setData(data)
      checkValue(data)
      setLoading(false)
      // 默认选中第一个
    })
  }


  const checkValue = (data) => {
    if (props.value) {
      const tempData = data.filter(f => f.buildingId == props.value)
      const va = (tempData.length > 0) ? props.value : '项目已下线，请重新选择项目'
      props.onChange(va)

    }
  }

  const onChange = (buildingId) => {
    const building = data.filter(x => buildingId === x.buildingId)[0]

    props.onChange(buildingId, building)
    // if (props.value) {
    //   const tempData = data.filter(f => f.buildingId == props.value)
    //   const va = (tempData.length > 0) ? props.value : '项目已下线，请重新选择项目'
    //   props.onChange(va)

    // }={props.onChange}building.buildingId
  }

  return (
    <Select
      showSearch
      value={props.value}
      style={{ width: '300px' }}
      placeholder="请选择项目"
      loading={loading}
      onChange={ onChange}
      filterOption={(input, option) =>
        option.props.children && option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
      }
      disabled={disabled}
      >
      {data.map(building => (
        <Option key={building.buildingId} value={building.buildingId}>{building.buildingName}</Option>
      ))}
    </Select>
  )
}
export default BuildingSelect2
