StrategyForm.tsx 9.3 KB
import { useEffect, useRef, useState, useCallback } from 'react';
import { Modal, Form, Input, Select, InputNumber, Switch } from 'antd';
import { useStrategyStore } from '../../stores/strategyStore';
import { useAccountStore } from '../../stores/accountStore';
import { useProviderStore } from '../../stores/providerStore';
import type { Strategy } from '../../types';

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

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

export default function StrategyForm({ open, strategy, onClose }: Props) {
  const [form] = Form.useForm();
  const { createStrategy, updateStrategy } = useStrategyStore();
  const { accounts, fetchAccounts } = useAccountStore();
  const { providers, fetchProviders } = useProviderStore();
  const isEdit = !!strategy;
  const [submitting, setSubmitting] = useState(false);
  const [dirty, setDirty] = useState(false);
  const firstFieldRef = useRef<HTMLInputElement>(null);
  const isInitialMount = useRef(true);

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

  useEffect(() => {
    if (open) {
      setDirty(false);
      isInitialMount.current = true;
      if (strategy) {
        form.setFieldsValue(strategy);
      } else {
        form.resetFields();
        form.setFieldValue('retry_enabled', false);
        form.setFieldValue('degrade_enabled', false);
        form.setFieldValue('timeout_enabled', false);
      }
      setTimeout(() => firstFieldRef.current?.focus(), 300);
    }
  }, [open, strategy, 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 handleOk = async () => {
    try {
      setSubmitting(true);
      const values = await form.validateFields();
      if (isEdit) {
        await updateStrategy(strategy!.id, values);
      } else {
        await createStrategy(values);
      }
      onClose();
    } catch {
      // validation errors shown inline
    } finally {
      setSubmitting(false);
    }
  };

  const getAccountLabel = (acctId: string) => {
    const acct = accounts.find((a) => a.id === acctId);
    if (!acct) return acctId;
    const p = providers.find((pr) => pr.id === acct.provider_id);
    return `${acct.account_name}${p ? ` (${p.display_name})` : ''}`;
  };

  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="account_id"
              label="关联账号"
              rules={[{ required: true, message: '请选择关联账号' }]}
            >
              <Select
                showSearch
                placeholder="选择关联账号"
                optionFilterProp="label"
                options={accounts.map((a) => ({
                  label: getAccountLabel(a.id),
                  value: a.id,
                  disabled: a.status !== 'active',
                }))}
              />
            </Form.Item>
          </div>
          <div className="form-field-enter">
            <Form.Item
              name="strategy_name"
              label="策略名称"
              rules={[{ required: true, message: '请输入策略名称' }]}
            >
              <Input placeholder="例如:默认策略、高可靠性策略" ref={firstFieldRef} />
            </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">重试 / 降级 / 超时 / 并发</span>
          </div>

          {/* 重试策略 */}
          <div className="form-field-enter">
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
              <Form.Item name="retry_enabled" valuePropName="checked" style={{ margin: 0 }}>
                <Switch />
              </Form.Item>
              <span style={{ fontWeight: 500, fontSize: 13 }}>重试策略</span>
              <span style={{ fontSize: 12, color: 'var(--color-text-muted)' }}>
                调用失败时自动重试
              </span>
            </div>
            <Form.Item noStyle shouldUpdate={(prev, cur) => prev.retry_enabled !== cur.retry_enabled}>
              {({ getFieldValue }) =>
                getFieldValue('retry_enabled') ? (
                  <div style={{ display: 'flex', gap: 12, marginLeft: 52, marginBottom: 12 }}>
                    <Form.Item name="retry_max_attempts" label="最大重试次数" style={{ flex: 1 }}>
                      <InputNumber min={1} max={20} placeholder="3" style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item name="retry_interval_ms" label="重试间隔(ms)" style={{ flex: 1 }}>
                      <InputNumber min={100} max={60000} step={500} placeholder="1000" style={{ width: '100%' }} />
                    </Form.Item>
                  </div>
                ) : null
              }
            </Form.Item>
          </div>

          {/* 降级策略 */}
          <div className="form-field-enter">
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
              <Form.Item name="degrade_enabled" valuePropName="checked" style={{ margin: 0 }}>
                <Switch />
              </Form.Item>
              <span style={{ fontWeight: 500, fontSize: 13 }}>降级策略</span>
              <span style={{ fontSize: 12, color: 'var(--color-text-muted)' }}>
                主账号不可用时切换备用账号
              </span>
            </div>
          </div>

          {/* 超时策略 */}
          <div className="form-field-enter">
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
              <Form.Item name="timeout_enabled" valuePropName="checked" style={{ margin: 0 }}>
                <Switch />
              </Form.Item>
              <span style={{ fontWeight: 500, fontSize: 13 }}>超时策略</span>
              <span style={{ fontSize: 12, color: 'var(--color-text-muted)' }}>
                设置请求超时时间
              </span>
            </div>
            <Form.Item noStyle shouldUpdate={(prev, cur) => prev.timeout_enabled !== cur.timeout_enabled}>
              {({ getFieldValue }) =>
                getFieldValue('timeout_enabled') ? (
                  <div style={{ display: 'flex', gap: 12, marginLeft: 52, marginBottom: 12 }}>
                    <Form.Item name="timeout_connect_ms" label="连接超时(ms)" style={{ flex: 1 }}>
                      <InputNumber min={100} max={120000} step={1000} placeholder="5000" style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item name="timeout_read_ms" label="读取超时(ms)" style={{ flex: 1 }}>
                      <InputNumber min={100} max={600000} step={1000} placeholder="30000" style={{ width: '100%' }} />
                    </Form.Item>
                  </div>
                ) : null
              }
            </Form.Item>
          </div>

          {/* 并发控制 */}
          <div className="form-field-enter" style={{ marginTop: 8 }}>
            <Form.Item
              name="max_concurrency"
              label="并发限制"
              tooltip="一次最多同时处理多少条模型请求,超出部分排队等待"
              extra="默认 5,设置为空表示不限制"
            >
              <InputNumber
                min={1}
                max={100}
                placeholder="5"
                style={{ width: 160 }}
              />
            </Form.Item>
          </div>
        </div>
      </Form>
    </Modal>
  );
}