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

const getActivities = fetch(apis.activity.list)

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

  const [list, setList] = useState([]);
  const [visible, setVisible] = useState(false);
  const [ activity, setActivity ] = useState({ dynamicId: undefined, title: '请选择活动' })
  const getActTitle = val => ((list.filter(x => x.dynamicId === val)[0]) || {}).title || '请选择活动'
  const setAct = val => setActivity({ dynamicId: val, title: getActTitle(val) })

  const buildingId = props.buildingId()
  
  useEffect(() => {
    getActivities({
      params: {
        buildingId,
        pageNum: 1,
        pageSize: 999,
      }
    }).then((data) => {
      setList(data.list || [])

      console.log('----', buildingId, value)

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

  if (value !== activity.dynamicId) {
    setAct(value);
  }

  let chooseVal = value

  const handleChange = val => chooseVal = val

  return (
    <div>
      <div onClick={() => setVisible(true)}>{activity.title}</div>
      <Modal
        title="请选择活动"
        visible={visible}
        onOk={() => {
          setAct(chooseVal)
          onChange(chooseVal)
          setVisible(false)
        }}
        onCancel={() => setVisible(false)}
      >
        <Select
        showSearch
        filterOption={(input, option) =>
          option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
        }
        defaultValue={chooseVal} 
        onChange={handleChange} 
        style={{ width: '90%' }}>
          {
            list.map(x => (<Select.Option key={x.dynamicId} value={x.dynamicId}>{x.title}</Select.Option>))
          }
        </Select>
      </Modal>
    </div>
  );
}
