PromptList.tsx 9.15 KB
import { useEffect, useState } from 'react';
import { Table, Button, Card, Space, Tag, Modal, message, Input, Tooltip, Typography } from 'antd';
import { PlusOutlined, EditOutlined, ReloadOutlined, FileTextOutlined, HistoryOutlined, DeleteOutlined } from '@ant-design/icons';
import { usePromptStore } from '../../stores/promptStore';
import PromptForm from './PromptForm';
import PromptDetail from './PromptDetail';
import type { Prompt } from '../../types';
import { TEMPLATE_TYPE_OPTIONS } from '../../types';

const { Search } = Input;

const TEMPLATE_TYPE_MAP = Object.fromEntries(
  TEMPLATE_TYPE_OPTIONS.map((opt) => [opt.value, opt.label]),
);

const TEMPLATE_COLORS: Record<string, string> = {
  general: 'blue',
  quality_inspection: 'purple',
  image: 'cyan',
  param_text: 'orange',
  audio_summary: 'green',
  employee_review: 'pink',
};

const STATUS_OPTIONS = [
  { label: '已发布', value: 'published' },
  { label: '草稿', value: 'draft' },
  { label: '已归档', value: 'archived' },
];

const STATUS_MAP = Object.fromEntries(STATUS_OPTIONS.map((opt) => [opt.value, opt.label]));

export default function PromptList() {
  const { prompts, total, page, pageSize, loading, fetchPrompts, deletePrompt } = usePromptStore();
  const [modalOpen, setModalOpen] = useState(false);
  const [editingPrompt, setEditingPrompt] = useState<Prompt | null>(null);
  const [typeFilter, setTypeFilter] = useState<string | undefined>(undefined);
  const [detailOpen, setDetailOpen] = useState(false);
  const [detailPromptId, setDetailPromptId] = useState<string | null>(null);

  useEffect(() => {
    fetchPrompts({ template_type: typeFilter });
  }, [fetchPrompts, typeFilter]);

  const handleEdit = (record: Prompt) => {
    setEditingPrompt(record);
    setModalOpen(true);
  };

  const handleViewDetail = (record: Prompt) => {
    setDetailPromptId(record.id);
    setDetailOpen(true);
  };

  const handleDelete = (record: Prompt) => {
    Modal.confirm({
      title: '确认删除',
      content: (
        <div style={{ paddingTop: 8 }}>
          <p>确定要删除提示词模板「<strong>{record.title}</strong>」吗?</p>
          <p style={{ color: 'var(--color-text-muted)', fontSize: 13, marginTop: 4 }}>
            删除后将标记为已删除状态,数据保留可恢复
          </p>
        </div>
      ),
      okText: '确认删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          await deletePrompt(record.id);
          message.success('删除成功');
        } catch {
          message.error('删除失败,请重试');
        }
      },
    });
  };

  const handleCreate = () => {
    setEditingPrompt(null);
    setModalOpen(true);
  };

  const handleSearch = (value: string) => {
    fetchPrompts({ title: value || undefined, template_type: typeFilter });
  };

  const handleTypeFilter = (type: string | undefined) => {
    setTypeFilter(type);
    fetchPrompts({ template_type: type, page: 1 });
  };

  const renderTypeTag = (type: string) => (
    <Tag color={TEMPLATE_COLORS[type] || 'default'} className="strategy-tag">
      {TEMPLATE_TYPE_MAP[type] || type}
    </Tag>
  );

  const renderStatus = (val: string) => {
    const colorMap: Record<string, string> = { published: 'success', draft: 'default', archived: 'warning' };
    return (
      <Tag className="status-tag" color={colorMap[val] || 'default'}>
        <span className={`status-dot ${val === 'published' ? 'active' : val === 'draft' ? 'disabled' : ''}`} />
        {STATUS_MAP[val] || val}
      </Tag>
    );
  };

  const renderPromptPreview = (text: string) => {
    const maxLen = 80;
    const display = text.length > maxLen ? text.slice(0, maxLen) + '...' : text;
    return (
      <code style={{
        fontSize: 12,
        fontFamily: "'JetBrains Mono', monospace",
        color: 'var(--color-text-secondary)',
        background: 'var(--color-surface-subtle)',
        padding: '4px 8px',
        borderRadius: 4,
        border: '1px solid var(--color-border-light)',
        display: 'block',
        maxWidth: 400,
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        lineHeight: 1.6,
      }}>
        {display}
      </code>
    );
  };

  const columns = [
    {
      title: '模板标题',
      dataIndex: 'title',
      key: 'title',
      width: 160,
      render: (val: string, record: Prompt) => (
        <Space>
          <FileTextOutlined style={{ color: 'var(--color-primary)' }} />
          <span style={{ fontWeight: 500 }}>{val}</span>
          <Tag style={{ fontSize: 11, marginLeft: 4 }}>v{record.version}</Tag>
        </Space>
      ),
    },
    {
      title: '业务编码',
      dataIndex: 'code',
      key: 'code',
      width: 200,
      render: (val: string) => (
        <Typography.Text copyable={{ text: val }} style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
          <code style={{
            fontSize: 12,
            fontFamily: "'JetBrains Mono', monospace",
            color: 'var(--color-text-secondary)',
            background: 'var(--color-surface-subtle)',
            padding: '2px 6px',
            borderRadius: 4,
            border: '1px solid var(--color-border-light)',
          }}>
            {val}
          </code>
        </Typography.Text>
      ),
    },
    {
      title: '类型',
      dataIndex: 'template_type',
      key: 'template_type',
      width: 110,
      render: renderTypeTag,
    },
    {
      title: 'System Prompt 预览',
      dataIndex: 'system_prompt',
      key: 'system_prompt',
      render: renderPromptPreview,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 90,
      render: renderStatus,
    },
    {
      title: '操作',
      key: 'action',
      width: 240,
      render: (_: unknown, record: Prompt) => (
        <Space>
          <Tooltip title="查看详情和版本历史">
            <Button type="link" size="small" icon={<HistoryOutlined />} onClick={() => handleViewDetail(record)} className="action-btn">
              详情
            </Button>
          </Tooltip>
          <Tooltip title="编辑模板">
            <Button type="link" size="small" icon={<EditOutlined />} onClick={() => handleEdit(record)} className="action-btn">
              编辑
            </Button>
          </Tooltip>
          <Tooltip title="删除模板">
            <Button type="link" size="small" danger icon={<DeleteOutlined />} onClick={() => handleDelete(record)} className="action-btn">
              删除
            </Button>
          </Tooltip>
        </Space>
      ),
    },
  ];

  return (
    <>
      <div className="page-header">
        <div className="page-header-left">
          <h4 className="page-header-title">提示词模板</h4>
          <span className="page-header-desc">管理 System/User Prompt 模板,支持多类型和版本管理</span>
        </div>
        <div className="page-header-actions">
          <Search
            placeholder="搜索模板标题..."
            allowClear
            onSearch={handleSearch}
            style={{ width: 240 }}
            className="page-search"
          />
          <Button icon={<ReloadOutlined />} onClick={() => fetchPrompts({ template_type: typeFilter })} className="action-btn" />
          <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate} className="action-btn">
            新增模板
          </Button>
        </div>
      </div>

      {/* 类型筛选标签 */}
      <div style={{ marginBottom: 16, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        <Tag
          className="filter-tag"
          color={!typeFilter ? 'blue' : 'default'}
          style={{ cursor: 'pointer', padding: '4px 12px' }}
          onClick={() => handleTypeFilter(undefined)}
        >
          全部
        </Tag>
        {TEMPLATE_TYPE_OPTIONS.map((opt) => (
          <Tag
            key={opt.value}
            className="filter-tag"
            color={typeFilter === opt.value ? (TEMPLATE_COLORS[opt.value] || 'blue') : 'default'}
            style={{ cursor: 'pointer', padding: '4px 12px' }}
            onClick={() => handleTypeFilter(opt.value)}
          >
            {opt.label}
          </Tag>
        ))}
      </div>

      <Card className="page-card" styles={{ body: { padding: 0 } }}>
        <Table
          dataSource={prompts}
          columns={columns}
          rowKey="id"
          loading={loading}
          className="page-table"
          pagination={{
            current: page,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            pageSizeOptions: ['10', '20', '50'],
            showTotal: (t) => `共 ${t} 条`,
            onChange: (p, ps) => fetchPrompts({ page: p, page_size: ps, template_type: typeFilter }),
          }}
        />
      </Card>

      <PromptForm
        open={modalOpen}
        prompt={editingPrompt}
        onClose={() => {
          setModalOpen(false);
          setEditingPrompt(null);
        }}
      />

      <PromptDetail
        open={detailOpen}
        promptId={detailPromptId}
        onClose={() => {
          setDetailOpen(false);
          setDetailPromptId(null);
        }}
      />
    </>
  );
}