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

const getNewsList = fetch(apis.news.getList)

export default (props) => {
  const {
    value,
    onChange,
    ...rest
  } = props;

  const [list, setList] = useState([]);
  const [visible, setVisible] = useState(false);
  const [ news, setNews ] = useState({ newsId: undefined, newsName: '请选择资讯' })
  const getNewsTitle = val => ((list.filter(x => x.newsId === val)[0]) || {}).newsName || '请选择资讯'
  const updateNews = val => setNews({ newsId: val, newsName: getNewsTitle(val) })

  const buildingId = props.buildingId()
  
  useEffect(() => {
    getNewsList({
      params: {
        buildingId,
        pageNum: 1,
        pageSize: 999,
      }
    }).then((data) => {
      setList(data.list || [])

      updateNews(buildingId ? undefined : value);
    })
  }, [buildingId]);

  if (value !== news.newsId) {
    updateNews(value);
  }

  const handleChange = val => {
    onChange(val)
  }

  return (
    <div>
      <div onClick={() => setVisible(true)}>{news.newsName}</div>
      <Modal
        title="请选择资讯"
        visible={visible}
        onOk={() => {
          updateNews(value)
          onChange(value)
          setVisible(false)
        }}
        onCancel={() => setVisible(false)}
      >
        <Select
          showSearch
          value={value ? parseInt(value) : undefined}
          onChange={handleChange}
          style={{ width: '90%' }}
          filterOption={(input, option) =>
            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
          }
        >
          {
            list.map(x => (<Select.Option key={x.newsId} value={x.newsId}>{x.newsName}</Select.Option>))
          }
        </Select>
      </Modal>
    </div>
  );
}
