import React, { useEffect, useState } from 'react';
import { Select, Divider, Modal, Button, Form, Input, Message } from '@arco-design/web-react';
import { IconPlus } from '@arco-design/web-react/icon';
import { useDispatch, useSelector } from 'react-redux';
import { addEventItem } from '@/api/event';
import { AddEventParams } from '@/api/interface';

const FormItem = Form.Item;
const TextArea = Input.TextArea;
const Option = Select.Option;

interface EventSelectProps {
  nodeData: any;
  eventList: any[];
  type: 'send' | 'listen';
  onRefresh: () => void;
  onUpdateData: (data) => void;
}

const typeMap = {
  send: 'EVENTSEND',
  listen: 'EVENTLISTENE'
};

const EventSelect: React.FC<EventSelectProps> = ({ nodeData, eventList, type, onRefresh, onUpdateData }) => {
  const [options, setOptions] = useState<any[]>([]);
  const [form] = Form.useForm();
  const [showModal, setShowModal] = useState(false);
  const [currentEvent, setCurrentEvent] = useState<any>(null);
  const { currentAppData, eventListOld } = useSelector(state => state.ideContainer);

  useEffect(() => {
    if (nodeData && eventList && eventList.length > 0) {
      setOptions(eventList.filter(item => !item.topic.includes('**empty**')));
      try {
        // 数据是JSON字符串，标识是接口回来的
        const customDef = JSON.parse(nodeData.component?.customDef);
        console.log('customDef:', customDef);
        // 先判断topic是不是**empty**，是就不设置currentevent
        if (customDef.topic && customDef.topic.includes('**empty**')) setCurrentEvent(null);
        else {
          if (!customDef.eventId) {
            const currentItem = eventList.find(item => customDef.topic === item.topic);
            setCurrentEvent(currentItem.name);
          }
          else {
            const currentItem = eventListOld.find(item => customDef.eventId === item.eventId);
            setCurrentEvent(currentItem.name);
          }
        }
      } catch (e) {
        // 数据是普通对象标识是当前操作数据
        // 先判断topic是不是**empty**，是就不设置currentevent
        if (nodeData.component?.customDef?.topic && nodeData.component?.customDef?.topic.includes('**empty**')) setCurrentEvent(null);
        else {
          const currentItem = eventList.find(item => nodeData.component?.customDef.topic === item.topic);
          setCurrentEvent(currentItem.name);
        }
      }
    }
  }, [nodeData, eventList]);

  const addItem = () => {
    setShowModal(true);
  };

  const saveForm = async () => {
    try {
      await form.validate();
      const formData = form.getFields();
      const params = {
        ...formData,
        sceneId: currentAppData.sceneId
      };
      const res: any = await addEventItem(params as AddEventParams);

      if (res && res.code === 200) {
        Message.success('添加成功');
        onRefresh();
      }
      else {
        Message.error(res.message);
      }
      setShowModal(false);
    } catch (e) {
    }
  };

  const handelSelect = (e) => {
    const data = {
      type: typeMap[type],
      customDef: {
        eventId: e.eventId,
        name: e.name,
        topic: e.topic
      }
    };
    onUpdateData(data);
  };

  return (
    <>
      <Select
        value={currentEvent}
        placeholder="请选择事件"
        onChange={(e) => handelSelect(e)}
        dropdownRender={(menu) => (
          <div>
            {menu}
            <Divider style={{ margin: 0 }} />
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                padding: '10px 12px',
                justifyContent: 'center'
              }}
            >
              <Button
                style={{ fontSize: 14, padding: '0 6px' }}
                type="text"
                size="mini"
                onClick={addItem}
              >
                <IconPlus />
                新增事件
              </Button>
            </div>
          </div>
        )}
        dropdownMenuStyle={{ maxHeight: 300 }}
      >
        {options.map((option, index) => (
          <Option key={option.topic} value={option}>
            {option.name}
          </Option>
        ))}
      </Select>
      {showModal && (<Modal
        title="新增事件"
        visible={showModal}
        onOk={saveForm}
        onCancel={() => setShowModal(false)}
        autoFocus={false}
        focusLock={true}
      >
        <Form
          form={form}
          autoComplete="off"
        >
          <FormItem
            label="事件名称"
            field="name"
            required
            rules={[
              {
                validator(value, cb) {
                  if (!value) {
                    return cb('请填写事件名称');
                  }

                  return cb();
                }
              }
            ]}
          >
            <Input placeholder="请输入事件名称" />
          </FormItem>
          <FormItem
            label="事件标识"
            field="topic"
            required
            rules={[
              {
                validator(value, cb) {
                  if (!value) {
                    return cb('请填写事件标识');
                  }
                  if (value.includes('**empty**')) {
                    return cb('非法事件标识，请重新输入');
                  }

                  return cb();
                }
              }
            ]}
          >
            <Input placeholder="请输入事件标识" />
          </FormItem>
          <FormItem
            label="事件描述"
            field="description"
            required
            rules={[
              {
                validator(value, cb) {
                  if (!value) {
                    return cb('请填写事件描述');
                  }

                  return cb();
                }
              }
            ]}
          >
            <TextArea placeholder="请输入事件描述" />
          </FormItem>
        </Form>
      </Modal>)}
    </>

  );
};

export default EventSelect;