AccountForm.tsx 12.5 KB
import { useEffect, useRef, useState, useCallback } from 'react';
import { Modal, Form, Input, Select, InputNumber, AutoComplete, Space, Button, Switch } from 'antd';
import { EyeOutlined, EyeInvisibleOutlined, BulbOutlined } from '@ant-design/icons';
import { useAccountStore } from '../../stores/accountStore';
import { accountService } from '../../services/accountService';
import { useProviderStore } from '../../stores/providerStore';
import type { Account } from '../../types';

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

const SECTION_BADGES = ['01', '02', '03'] as const;

export default function AccountForm({ open, account, onClose }: Props) {
  const [form] = Form.useForm();
  const { createAccount, updateAccount } = useAccountStore();
  const { providers, fetchProviders } = useProviderStore();
  const isEdit = !!account;
  const [selectedProviderId, setSelectedProviderId] = useState<string | undefined>();
  const [submitting, setSubmitting] = useState(false);
  const [modelLoading, setModelLoading] = useState(false);
  const [dirty, setDirty] = useState(false);
  const [decryptedKey, setDecryptedKey] = useState<string | null>(null);
  const [showDecryptedKey, setShowDecryptedKey] = useState(false);
  const [keyLoading, setKeyLoading] = useState(false);
  const firstFieldRef = useRef<HTMLInputElement>(null);
  const isInitialMount = useRef(true);
  const [thinkingEnabled, setThinkingEnabled] = useState(false);

  useEffect(() => {
    fetchProviders();
  }, [fetchProviders]);

  useEffect(() => {
    if (open) {
      setDirty(false);
      setDecryptedKey(null);
      setShowDecryptedKey(false);
      isInitialMount.current = true;
      if (account) {
        // 只设置非敏感字段,api_key 留空让用户决定是否修改
        const { api_key, ...safeFields } = account;
        form.setFieldsValue(safeFields);
        setSelectedProviderId(account.provider_id);
        setThinkingEnabled(account.extra_config?.thinking_enabled ?? false);
      } else {
        form.resetFields();
        setSelectedProviderId(undefined);
        setThinkingEnabled(false);
      }
      // Auto-focus first field after modal animation
      setTimeout(() => firstFieldRef.current?.focus(), 300);
    }
  }, [open, account, form]);

  // Track dirty state
  const onFieldsChange = useCallback(() => {
    // Skip the initial form population
    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 handleToggleKeyVisibility = async () => {
    if (showDecryptedKey) {
      setShowDecryptedKey(false);
      return;
    }
    if (decryptedKey) {
      setShowDecryptedKey(true);
      return;
    }
    // Fetch decrypted key from API
    if (!account) return;
    setKeyLoading(true);
    try {
      const key = await accountService.getDecryptedKey(account.id);
      setDecryptedKey(key);
      setShowDecryptedKey(true);
    } catch {
      Modal.error({ title: '获取失败', content: '无法获取解密后的 API Key,请稍后重试' });
    } finally {
      setKeyLoading(false);
    }
  };

  const selectedProvider = providers.find((p) => p.id === selectedProviderId);
  const modelOptions = selectedProvider?.supported_models?.map((m) => ({
    label: m,
    value: m,
  })) ?? [];

  const handleProviderChange = (val: string) => {
    setSelectedProviderId(val);
    form.setFieldValue('model_name', '');
    // Simulate loading for model field when provider changes
    setModelLoading(true);
    setTimeout(() => setModelLoading(false), 400);
  };

  const handleOk = async () => {
    try {
      setSubmitting(true);
      const values = await form.validateFields();
      // 将思考模式开关合并到 extra_config
      const extraConfig = values.extra_config || {};
      extraConfig.thinking_enabled = thinkingEnabled;
      values.extra_config = extraConfig;
      if (isEdit) {
        const cleanData: Record<string, unknown> = {};
        for (const [k, v] of Object.entries(values)) {
          if (v !== undefined && v !== null && v !== '') {
            cleanData[k] = v;
          }
        }
        // 确保 extra_config 即使其他字段为空也能提交
        if (Object.keys(extraConfig).length === 0) {
          delete cleanData.extra_config;
        }
        await updateAccount(account!.id, cleanData);
      } else {
        await createAccount(values);
      }
      onClose();
    } catch {
      // validation errors shown inline
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Modal
      title={isEdit ? '编辑账号' : '新增账号'}
      open={open}
      onOk={handleOk}
      onCancel={handleClose}
      okText="保存"
      cancelText="取消"
      destroyOnHidden
      width={640}
      confirmLoading={submitting}
      className={dirty ? 'has-dirty-dot' : ''}
      footer={(_, { OkBtn, CancelBtn }) => (
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span className="kbd-hint">
            按 <kbd>Ctrl</kbd> + <kbd>Enter</kbd> 快速保存
          </span>
          <div style={{ display: 'flex', gap: 8 }}>
            <CancelBtn />
            <OkBtn />
          </div>
        </div>
      )}
    >
      <Form
        form={form}
        layout="vertical"
        style={{ marginTop: 8 }}
        onFieldsChange={onFieldsChange}
      >
        {/* Section 1: 基础信息 */}
        <div className="form-section">
          <div className="form-section-header">
            <span className="section-badge">{SECTION_BADGES[0]}</span>
            <h5>基础信息</h5>
            <span className="section-hint">选择供应商并命名账号</span>
          </div>
          <div className="form-field-enter">
            <Form.Item
              name="provider_id"
              label="关联供应商"
              rules={[{ required: true, message: '请选择供应商' }]}
            >
              <Select
                showSearch
                placeholder="选择供应商"
                optionFilterProp="label"
                onChange={handleProviderChange}
                options={providers.map((p) => ({
                  label: p.display_name,
                  value: p.id,
                  disabled: p.status !== 'active',
                }))}
              />
            </Form.Item>
          </div>
          <div className="form-field-enter">
            <Form.Item
              name="account_name"
              label="账号名称"
              rules={[
                { required: true, message: '请输入账号名称' },
                { pattern: /^[a-zA-Z0-9_-]+$/, message: '仅支持字母、数字、下划线和连字符' },
              ]}
              extra="建议使用环境前缀,如 dev-main, prod-main"
            >
              <Input placeholder="例如: dev-main" ref={firstFieldRef} />
            </Form.Item>
          </div>
          <div className="form-field-enter">
            <Form.Item
              name="code"
              label="业务编码"
              rules={[
                { required: !isEdit, message: '请输入业务编码' },
                { pattern: /^[a-zA-Z0-9_-]+$/, message: '仅支持字母、数字、下划线和连字符' },
              ]}
              extra="跨环境唯一标识,如 ACCOUNT-QWEN-001,创建后不可修改"
            >
              <Input placeholder="例如: ACCOUNT-QWEN-001" disabled={isEdit} />
            </Form.Item>
          </div>
        </div>

        {/* Section 2: 凭证配置 */}
        <div className="form-section">
          <div className="form-section-header">
            <span className="section-badge">{SECTION_BADGES[1]}</span>
            <h5>凭证配置</h5>
            <span className="section-hint">API 密钥和接入地址</span>
          </div>
          <div className="form-field-enter">
            <Form.Item
              name="api_key"
              label="API Key"
              rules={isEdit ? [] : [{ required: true, message: '请输入 API Key' }]}
              extra={isEdit ? '留空则不修改当前 API Key' : undefined}
            >
              {isEdit ? (
                <Space.Compact style={{ width: '100%' }}>
                  <Input
                    placeholder="留空则不修改"
                    autoComplete="off"
                    type={showDecryptedKey ? 'text' : 'password'}
                    value={showDecryptedKey && decryptedKey ? decryptedKey : undefined}
                    style={{ fontFamily: showDecryptedKey && decryptedKey ? 'monospace' : undefined }}
                  />
                  <Button
                    icon={showDecryptedKey ? <EyeInvisibleOutlined /> : <EyeOutlined />}
                    loading={keyLoading}
                    onClick={handleToggleKeyVisibility}
                    title={showDecryptedKey ? '隐藏 API Key' : '查看 API Key'}
                  />
                </Space.Compact>
              ) : (
                <Input.Password
                  placeholder="输入 API Key"
                  autoComplete="off"
                />
              )}
            </Form.Item>
          </div>
          <div className="form-field-enter">
            <Form.Item name="endpoint" label="自定义 Endpoint">
              <Input placeholder="可选,覆盖供应商默认 Endpoint URL" />
            </Form.Item>
          </div>
        </div>

        {/* Section 3: 模型参数 */}
        <div className="form-section">
          <div className="form-section-header">
            <span className="section-badge">{SECTION_BADGES[2]}</span>
            <h5>模型参数</h5>
            <span className="section-hint">选择模型并配置调用参数</span>
          </div>
          <div className="form-field-enter">
            <Form.Item
              name="model_name"
              label="模型名称"
              rules={[{ required: true, message: '请选择或输入模型名称' }]}
              extra={selectedProvider ? `${selectedProvider.display_name} 支持的模型列表已加载` : '请先选择供应商'}
            >
              {modelLoading ? (
                <div className="field-skeleton" />
              ) : (
                <AutoComplete
                  placeholder="选择或输入模型名称"
                  options={modelOptions}
                  filterOption={(inputValue, option) =>
                    option!.value.toUpperCase().includes(inputValue.toUpperCase())
                  }
                  allowClear
                />
              )}
            </Form.Item>
          </div>
          <div className="form-field-enter" style={{ display: 'flex', gap: 12 }}>
            <Form.Item name="temperature" label="Temperature" style={{ flex: 1 }}>
              <InputNumber min={0} max={2} step={0.1} placeholder="0.7" style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item name="max_tokens" label="Max Tokens" style={{ flex: 1 }}>
              <InputNumber min={1} max={1000000} step={100} placeholder="4096" style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item name="priority" label="优先级" style={{ flex: 1 }}>
              <InputNumber min={0} max={999} placeholder="0" style={{ width: '100%' }} />
            </Form.Item>
          </div>
          <div className="form-field-enter thinking-toggle-row">
            <Form.Item label=" " colon={false}>
              <Space>
                <Switch
                  checked={thinkingEnabled}
                  onChange={(checked) => {
                    setThinkingEnabled(checked);
                    setDirty(true);
                  }}
                />
                <span className="thinking-toggle-label">
                  <BulbOutlined /> 思考模式
                </span>
                <span className="thinking-toggle-hint">
                  {thinkingEnabled
                    ? '调用模型时注入推理参数(如 reasoning_effort),让模型展示推理过程'
                    : '模型直接返回最终答案,不展示中间推理过程'}
                </span>
              </Space>
            </Form.Item>
          </div>
        </div>
      </Form>
    </Modal>
  );
}