import React, { useState, useEffect } from 'react';
import { Select } from 'antd';

import request from '../../utils/request'
import { APIBaseURL } from '../../utils/constant'

const { Option } = Select;
const prefix = APIBaseURL

/**
 *
 *
 * @param {*} props
 * @returns
 */
const CitySelect = (props) => {
  const [ data, setData ] = useState([])
  const cityId = typeof props.cityId === 'function' ? props.cityId() : props.cityId

  useEffect(() => {
    getCityAreaList();
    getValue();
  },[cityId])

  const getCityAreaList = (e) => {
    request({
        url: prefix + 'api/admin/tdCityList/tdAreaCity',
        method: 'GET',
        params: {leveltype: 3, cityId},
        action: 'select',
    }).then((data) => {
        setData(data)
    })
  }

  /**
   * 因为 有个需求是，如果这个城市被删除了，那么就直接展示为空，不能展示 cityId
   */
  const getValue = () => {
    if (props.value) {
      const tempData = data.filter(f => f.id == props.value)
      const va = (tempData.length > 0) ? props.value : undefined
      props.onChange(va)
    }
  }

  return (
      <Select
      {...props}
      showSearch
      value={props.value}
      style={{ width: '300px' }}
      placeholder="请选择区域"
      onChange={props.onChange}
      filterOption={(input, option) =>
        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
      }
      >
          {data.map(city => (
            <Option key={city.id} value={city.name}>{city.name}</Option>
          ))}
      </Select>
  )
}
export default CitySelect
