ProviderForm.tsx 7.26 KB
import { useEffect, useRef, useState, useCallback } from 'react';
import { Modal, Form, Input, Select, Button } from 'antd';
import { Tag } from 'antd';
import { PlusOutlined, CloseOutlined } from '@ant-design/icons';
import { useProviderStore } from '../../stores/providerStore';
import type { Provider } from '../../types';

interface Props {
  open: boolean;
  provider: Provider | null;
  onClose: () => void;
}

export default function ProviderForm({ open, provider, onClose }: Props) {
  const [form] = Form.useForm();
  const { updateProvider } = useProviderStore();
  const [submitting, setSubmitting] = useState(false);
  const [dirty, setDirty] = useState(false);
  const [modelInput, setModelInput] = useState('');
  const [models, setModels] = useState<string[]>([]);
  const firstFieldRef = useRef<HTMLInputElement>(null);
  const isInitialMount = useRef(true);

  useEffect(() => {
    if (open && provider) {
      setDirty(false);
      isInitialMount.current = true;
      setModelInput('');
      const initModels = provider.supported_models ?? [];
      setModels(initModels);
      form.setFieldsValue({
        display_name: provider.display_name,
        description: provider.description,
        default_model: provider.default_model,
        supported_models: initModels,
      });
      setTimeout(() => firstFieldRef.current?.focus(), 300);
    }
  }, [open, provider, form]);

  const onFieldsChange = useCallback(() => {
    if (isInitialMount.current) {
      isInitialMount.current = false;
      return;
    }
    if (!dirty && form.isFieldsTouched()) {
      setDirty(true);
    }
  }, [dirty, form]);

  const handleClose = useCallback(() => {
    if (dirty) {
      Modal.confirm({
        title: '未保存的更改',
        content: '当前表单有未保存的修改,确定要关闭吗?',
        okText: '关闭',
        cancelText: '继续编辑',
        onOk: onClose,
      });
    } else {
      onClose();
    }
  }, [dirty, onClose]);

  const addModel = () => {
    const trimmed = modelInput.trim();
    if (!trimmed) return;
    if (models.includes(trimmed)) return;
    const next = [...models, trimmed];
    setModels(next);
    form.setFieldValue('supported_models', next);
    setModelInput('');
    setDirty(true);
  };

  const removeModel = (model: string) => {
    const next = models.filter((m) => m !== model);
    setModels(next);
    form.setFieldValue('supported_models', next);
    // 清除已被删除的默认模型
    const currentDefault = form.getFieldValue('default_model');
    if (currentDefault === model) {
      form.setFieldValue('default_model', undefined);
    }
    setDirty(true);
  };

  const handleModelInputKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      addModel();
    }
  };

  const handleOk = async () => {
    try {
      setSubmitting(true);
      const values = await form.validateFields();
      const submitData = {
        ...values,
        supported_models: models,
      };
      await updateProvider(provider!.id, submitData);
      onClose();
    } catch {
      // validation errors shown inline
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Modal
      title="编辑供应商"
      open={open}
      onOk={handleOk}
      onCancel={handleClose}
      okText="保存"
      cancelText="取消"
      destroyOnHidden
      width={640}
      confirmLoading={submitting}
    >
      <Form
        form={form}
        layout="vertical"
        style={{ marginTop: 8 }}
        onFieldsChange={onFieldsChange}
        initialValues={{ supported_models: [] }}
      >
        {/* 基本信息 */}
        <div className="form-section">
          <div className="form-section-header">
            <h5>基本信息</h5>
            <span className="section-hint">只读信息来自代码配置</span>
          </div>
          <div className="form-field-enter">
            <Form.Item label="供应商名称">
              <Input value={provider?.provider_name ?? ''} disabled />
            </Form.Item>
          </div>
          <div className="form-field-enter">
            <Form.Item
              name="display_name"
              label="显示名称"
              rules={[{ required: true, message: '请输入显示名称' }]}
            >
              <Input placeholder="例如: 通义千问" ref={firstFieldRef} />
            </Form.Item>
          </div>
          <div className="form-field-enter">
            <Form.Item label="适配器类型">
              <Input value={provider?.adapter_type ?? ''} disabled />
            </Form.Item>
          </div>
        </div>

        {/* 模型配置 */}
        <div className="form-section">
          <div className="form-section-header">
            <h5>模型配置</h5>
            <span className="section-hint">逐一添加支持的模型</span>
          </div>
          <div className="form-field-enter">
            <Form.Item label="支持的模型" required>
              <div className="model-add-row">
                <Input
                  placeholder="输入模型名称,例如 qwen-plus"
                  value={modelInput}
                  onChange={(e) => setModelInput(e.target.value)}
                  onKeyDown={handleModelInputKeyDown}
                  className="model-add-input"
                />
                <Button
                  type="primary"
                  ghost
                  icon={<PlusOutlined />}
                  onClick={addModel}
                  className="model-add-btn"
                >
                  添加
                </Button>
              </div>
              {models.length > 0 && (
                <div className="model-tag-list">
                  {models.map((m) => (
                    <span key={m} className="model-tag-item">
                      <span>{m}</span>
                      <button
                        type="button"
                        className="model-tag-remove"
                        onClick={() => removeModel(m)}
                        aria-label={`移除 ${m}`}
                      >
                        <CloseOutlined />
                      </button>
                    </span>
                  ))}
                </div>
              )}
              {models.length === 0 && (
                <span className="model-tag-empty">尚未添加模型,在上方输入后点击"添加"</span>
              )}
            </Form.Item>
          </div>
          <div className="form-field-enter">
            <Form.Item name="default_model" label="默认模型">
              <Select
                placeholder="从支持的模型中选择默认模型"
                options={models.map((m) => ({ label: m, value: m }))}
                allowClear
              />
            </Form.Item>
          </div>
        </div>

        {/* 其他信息 */}
        <div className="form-section">
          <div className="form-section-header">
            <h5>其他信息</h5>
            <span className="section-hint">备注和描述</span>
          </div>
          <div className="form-field-enter">
            <Form.Item name="description" label="描述">
              <Input.TextArea rows={3} placeholder="供应商描述、使用注意事项等(可选)" />
            </Form.Item>
          </div>
        </div>
      </Form>
    </Modal>
  );
}