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

const { Search } = Input;

const getGroupList = fetch(apis.taliveActivity.taLiveActivity)

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

  const [list, setList] = useState([]);
  const [visible, setVisible] = useState(false);
  const [group, setGroup] = useState({ groupId: undefined, groupName: '请选择直播活动' })
  const getGroupTitle = val => {
    return (list.filter(x => x.liveActivityId == val)[0] || {}).liveActivityTitle || '请选择直播活动'
  }
  const updateGroup = val => setGroup({ groupId: val, groupName: getGroupTitle(val) })

  const buildingId = props.buildingId()

  useEffect(() => {
    getGroupList({
      params: {
        buildingId,
        pageNum: 1,
        pageSize: 999,
        status: 1,
      },
    }).then(data => {
      setList(data.records || [])

      updateGroup(buildingId ? undefined : value);
    })
  }, [buildingId]);
  const searchGroup = (e) => {
    getGroupList({
      params: {
        buildingId,
        pageNum: 1,
        pageSize: 999,
        status: 1,
        liveActivityTitle: e
      }
    }).then((data) => {
      setList(data.records || [])

      updateGroup(buildingId ? undefined : value);
      // setAct(buildingId ? undefined : value);
    })
  }
  if (value !== group.groupId) {
    updateGroup(value);
  }

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

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

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

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