import React, { useEffect, useMemo, useState } from 'react';
import { Table, Pagination, Modal, Space, Button, TablePaginationConfig, Input, Radio, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { observer } from 'mobx-react';
import { SearchOutlined, BulbOutlined, CloseOutlined } from '@ant-design/icons';
import LocalStorage from '@/LocalStorage';

import store from './store';
import DataManagementMode from '../components/dataManagementMode';
import ExampleModel from '../components/exampleModel';

import { deleteDatasetApi } from '@/apis';

interface KnowledgeRecord {
  name: string;
  knowledgeId: string | number;
  length: string | number; // 使用空间
  appNames: string; // 关联空间
  documentSize: number; // 文件数量
  createTime: string; // 创建时间
  updateTime: string; // 更新时间
  status: string | number; // 状态
}


const RevisionToolList: React.FC = () => {
  const [loading, setLoading] = useState(false);

  const { state, init, handleNameChange, onChangePagination, handleModeChange } = store;

  const { reviseList, name } = state



  useEffect(() => {
    // 模拟加载状态
    setLoading(true);
    const t = setTimeout(() => setLoading(false), 250);
    return () => clearTimeout(t);
  }, [state.page]);

  const [deletedatasetManagement, setDeletedatasetManagement] = useState<boolean>(false); // 是否删除数据集
  const [downloaddatasetManagement, setDownloaddatasetManagement] = useState<boolean>(false); // 下载数据集
  const [userInfoAll, setUserInfoAll] = React.useState<any>({});

  useEffect(() => {
    init();


    setDeletedatasetManagement(LocalStorage.getStatusFlag('evaluationTool:datasetManagement:del'));
    setDownloaddatasetManagement(LocalStorage.getStatusFlag('evaluationTool:datasetManagement:download'));
    setUserInfoAll(LocalStorage.getUserInfo());





    const handleEvaluationTaskCreate = (e: any) => {
      if (e.detail && e.detail.platform === 'Management') {
        console.log('监听到创建数据集事件');
        setOpenDataManagementMode(true);
      }
    }
    window.addEventListener('datasetManagement', handleEvaluationTaskCreate as EventListener);

    return () => {
      window.removeEventListener('datasetManagement', handleEvaluationTaskCreate as EventListener);
    };
  }, []);

  const [showGuide, setShowGuide] = React.useState<boolean>(() => localStorage.getItem('revisionToolGuideHidden') !== 'true');
  const hideGuide = () => { localStorage.setItem('revisionToolGuideHidden', 'true'); setShowGuide(false); };
  const [record, setRecord] = useState<KnowledgeRecord>({} as KnowledgeRecord);
  const columns: ColumnsType<KnowledgeRecord> = [
    {
      title: '数据集名称', dataIndex: 'name', width: 220,
      render: (text, record: any) => {
        return <div>
          <div style={{ fontWeight: 600 }} className='cursor-pointer'>{text}</div>
        </div>
      },
    },
    { title: '描述', dataIndex: 'description' },
    {
      title: '创建人', dataIndex: 'nickName', width: 120,
    },
    { title: '创建时机', dataIndex: 'createTime', width: 190 },
    // { title: '更新时间', dataIndex: 'updateTime', width: 140 },
    {
      title: '操作',
      dataIndex: 'status',
      align: 'center',
      width: 120,
      render: (val, record: any) => (
        <p className='flex'>
          {(downloaddatasetManagement || userInfoAll.id === record.createBy) && <Button type="link" onClick={() => { window.open(record.url) }}>下载</Button>}
          {(deletedatasetManagement || userInfoAll.id === record.createBy) && <Button type="link" style={{ color: '#ff4d4f', paddingLeft: 0 }} onClick={() => {
            Modal.confirm({
              title: '删除',
              content: `确定删除吗？`,
              okType: 'danger',
              onOk: async () => {
                const res: any = await deleteDatasetApi(record.id);
                if (res.code === 200) {
                  message.success('删除成功');
                  init();
                }
              }
            });
          }}>删除</Button>}
        </p>
      ),
    }
  ]

  const paginationConfig: TablePaginationConfig = {
    // 显示数据总量
    showTotal: (total: number) => {
      return `共 ${total} 条`;
    },
    // 展示分页条数切换
    showSizeChanger: true,
    // 指定每页显示条数
    pageSizeOptions: ['10', '20', '50', '100'],
    // 快速跳转至某页
    showQuickJumper: true,
    current: state.page.page,
    pageSize: state.page.size,
    total: state.page.total,
    onChange: async (page, pageSize) => {
      await onChangePagination(page, pageSize);
    },
  };
  const [openDataManagementMode, setOpenDataManagementMode] = useState(false);
  const [ExampleModelVisible, setExampleModelVisible] = useState(false);
  const [title, setTitle] = useState('');
  return (
    <div style={{ padding: 20, background: '#fff' }}>
      {showGuide && <> <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
        <div style={{ fontSize: 13, color: '#333', display: 'flex', alignItems: 'center', gap: 6 }}>
          <BulbOutlined style={{ color: '#faad14' }} />
          参考数据模版及数据格式要求，准备并上传您的评测数据。提供和您实际场景相关的问题以评估RAG或模型的效果和场景匹配性。<span className='text-primary cursor-pointer'
            onClick={() => {
              setExampleModelVisible(true);
            }}
          >查看示例数据</span>
        </div>
        {/* <CloseOutlined onClick={hideGuide} style={{ color: '#999', cursor: 'pointer' }} /> */}
      </div></>}
      <div className='mb-2'>
        <Radio.Group onChange={(e) => {
          handleModeChange(e.target.value)
        }} value={state.createBy} style={{ marginBottom: 8 }}>
          <Radio.Button value="">全部</Radio.Button>
          <Radio.Button value={state.myCreateBy}>我创建的</Radio.Button>
        </Radio.Group>
        <Space.Compact style={{ width: '300px', float: 'right' }}>
          <Input
            placeholder='请输入数据集名称'
            value={name}
            onChange={(e) => handleNameChange(e.target.value)}
          />
          <Button type="primary" onClick={() => { init() }}><SearchOutlined /></Button>
        </Space.Compact>
      </div>
      {/* 表格 */}
      <Table
        columns={columns}
        dataSource={reviseList}
        rowKey="id"
        loading={loading}
        pagination={paginationConfig}
      />
      {/* 修订工具弹窗 */}
      {openDataManagementMode && <DataManagementMode openDataManagementMode={openDataManagementMode} onCancel={() => { setOpenDataManagementMode(false); init(); }} />}
      {/* 示例数据文件弹窗 */}
      {<ExampleModel visible={ExampleModelVisible} onClose={() => {
        setExampleModelVisible(false);
      }} />}
    </div>
  );
};

export default observer(RevisionToolList);
