AgentDisplayConfigEditModal.tsx 6.49 KB
import { useState, useEffect } from 'react';

import { Button, FormItem, Input, MediaWall, Modal, Select } from '../../../packages/ui/src';
import {
  saveAgentDisplayConfig,
  type OfficialSiteConfiguredAgent,
  type DisplayStatus,
  type MediaType,
} from '../../api/officialSiteAgentDisplay';

interface EditModalProps {
  open: boolean;
  agent: OfficialSiteConfiguredAgent | null;
  tabId: number;
  onCancel: () => void;
  onSaveSuccess: () => void;
}

interface EditFormState {
  speech_title: string;
  speech_content: string;
  sort_order: number;
  display_status: DisplayStatus;
  media_url: string;
  media_type: MediaType;
}

interface EditFormErrors {
  speech_content?: string;
  sort_order?: string;
  speech_title?: string;
  media_url?: string;
}

export function AgentDisplayConfigEditModal({
  open,
  agent,
  tabId,
  onCancel,
  onSaveSuccess,
}: EditModalProps) {
  const [form, setForm] = useState<EditFormState>({
    speech_title: '',
    speech_content: '',
    sort_order: 10,
    display_status: 'disable',
    media_url: '',
    media_type: 'gif',
  });

  const [errors, setErrors] = useState<EditFormErrors>({});
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (agent) {
      setForm({
        speech_title: agent.agent_name ?? '',
        speech_content: agent.speech_content ?? '',
        sort_order: agent.sort_order ?? 10,
        display_status: agent.display_status ?? 'disable',
        media_url: agent.media_url ?? '',
        media_type: agent.media_type ?? 'gif',
      });
      setErrors({});
    }
  }, [agent]);

  const validate = () => {
    const nextErrors: EditFormErrors = {};

    if (!form.speech_title.trim()) {
      nextErrors.speech_title = 'Agent名称必填';
    }

    if (!form.speech_content.trim()) {
      nextErrors.speech_content = 'Agent概述必填';
    } else if (form.speech_content.length > 100) {
      nextErrors.speech_content = 'Agent概述不能超过100字';
    }

    if (!form.media_url.trim()) {
      nextErrors.media_url = '展示素材必填';
    }

    if (form.sort_order < 0 || form.sort_order > 99 || !Number.isInteger(form.sort_order)) {
      nextErrors.sort_order = '排序请输入0-99的整数';
    }

    setErrors(nextErrors);
    return Object.keys(nextErrors).length === 0;
  };

  const handleSave = async () => {
    if (!agent) return;

    if (!validate()) return;

    setSaving(true);

    try {
      await saveAgentDisplayConfig(tabId, Number(agent.agent_id), {
        speech_title: form.speech_title,
        speech_content: form.speech_content,
        display_status: form.display_status,
        sort_order: form.sort_order,
        media_url: form.media_url,
        media_type: form.media_type,
        media_size: 0,
      });
      setSaving(false);
      onSaveSuccess();
    } catch {
      setSaving(false);
      setErrors({ speech_content: '保存失败,请重试' });
    }
  };

  const handleRemoveMedia = () => {
    setForm((current) => ({
      ...current,
      media_url: '',
      media_type: 'gif',
    }));
  };

  if (!agent) return null;

  const mediaItems: { id: string; type: 'image' | 'video'; src: string; alt: string }[] = form.media_url
    ? [{ id: 'media', type: (form.media_type === 'mp4' ? 'video' : 'image') as 'image' | 'video', src: form.media_url, alt: '' }]
    : [];

  return (
    <Modal
      open={open}
      title={`编辑展示配置 - ${agent.agent_name}`}
      onCancel={onCancel}
      onOk={handleSave}
      footer={
        <div className="flex justify-end gap-3">
          <Button variant="outline" onClick={onCancel} disabled={saving}>
            取消
          </Button>
          <Button variant="primary" onClick={handleSave} disabled={saving}>
            {saving ? '保存中...' : '确定'}
          </Button>
        </div>
      }
    >
      <div className="grid gap-6 py-4">
        <FormItem label="Agent 名称" layout="horizontal" required error={errors.speech_title}>
          <Input
            className="w-full max-w-[400px]"
            placeholder="请输入Agent名称"
            value={form.speech_title}
            onChange={(value) => setForm((current) => ({ ...current, speech_title: value }))}
          />
        </FormItem>

        <FormItem label="Agent 概述" layout="horizontal" required error={errors.speech_content}>
          <Input
            className="w-full max-w-[400px]"
            placeholder="请输入Agent概述"
            value={form.speech_content}
            onChange={(value) => setForm((current) => ({ ...current, speech_content: value }))}
          />
        </FormItem>

        <FormItem label="展示素材" layout="horizontal" required error={errors.media_url}>
          <MediaWall
            accept="image/png,image/jpeg,image/jpg,image/gif,video/mp4"
            maxCount={1}
            multiple={false}
            items={mediaItems}
            helperText="支持图片、视频、GIF,推荐 1:1,最大 20MB"
            onSelectFiles={(files) => {
              const file = files[0];
              if (!file) return;
              const isVideo = file.type === 'video/mp4';
              setForm((current) => ({
                ...current,
                media_url: `https://mock.assets.local/uploads/${file.name}`,
                media_type: isVideo ? 'mp4' : 'gif',
              }));
            }}
            onRemove={handleRemoveMedia}
          />
        </FormItem>

        <FormItem label="展示排序" layout="horizontal" required error={errors.sort_order}>
          <Input
            className="w-full max-w-[400px]"
            type="number"
            min={0}
            max={99}
            placeholder="请输入展示排序"
            value={form.sort_order === undefined || (typeof form.sort_order === 'number' && isNaN(form.sort_order)) ? '' : String(form.sort_order)}
            onChange={(value) => setForm((current) => ({
              ...current,
              sort_order: value === '' ? undefined as unknown as number : Number(value),
            }))}
          />
        </FormItem>

        <FormItem label="展示状态" layout="horizontal" required>
          <Select
            className="w-full max-w-[400px]"
            options={[
              { value: 'disable', label: '已下架' },
              { value: 'enable', label: '展示中' },
            ]}
            value={form.display_status}
            onChange={(value) => setForm((current) => ({
              ...current,
              display_status: value as DisplayStatus,
            }))}
          />
        </FormItem>
      </div>
    </Modal>
  );
}