import React, { useState, useEffect } from 'react';
import { Table, Button, message, Space, Spin, Form, Input, Select, Modal } from 'antd';
import TemplateContainer from '@/pages/TemplateContainer';
import { useModel } from '@umijs/max';
import { objectToQueryString } from '@/services/services/common';
import { GetDataInfoTypeOption, GetDataInfoTypeOptions } from '@/services/enum/dataInfo';
import { SearchOutlined } from '@ant-design/icons';
import { ColumnsType } from 'antd/lib/table';
import JsonView from '@uiw/react-json-view';
import cusRequest from '@/request';

const DataInfo: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [dataList, setDataList] = useState<DataInfoModel.DataInfoBase[]>([]);
  const { initialState } = useModel('@@initialState');
  const [messageApi, messageHolder] = message.useMessage();
  const [form] = Form.useForm();

  const [tableParams, setTableParams] = useState<TableModel.TableParams>({
    pagination: {
      current: 1,
      pageSize: 10,
      showQuickJumper: true,
      totalBoundaryShowSizeChanger: true,
    },
  });

  useEffect(() => {
    QueryDataInfoCollection(tableParams, form.getFieldsValue());
  }, []);

  async function QueryDataInfoCollection(tableParams: TableModel.TableParams, options?: any) {
    try {
      setLoading(true);
      let data = {
        ...options,
        page: tableParams.pagination?.current,
        pageSize: tableParams.pagination?.pageSize,
      };
      let query = objectToQueryString(data);
      let res = await cusRequest<DataInfoModel.QueryDataInfoData>(`/lms/Other/QueryDataInfoCollection?${query}`, {
        method: 'GET',
      });
      if (res.code != 1) {
        throw new Error(res.message);
      }
      let resData = res.data;
      if (resData?.collection == undefined) {
        messageApi.error('请求获取数据为空，请重试！');
        return;
      }
      setDataList(resData.collection);
      setTableParams({
        pagination: {
          ...tableParams.pagination,
          total: resData.total,
        },
      });
      messageApi.success('Data fetched successfully');
    } catch (error: any) {
      messageApi.error(error.message);
    } finally {
      setLoading(false);
    }
  }

  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [currentJsonData, setCurrentJsonData] = useState<any>(null);
  const [isJsonFormat, setIsJsonFormat] = useState<boolean>(false);

  function CheckJson(str: string) {
    try {
      JSON.parse(str);
    } catch (e) {
      return false;
    }
    return true;
  }

  // Function to handle clicking on data
  const handleDataClick = (dataString: string) => {
    let isJsonString = CheckJson(dataString);

    if (isJsonString) {
      const jsonData = JSON.parse(dataString);
      setCurrentJsonData(jsonData);
      setIsJsonFormat(true);
    } else {
      // 不是JSON格式，直接展示原始字符串
      setCurrentJsonData(dataString);
      setIsJsonFormat(false);
    }
    setIsModalVisible(true);
  };

  // 关闭Modal的函数
  const handleModalClose = () => {
    setIsModalVisible(false);
    setCurrentJsonData(null);
  };

  const columns: ColumnsType<DataInfoModel.DataInfoBase> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (text, record) => GetDataInfoTypeOption(record.type),
    },
    {
      title: '数据字符串',
      dataIndex: 'dataString',
      key: 'dataString',
      width: 250,
      ellipsis: {
        showTitle: false,
      },
      render: (text) => (
        <a onClick={() => handleDataClick(text)} style={{ cursor: 'pointer', color: 'black' }}>
          {text}
        </a>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      width: 180,
    },
    {
      title: 'Actions',
      key: 'actions',
      render: (_: any) => (
        <Space size="middle">
          <Button type="link" danger>
            Delete
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <TemplateContainer navTheme={initialState?.settings?.navTheme ?? 'light'}>
      <Spin spinning={loading}>
        <Form
          form={form}
          layout="inline"
          onFinish={(values) => QueryDataInfoCollection(tableParams, values)}
          style={{ marginBottom: 16 }}
        >
          {/* <Form.Item name="id" label="ID">
            <Input placeholder="ID" style={{ width: 200 }} />
          </Form.Item>

          <Form.Item name="dataString" label="数据字符串">
            <Input placeholder="数据字符串" style={{ width: 200 }} />
          </Form.Item> */}
          <Form.Item name="type" label="数据类型">
            <Select
              placeholder="数据类型"
              style={{ width: 180 }}
              allowClear
              options={GetDataInfoTypeOptions()}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button onClick={() => form.resetFields()}>重置</Button>
            </Space>
          </Form.Item>
        </Form>

        <Table columns={columns} dataSource={dataList} rowKey="id" pagination={{ pageSize: 10 }} />

        {/* JSON 数据查看器 Modal */}
        <Modal
          title="数据详情"
          open={isModalVisible}
          onCancel={handleModalClose}
          footer={null}
          width={800}
        >
          {isJsonFormat ? (
            <JsonView
              value={currentJsonData}
              displayDataTypes={false}
              displayObjectSize={false}
              enableClipboard={true}
              style={{
                padding: '10px',
                borderRadius: '4px',
                maxHeight: '70vh',
                overflow: 'auto',
              }}
            />
          ) : (
            <pre
              style={{
                whiteSpace: 'pre-wrap',
                wordWrap: 'break-word',
                maxHeight: '70vh',
                overflow: 'auto',
                padding: '10px',
                background: '#f5f5f5',
                borderRadius: '4px',
              }}
            >
              {currentJsonData}
            </pre>
          )}
        </Modal>
      </Spin>
      {messageHolder}
    </TemplateContainer>
  );
};

export default DataInfo;