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

const getH5List = fetch(apis.h5Activity.EffectiveList)
const { Search } = Input;

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.drainageId == val)[0] || {}).name || '请选择'
  }
  const updateGroup = val => setGroup({ groupId: val, groupName: getGroupTitle(val) })

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

      updateGroup(value ? undefined : value);
    })
  }, []);
  const searchH5 = (e) => {
    getH5List({
      params: {
        buildingId,
        pageNum: 1,
        pageSize: 999,
        activityStatus: 2,
        name: e
      }
    }).then((data) => {
      setList(data.records || [])

      updateGroup(value ? undefined : value);
    })
  }

  if (value !== group.groupId) {
    updateGroup(value);
  }

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

  const setData = val => {
    updateGroup('')
    onChange('')
  }

  return (
    <div>
      <div onClick={() => setVisible(true)}>{group.groupName}</div>
      <Modal
        title="请选择"
        visible={visible}
        onCancel={() => setVisible(false)}
        footer={[
          <Button key="back" onClick={() => setVisible(false)}>
            取消
            </Button>,
          <Button key="cancel" onClick={() => setData(value)}>
            清空
            </Button>,
          <Button key="submit" type="primary" onClick={() => {
            updateGroup(value)
            onChange(value)
            setVisible(false)
          }}>
            提交
            </Button>
        ]}
      >
        <Search
          placeholder="请输入标题"
          enterButton="搜索"
          size="large"
          onSearch={value => searchH5(value)}
          style={{ marginBottom: '16px' }}
        />
        <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.drainageId} value={x.drainageId}>{x.name}</Select.Option>))
          }
        </Select>
      </Modal>
    </div>
  );
}
