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 { Search } = Input;

const getHelpList = fetch(apis.helpActivity.effectiveList)

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

  const [list, setList] = useState([]);
  const [visible, setVisible] = useState(false);
  const [help, setHelp] = useState({ helpId: undefined, helpName: '请选择助力' })
  const getHelpTitle = val => {
    return (list.filter(x => x.helpActivityId == val)[0] || {}).title || '请选择助力'
  }

  const updateHelp = val => setHelp({ helpId: val, helpName: getHelpTitle(val) })

  const buildingId = props.buildingId()

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

      updateHelp(value ? undefined : value);
    })
  }, [buildingId]);
  const searchHelp = (e) => {
    getHelpList({
      params: {
        buildingId,
        pageNum: 1,
        pageSize: 999,
        status: 1,
        name: e
      },
    }).then(data => {
      setList(data.records || [])

      updateHelp(value ? undefined : value);
    })
  }
  if (value !== help.helpId) {
    updateHelp(value);
  }

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

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

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

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