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

const getHelpList = fetch(apis.helpActivity.list)

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

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

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

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

  return (
    <div>
      <div onClick={() => setVisible(true)}>{help.helpName}</div>
      <Modal
        title="请选择助力"
        visible={visible}
        onOk={() => {
          updateHelp(value)
          onChange(value)
          setVisible(false)
        }}
        onCancel={() => setVisible(false)}
      >
        <Select
          placeholder="请选择助力"
          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.helpActivityId} value={x.helpActivityId}>{x.title}</Select.Option>))
          }
        </Select>
      </Modal>
    </div>
  );
}
