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

const getGroupList = fetch(apis.groupActivity.list)

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

  const buildingId = props.buildingId()

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

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

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

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

  return (
    <div>
      <div onClick={() => setVisible(true)}>{group.groupName}</div>
      <Modal
        title="请选择拼团"
        visible={visible}
        onOk={() => {
          updateGroup(value)
          onChange(value)
          setVisible(false)
        }}
        onCancel={() => setVisible(false)}
      >
        <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.groupActivityId} value={x.groupActivityId}>{x.activityName}</Select.Option>))
          }
        </Select>
      </Modal>
    </div>
  );
}
