import React, { useState, useEffect } from 'react';
import { Form, Select, Modal, Button, Table, Divider, Tag, Input } from 'antd';
import { apis, fetch } from '../../utils/request';
import Navigate from '@/components/Navigate';

const getNewsList = fetch(apis.news.getList)
const { Search } = Input;

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,
        newsStatus: 0,
      },
    }).then(data => {
      setList(data.records || [])

      updateNews(buildingId ? undefined : value);
    })
  }, [buildingId]);
  const searchActivity = (e) => {
    getNewsList({
      params: {
        buildingId,
        pageNum: 1,
        pageSize: 999,
        newsStatus: 0,
        title: e
      },
    }).then(data => {
      setList(data.records || [])

      updateNews(buildingId ? undefined : value);
    })
  }
  if (value !== news.newsId) {
    updateNews(value);
  }

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

  const setData = val => {
    updateNews(val)
    onChange(val)
    setVisible(false)
  }

  const columns = [
    {
      title: '标题',
      dataIndex: 'newsName',
      key: 'newsId',
      align: 'center',
      ellipsis: true,
      render: text => <a>{text}</a>,
    },
    {
      title: '操作',
      align: 'center',
      width: '20%',
      render: (text, record) => (
        <Navigate onClick={() => setData(record.newsId)}>选择</Navigate>
      ),
    },
  ];

  return (
    <div>
      <div ><Navigate onClick={() => setVisible(true)}>{news.newsName}</Navigate></div>
      <Modal
        title="请选择"
        visible={visible}
        onCancel={() => setVisible(false)}
        footer={[]}
      >
        <Search
          placeholder="请输入标题"
          enterButton="搜索"
          size="large"
          onSearch={value => searchActivity(value)}
          style={{ marginBottom: '16px' }}
        />
        <Table rowKey={list => list.newsId} columns={columns} dataSource={list} />
      </Modal>
    </div>
  );
}
