import React, { useEffect, useState, useMemo } from 'react';
import styles from './style/index.module.less';
import { Button, Divider, Input, Space, Table, Form, Message, Popconfirm } from '@arco-design/web-react';
import { IconSearch, IconDelete } from '@arco-design/web-react/icon';
import { addGlobal, deleteGlobal, getGlobalList } from '@/api/global';
import { useSelector } from 'react-redux';
import AddGlobalVarModal from './addModal';

// 定义数据类型映射对象
const dataTypeMap = {
  OBJECT: '复合类型',
  JSON: 'JSON类型',
  ARRAY: '数组类型',
  BOOLEAN: '布尔类型',
  INTEGER: '整数类型',
  DOUBLE: '双精度浮点类型',
  STRING: '字符串类型',
  DATE: '日期类型',
  DATETIME: '日期时间类型',
  TIMESTAMP: '时间戳类型',
  DATABASE: '数据库类型'
};

const GlobalVarContainer = () => {
  const [selectedItem, setSelectedItem] = useState('OBJECT');
  const { info } = useSelector((state: any) => state.ideContainer);
  const [addModalVisible, setAddModalVisible] = useState(false); // 控制弹窗显示状态
  const [form] = Form.useForm(); // 创建表单实例
  const [globalVarData, setGlobalVarData] = useState({}); // 存储全局变量数据
  const [searchText, setSearchText] = useState(''); // 搜索文本

  const menuItems = Object.keys(dataTypeMap);

  const getGlobalVar = async () => {
    try {
      const res: any = await getGlobalList(info.id);
      if (res.code === 200) {
        const initData = {};
        menuItems.forEach(item => {
          initData[item] = [];
        });

        // 处理接口返回的数据，按类型分类
        if (res.data) {
          Object.keys(res.data).forEach(dataType => {
            const items = res.data[dataType];
            if (Array.isArray(items) && initData[dataType]) {
              initData[dataType] = items;
            }
          });
        }

        setGlobalVarData(initData);
      }
      else {
        Message.error('获取全局变量失败');
      }
    } catch (error) {
      console.error('获取全局变量失败:', error);
      Message.error('获取全局变量失败');
    }
  };

  const handleAddGlobalVar = () => {
    setAddModalVisible(true); // 显示弹窗
  };

  // 处理弹窗确认
  const handleAddModalOk = async () => {
    try {
      const values = await form.validate();
      const params = {
        ...values,
        sceneId: info.id
      };
      if (!params?.arrayType) params.arrayType = null;

      const res: any = await addGlobal(params);
      if (res.code === 200) {
        Message.success('添加成功');
        await getGlobalVar(); // 重新获取数据
      }
      else {
        Message.error('添加失败: ' + res.msg);
      }

      form.resetFields(); // 重置表单
      setAddModalVisible(false); // 关闭弹窗
    } catch (error) {
      console.log('表单验证失败:', error);
      Message.error('添加失败');
    }
  };

  // 处理弹窗关闭
  const handleAddModalCancel = () => {
    form.resetFields(); // 重置表单
    setAddModalVisible(false); // 关闭弹窗
  };

  // 处理删除全局变量
  const handleDeleteGlobalVar = async (id) => {
    console.log('删除全局变量:', id);
    try {
      const res: any = await deleteGlobal(id);
      if (res.code === 200) {
        Message.success('删除成功');
        await getGlobalVar(); // 重新获取数据
      }
      else {
        Message.error('删除失败: ' + res.msg);
      }
    } catch (error) {
      console.log('删除失败:', error);
      Message.error('删除失败');
    }
  };

  // 处理搜索输入变化
  const handleSearchChange = (value) => {
    setSearchText(value);
  };

  const filteredData = useMemo(() => {
    const currentData = globalVarData[selectedItem] || [];
    if (!searchText) {
      return currentData;
    }

    return currentData.filter(item => {
      // 在变量名、数据类型、默认值和描述中搜索
      return (
        item.name?.toLowerCase().includes(searchText.toLowerCase()) ||
        item.dataType?.toLowerCase().includes(searchText.toLowerCase()) ||
        item.defaultValue?.toLowerCase().includes(searchText.toLowerCase()) ||
        item.description?.toLowerCase().includes(searchText.toLowerCase())
      );
    });
  }, [globalVarData, selectedItem, searchText]);

  useEffect(() => {
    getGlobalVar();
  }, []);

  // 定义表格列
  const columns = [
    {
      title: '变量名',
      dataIndex: 'name'
    },
    {
      title: '数据类型',
      dataIndex: 'dataType'
    },
    {
      title: '默认值',
      dataIndex: 'defaultValue'
    },
    {
      title: '描述',
      dataIndex: 'description'
    },
    {
      title: '操作',
      dataIndex: 'operations',
      render: (_, record) => (
        <Popconfirm
          title="确定删除该全局变量吗？"
          onOk={() => handleDeleteGlobalVar(record.id)}
        >
          <Button type="text" icon={<IconDelete />} />
        </Popconfirm>
      )
    }
  ];

  return (
    <div className={styles['global-var-container']}>
      {/*左侧菜单*/}
      <div className={styles['global-var-menu']}>
        {menuItems.map((item, index) => (
          <div
            key={index}
            className={selectedItem === item ? styles['selected'] : ''}
            onClick={() => setSelectedItem(item)}
          >
            {dataTypeMap[item]}
          </div>
        ))}
      </div>
      <div className={styles['global-var-content']}>
        {/*头部*/}
        <div className={styles['global-var-header']}>
          <div className={styles['global-var-title']}>全局参数</div>
          <div className={styles['global-var-handle']}>
            <Space split={<Divider type="vertical" />}>
              <Input
                prefix={<IconSearch />}
                placeholder={'搜索'}
                style={{ width: 236 }}
                value={searchText}
                onChange={handleSearchChange}
              />
              <Button
                type="primary"
                style={{ marginLeft: 5, borderRadius: 4 }}
                onClick={handleAddGlobalVar}
              >
                + 新增参数
              </Button>
            </Space>
          </div>
        </div>
        {/*数据列表*/}
        <div className={styles['global-var-list']}>
          <Table
            columns={columns}
            data={filteredData}
            pagination={false}
            rowKey="id"
          />
        </div>
      </div>

      {/* 添加全局变量弹窗 */}
      <AddGlobalVarModal
        visible={addModalVisible}
        onOk={handleAddModalOk}
        onChangeVisible={setAddModalVisible}
        form={form}
      />
    </div>
  );
};

export default GlobalVarContainer;