import React, { useEffect, useState } from 'react';
import styles from './style/index.module.less';
import {
  Button,
  Input,
  Space,
  Divider,
  Table,
  TableColumnProps,
  Modal,
  Form,
  Message,
  Popconfirm
} from '@arco-design/web-react';
import { IconSearch } from '@arco-design/web-react/icon';
import { useSelector } from 'react-redux';
import { addEventItem, deleteEventItem, queryEventItemBySceneId } from '@/api/event';

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

const HandleModal = ({ visible, onChangeVisible, onRefresh }) => {
  const [form] = Form.useForm();
  const { info } = useSelector((state: any) => state.ideContainer);

  const onOk = async () => {
    await form.validate();
    const formData = form.getFields();

    const params = {
      name: formData.name,
      topic: `${formData.topic}/${info.identity}`,
      description: formData.description,
      sceneId: info.id
    };

    const res: any = await addEventItem(params);

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

    // 清空表单数据和其他变量数据
    form.resetFields();

  };

  return (
    <Modal
      title="新增事件"
      visible={visible}
      onOk={() => onOk()}
      onCancel={() => onChangeVisible(false)}
      autoFocus={false}
      focusLock={true}
      maskClosable={false}
    >
      <Form form={form} autoComplete="off">
        <FormItem
          field="name"
          label="事件名称"
          required
          rules={[
            {
              validator(value, cb) {
                if (!value) {
                  return cb('请填写事件名称');
                }
                // 检查是否只包含汉字
                const chineseOnlyRegex = /^[\u4e00-\u9fa5]+$/;
                if (!chineseOnlyRegex.test(value)) {
                  return cb('事件名称只能输入汉字');
                }

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

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

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


const EventContainer = () => {
  const [eventData, setEventData] = useState<any[]>([]);
  const [visible, setVisible] = useState(false);
  const { info } = useSelector((state: any) => state.ideContainer);

  const columns: TableColumnProps[] = [
    {
      title: '序号',
      dataIndex: 'index',
      render: (_, record, index) => (
        <div>{index + 1}</div>
      )
    },
    {
      title: '事件名称',
      dataIndex: 'name'
    },
    {
      title: '事件标识',
      dataIndex: 'topic',
      render: (_, record) => (
        <div>{record.topic.includes('/') ? record.topic.split('/')[0] : record.topic}</div>
      )
    },
    {
      title: '事件描述',
      dataIndex: 'description',
      width: '80%'
    },
    {
      title: '操作',
      dataIndex: 'actions',
      render: (_, record) => (
        <Popconfirm
          focusLock
          title="删除事件"
          content="事件删除后无法恢复，请谨慎删除！"
          onOk={async () => {
            const res: any = await deleteEventItem(record.id);
            if (res && res.code === 200) {
              Message.success('删除成功');
              fetchEventData();
            }
            else {
              Message.error(res.message);
            }
          }}

        >
          <Button style={{ padding: 0 }} type="text" status="danger" size="small">删除</Button>
        </Popconfirm>
      )
    }
  ];

  const fetchEventData = async () => {
    const res: any = await queryEventItemBySceneId(info.id);
    if (res && res.code === 200) setEventData(res.data);
  };

  useEffect(() => {
    if (info.id) {
      fetchEventData();
    }
  }, [info.id]);

  return (
    <div className={styles['event-container']}>
      {/*头部*/}
      <div className={styles['event-header']}>
        <div className={styles['event-title']}>事件列表</div>
        <div className={styles['event-handle']}>
          <Space split={<Divider type="vertical" />}>
            <Input
              prefix={<IconSearch />}
              placeholder={'搜索'}
              style={{ width: 236 }}
            />
            <Button
              type="primary"
              style={{ marginLeft: 5, borderRadius: 4 }}
              onClick={() => setVisible(true)}
            >
              + 添加事件
            </Button>
          </Space>
        </div>
      </div>
      {/*数据列表*/}
      <div className={styles['event-list']}>
        <Table columns={columns} data={eventData} pagination={false} />
      </div>

      {visible &&
        <HandleModal
          visible={visible}
          onChangeVisible={(value => setVisible(value))}
          onRefresh={() => fetchEventData()}
        />
      }
    </div>
  );
};

export default EventContainer;