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

import store from './store';
import Step from '@/components/step';
import CreateTaskMode from '../components/CreateTaskMode';
import IndicatorRag from '../components/indicatorRag';
import EvaluationTaskHistory from '../components/evaluationTaskHistory';
import { deleteEvaluationApi, beginEvaluationApi } from '@/apis';
import { Tooltip } from 'antd/lib';

interface KnowledgeRecord {
  knowledgeName: 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 } = store;

  const { reviseList, knowledgeName } = state



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

  const [deleteEvaluationTask, setDeleteEvaluationTask] = useState<boolean>(false); // 是否删除评测任务
  const [startEvaluationTask, setStartEvaluationTask] = useState<boolean>(false); // 是否开始评测任务
  const [prewEvaluationTask, setPrewEvaluationTask] = useState<boolean>(false); // 是否雷达图预览
  const [userInfoAll, setUserInfoAll] = React.useState<any>({});

  const [openEvaluationTaskHistory,setOpenEvaluationTaskHistory] = useState<boolean>(false);

  useEffect(() => {
    init();

    setDeleteEvaluationTask(LocalStorage.getStatusFlag('evaluationTool:evaluationTask:del'));
    setStartEvaluationTask(LocalStorage.getStatusFlag('evaluationTool:evaluationTask:start'));
    setPrewEvaluationTask(LocalStorage.getStatusFlag('evaluationTool:evaluationTask:prew'));
    setUserInfoAll(LocalStorage.getUserInfo());
    const handleEvaluationTaskCreate = (e: any) => {
      if (e.detail && e.detail.platform === 'Task') {
        setOpenCreateTaskMode(true);
      }
    }

    const handlEvaluationTaskHistoryCreate = (e: any) => {
      if (e.detail && e.detail.platform === 'evaluationTaskHistory') {
        setOpenEvaluationTaskHistory(true);
      }
    }



    window.addEventListener('evaluationTask', handleEvaluationTaskCreate as EventListener);
    window.addEventListener('evaluationTaskHistory', handlEvaluationTaskHistoryCreate as EventListener);

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

  const steps = [
    {
      title: '创建评测任务',
      description: '上传本地数据集，选择需要评测的RAG或模型，进行自动评测；',
      number: 1,
    },
    {
      title: '配置打分模型',
      description: '选择自动打分的模型，设置不同的评估维度；',
      number: 2,
    },
    {
      title: '查看评测报告',
      description: '生成多维度的评测报告，查看详细评分、能力指标、评估日志。',
      number: 3,
    }
  ]
  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 [openIndicatorRag, setOpenIndicatorRag] = useState<boolean>(false);

  const onBeginEvaluationApi = async (record: any) => {
    const res: any = await beginEvaluationApi({ ...record });
    if (res.code === 200) {
      message.success('评测任务启动成功');
      init();
    }
  }


  const columns: ColumnsType<KnowledgeRecord> = [
    {
      title: '任务名称/ID', dataIndex: 'taskId', width: 220,
      render: (text, record: any) => {
        return <div>
          {(prewEvaluationTask || userInfoAll.id === record.createBy) ? <div style={{ fontWeight: 600 }} className='cursor-pointer text-primary' onClick={() => {
            setOpenIndicatorRag(true)
            setRecord(record)
          }} >{record.taskName}</div> : <div style={{ fontWeight: 600 }}>{record.taskName}</div>}
          <div style={{ color: '#999', fontSize: 12, marginTop: 4 }}>ID: {record?.taskId}
          </div>
        </div>
      },
    },
    {
      title: '状态', dataIndex: 'status', width: 120,
      render: (text) => {
        let color = '#52c41a';
        let statusText = '';
        if (text === '0') {
          color = '';
          statusText = '未执行';
        } else if (text === '1') {
          return <Spin size="small" />;
        } else if (text === '2') {
          color = '#52c41a';
          statusText = '成功';
        } else if (text === '3') {
          color = '';
          statusText = '失败';
        }
        return <span style={{ color }}>{statusText}</span>;
      }
    },
    {
      title: '模型服务', dataIndex: 'model', width: 120
    },
    { title: '类型', dataIndex: 'evaluationType', width: 140 },
    { title: '数据集', dataIndex: 'datesetName', width: 140 },
    { title: '结果打分', dataIndex: 'resultStore', width: 140 },
    { title: '创建时间', dataIndex: 'createTime', width: 140 },
    { title: '开始时间', dataIndex: 'startTime', width: 140 },
    { title: '结束时间', dataIndex: 'endTime', width: 140 },
    {
      title: '操作',
      dataIndex: 'status',
      align: 'center',
      width: 120,
      render: (val, record: any) => (
        <p className='flex items-center justify-center'>
          {(prewEvaluationTask || userInfoAll.id === record.createBy) && <Tooltip title="详情">
            <Button 
            type="link"
            style={{ paddingLeft: 0 }}
            onClick={()=>{
             setOpenIndicatorRag(true)
            setRecord(record)
          }} icon={<RadarChartOutlined />}/>
          </Tooltip>}
          { (record.status === '2'||record.status === '3') &&<Tooltip title="查看评测历史">
            <Button 
            type="link"
            style={{ paddingLeft: 0 }}
            onClick={()=>{
            setOpenEvaluationTaskHistory(true);
            setRecord(record)
          }} icon={<LayoutOutlined />}/>
          </Tooltip>}
          {(startEvaluationTask || userInfoAll.id === record.createBy) && record.status === '0' && <Button type="link" onClick={async () => {
            onBeginEvaluationApi(record)
          }}>开始</Button>}
          {(startEvaluationTask || userInfoAll.id === record.createBy) && record.status !== '0'&&record.status !== '1' && <Tooltip title="重新评测"><Button type="link" icon={<RedoOutlined />} onClick={() => { onBeginEvaluationApi(record) }}></Button></Tooltip>}
          {(deleteEvaluationTask || userInfoAll.id === record.createBy) && <Button type="link"
           icon={<DeleteOutlined />}
           style={{ color: '#ff4d4f', paddingLeft: 0 }}
            onClick={() => {
              Modal.confirm({
                title: '提示',
                content: `确定删除【${record.taskName}】任务吗？`,
                okType: 'danger',
                onOk: async () => {
                  const res: any = await deleteEvaluationApi(record.taskId);
                  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 [openCreateTaskMode, setOpenCreateTaskMode] = 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' }} />
          提示: 开始评测模型
        </div>
        <CloseOutlined onClick={hideGuide} style={{ color: '#999', cursor: 'pointer' }} />
      </div>
        <Step steps={steps} className='mb-3' /></>}
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 12 }} className='items-center'>
        <p style={{ margin: 0 }}>任务管理</p>
        <Space.Compact style={{ width: '300px' }}>
          <Input
            placeholder='请输入任务名称'
            value={knowledgeName}
            onChange={(e) => handleNameChange(e.target.value)}
          />
          <Button type="primary" onClick={() => { init() }}><SearchOutlined /></Button>
        </Space.Compact>
      </div>
      {/* 表格 */}
      <Table
        columns={columns}
        dataSource={reviseList}
        rowKey="taskId"
        loading={loading}
        pagination={paginationConfig}
      />
      {/* 修订工具弹窗 */}
      {/* { <ReviseDrawer openDrawer={openDrawer} record={record} title={title} onClose={() => setOpenDrawer(false)} />} */}
      <CreateTaskMode openCreateTaskMode={openCreateTaskMode} onCancel={() => { setOpenCreateTaskMode(false), init() }}></CreateTaskMode>
      <IndicatorRag open={openIndicatorRag} record={record} onCancel={() => {
        setOpenIndicatorRag(false);
      }}></IndicatorRag>
      <EvaluationTaskHistory open={openEvaluationTaskHistory}  record={record} onClose={() => {
        setOpenEvaluationTaskHistory(false);
      }}></EvaluationTaskHistory>
    </div>
  );
};

export default observer(RevisionToolList);
