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

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 NewsTypeSelect = (props) => {
  const [ data, setData ] = useState([])
  const [ value, setValue ] = useState('')
  const preProps = usePrevious(props)
  
  if ((!preProps || !preProps.value) && props.value && !value) {
    setValue(props.value)
  }

  useEffect(() => {
    getNewsTypeList();
  },[props.buildingId])

  const getNewsTypeList = (e) => {
    request({
        url: '/api/admin/taNewsType',
        method: 'GET',
        params: {pageNum: 1,pageSize: 999,buildingId: props.buildingId},
        action: 'admin.taNewsType.get',
    }).then((data) => {
        setData(data.records)
    })
  }

  const handleChange = (e) => {
    setValue(e)
    props.onChange(e)
  }

  return (
      <Select value={props.value} style={{ width: '180px' }} placeholder="请选择资讯类型" onChange={handleChange}>
          {data.map(type => (
            <Option key={type.newsTypeId} value={type.newsTypeId}>{type.newsTypeName}</Option>
          ))}
      </Select>
  )
}
export default NewsTypeSelect

