import React, { useEffect, useMemo, useState } from 'react';
import { Table, Pagination, Space, Button, TablePaginationConfig, Input } from 'antd';
import type { ColumnsType } from 'antd/es/table';

import { SearchOutlined, BulbOutlined, CloseOutlined } from '@ant-design/icons';

import store from './store';
import Step from '@/components/step';
import ReviseDrawer from '../components/reviseDrawer';
import LocalStorage from '@/LocalStorage';


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


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

    setAllupdateSliceDoc(LocalStorage.getStatusFlag('knowledge:revisionTool:all'));
    setSingleUpdateSliceDoc(LocalStorage.getStatusFlag('knowledge:revisionTool:single'));



    init();
  }, []);

  const steps = [
    {
      title: '选择知识库',
      description: '选中某个已解析完成的标准规范类知识库',
      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 columns: ColumnsType<KnowledgeRecord> = [
    {
      title: '知识库名称/ID', dataIndex: 'knowledgeName', width: 220,
      render: (text, record: any) => {
        return <div>
          <div style={{ fontWeight: 600 }} className='cursor-pointer text-primary'>{text}</div>
          <div style={{ color: '#999', fontSize: 12, marginTop: 4 }}>ID: {record?.knowledgeId}
          </div>
        </div>
      },
    },
    {
      title: '关联RAG应用', dataIndex: 'appNames', width: 120, render: (text) => (
          text.length ? text.map((item: string, index: number) => (
              <span key={index} className='mr-2'>{item}{index === text.length - 1 ? '' : ','}</span>
          )) : '-'
      )
    },
    { title: '使用空间', dataIndex: 'length', width: 120 },

    { title: '文件数量', dataIndex: 'documentSize', width: 120 },
    { title: '创建时间', dataIndex: 'createTime', width: 140 },
    { title: '更新时间', dataIndex: 'updateTime', width: 140 },
    {
      title: '操作',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      width: 120,
      render: (val, record) => (
        singleUpdateSliceDoc ? <Button type="link" onClick={() => { setOpenDrawer(true); setTitle(record.knowledgeName); setRecord(record); }}>当前知识修订</Button> :
        '-'
        // <Button type="link" onClick={() => { setOpenDrawer(true); setTitle(record.knowledgeName); setRecord(record); }}>当前知识修订</Button>
      ),
    }
  ]

  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 [openDrawer, setOpenDrawer] = 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 }}>
        {allupdateSliceDoc && <Button type="primary" style={{ margin: 0 }} onClick={() => { setOpenDrawer(true); setRecord({} as KnowledgeRecord); setTitle('全局修订工具'); }}>全局修订工具</Button>}
        <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="knowledgeId"
        loading={loading}
        pagination={paginationConfig}
      />
      {/* 修订工具弹窗 */}
      {<ReviseDrawer openDrawer={openDrawer} record={record} title={title} onClose={() => setOpenDrawer(false)} />}
    </div>
  );
};

export default observer(RevisionToolList);
