AgentEditorPage.tsx 10.9 KB
import { useMemo, useState } from 'react';
import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';

import { Button, FormItem, Input, Select, StatePlaceholder, Switch, Textarea } from '../../../packages/ui/src';
import {
  createAgentRecord,
  getAgentDetail,
  getAgentEditorFixture,
  type AgentDraftPayload,
  type AgentEditorScenario,
} from '../../../packages/contracts/agent-editor-mock';
import { findSavedAgent, upsertSavedAgent } from './agentLocalStore';
import { buildAgentListSearch, readAgentListRouteState } from './agentRouteState';

interface AgentFormState {
  name: string;
  positionIds: string[];
  userId?: string;
  description: string;
  skillIds: string[];
  status: 'enable' | 'disable';
}

function buildInitialFormState(agentId?: string): AgentFormState {
  const detail = findSavedAgent(agentId) ?? getAgentDetail(agentId);
  if (!detail) {
    return {
      name: '',
      positionIds: [],
      userId: undefined,
      description: '',
      skillIds: [],
      status: 'disable',
    };
  }

  return {
    name: detail.name,
    positionIds: detail.positions.map((position) => position.id),
    userId: detail.employee_id,
    description: detail.description,
    skillIds: detail.skill_ids,
    status: detail.status,
  };
}

export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) {
  const navigate = useNavigate();
  const location = useLocation();
  const params = useParams();
  const [searchParams] = useSearchParams();
  const [form, setForm] = useState<AgentFormState>(() => buildInitialFormState(params.agentId));
  const [errors, setErrors] = useState<Partial<Record<keyof AgentFormState, string>>>({});
  const routeState = readAgentListRouteState(searchParams);
  const scenario = (searchParams.get('scenario') ?? 'normal') as AgentEditorScenario;
  const fixture = useMemo(
    () => getAgentEditorFixture({ agentId: params.agentId, mode, scenario, positionIds: form.positionIds }),
    [form.positionIds, mode, params.agentId, scenario],
  );
  const detail = findSavedAgent(params.agentId) ?? getAgentDetail(params.agentId);
  const isManager = detail?.is_manager ?? false;
  const fieldWidthClassName = 'w-full max-w-[450px]';

  if (fixture.detailLoading) {
    return <StatePlaceholder state="empty" title="加载中" description="正在加载 Agent 详情" />;
  }

  if (mode === 'edit' && !detail) {
    return <StatePlaceholder state="error" title="Agent不存在" description="当前 Agent 详情无法加载" />;
  }

  const goBackToList = (restoreDetail: boolean) => {
    const nextSearch = buildAgentListSearch({
      ...routeState,
      detail: restoreDetail ? routeState.detail : undefined,
    });
    navigate(`/agents${nextSearch}`);
  };

  const validate = () => {
    const nextErrors: Partial<Record<keyof AgentFormState, string>> = {};
    if (!form.name.trim()) nextErrors.name = '请输入 Agent 名称';
    if (form.positionIds.length === 0) nextErrors.positionIds = '请选择所属岗位';
    if (!form.userId) nextErrors.userId = '请选择托管企微员工';
    if (!form.description.trim()) nextErrors.description = '请输入 Agent 描述';
    if (!isManager && form.skillIds.length === 0) nextErrors.skillIds = '请至少绑定一个 Skill';
    setErrors(nextErrors);
    return Object.keys(nextErrors).length === 0;
  };

  const handleSave = () => {
    if (!validate()) {
      return;
    }

    if (fixture.saveError) {
      return;
    }

    const payload: AgentDraftPayload = {
      name: form.name.trim(),
      positionIds: form.positionIds,
      userId: form.userId,
      description: form.description.trim(),
      skillIds: form.skillIds,
      status: form.status,
    };
    const savedDetail = mode === 'create'
      ? createAgentRecord(payload)
      : {
        ...detail!,
        name: isManager ? detail!.name : payload.name,
        positions: isManager ? detail!.positions : fixture.positions.filter((position) => payload.positionIds.includes(position.id)),
        employee_id: isManager ? detail!.employee_id : payload.userId ?? '',
        employee_name: isManager ? detail!.employee_name : fixture.employees.find((employee) => employee.id === payload.userId)?.name ?? '',
        description: payload.description,
        skill_ids: payload.skillIds,
        status: isManager ? detail!.status : payload.status,
      };
    upsertSavedAgent(savedDetail);
    const nextDetailId = String(savedDetail.agent_id);

    navigate(
      `/agents${buildAgentListSearch({
        ...routeState,
        detail: mode === 'edit' && routeState.detail ? nextDetailId : undefined,
        refreshToken: String(Date.now()),
      })}`,
    );
  };

  const title = mode === 'create' ? '新建Agent' : '编辑Agent';
  const employeeOptions = fixture.employees.map((employee) => ({
    label: employee.status === 'mounted' ? `${employee.name}(已挂载Agent)` : employee.name,
    value: employee.id,
    disabled: employee.status === 'mounted',
  }));

  return (
    <section className="grid gap-6">
      <header className="flex items-center justify-between gap-6 rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-6">
        <div className="flex items-center gap-4">
          <Button variant="outline" onClick={() => goBackToList(Boolean(routeState.detail && mode === 'edit'))}>返回</Button>
          <div>
            <h2 className="m-0 text-2xl leading-[var(--gl-line-height-xl)]">{title}</h2>
            <p className="m-0 mt-1 text-sm text-[var(--gl-color-text-secondary)]">
              {mode === 'create' ? '创建新的岗位 Agent 配置' : '编辑已存在的 Agent 配置'}
            </p>
          </div>
        </div>
        <div className="flex items-center gap-3">
          <Button variant="outline" onClick={() => goBackToList(Boolean(routeState.detail && mode === 'edit'))}>取消</Button>
          <Button variant="primary" loading={fixture.saveLoading} onClick={handleSave}>保存</Button>
        </div>
      </header>

      {fixture.saveError ? (
        <StatePlaceholder
          state="error"
          title="保存失败,请重试"
          description="当前变更尚未保存成功,请检查表单后重新提交。"
        />
      ) : null}

      <div className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-10">
        <div className="mx-auto grid max-w-[760px] gap-6">
          <FormItem label="Agent名称" layout="horizontal" required error={errors.name}>
            <span className="grid gap-2">
              <Input
                aria-label="Agent名称"
                className={fieldWidthClassName}
                disabled={isManager}
                maxLength={50}
                showCount
                value={form.name}
                onChange={(value) => setForm((current) => ({ ...current, name: value }))}
              />
            </span>
          </FormItem>

          <FormItem label="所属岗位" layout="horizontal" required error={errors.positionIds}>
            <span className="grid gap-2">
              {fixture.positionsError ? (
                <StatePlaceholder state="error" title="岗位选项加载失败" description="请重试加载岗位选项" primaryAction={<Button size="small">重试</Button>} />
              ) : (
                <Select
                  aria-label="所属岗位"
                  className={fieldWidthClassName}
                  disabled={isManager}  
                  multiple
                  options={fixture.positions.map((position) => ({ label: position.name, value: position.id }))}
                  value={form.positionIds}
                  onChange={(value) => {
                    const nextValue = Array.isArray(value) ? value : [];
                    setForm((current) => ({
                      ...current,
                      positionIds: nextValue,
                      userId: nextValue.some((positionId) => current.positionIds.includes(positionId)) ? current.userId : undefined,
                    }));
                  }}
                />
              )}
            </span>
          </FormItem>

          <FormItem
            label="托管企微员工"
            layout="horizontal"
            required
            error={errors.userId}
            tips={!isManager && form.positionIds.length === 0 ? '请先选择所属岗位' : undefined}
          >
            <span className="grid gap-2">
              {fixture.employeesError ? (
                <StatePlaceholder state="error" title="托管企微员工加载失败" description="请重试加载托管企微员工选项" primaryAction={<Button size="small">重试</Button>} />
              ) : (
                <Select
                  aria-label="托管企微员工"
                  className={fieldWidthClassName}
                  disabled={isManager || form.positionIds.length === 0}
                  options={employeeOptions}
                  placeholder={form.positionIds.length === 0 ? '请先选择所属岗位' : '请选择托管企微员工'}
                  value={form.userId}
                  onChange={(value) => setForm((current) => ({ ...current, userId: typeof value === 'string' ? value : undefined }))}
                />
              )}
            </span>
          </FormItem>

          <FormItem label="Agent描述" layout="horizontal" required error={errors.description}>
            <Textarea
              aria-label="Agent描述"
              className={fieldWidthClassName}
              maxLength={200}
              rows={5}
              showCount
              value={form.description}
              onChange={(value) => setForm((current) => ({ ...current, description: value }))}
            />
          </FormItem>

          <FormItem label="绑定Skill" layout="horizontal" required={!isManager} error={errors.skillIds}>
            <span className="grid gap-2">
              {fixture.skillsError ? (
                <StatePlaceholder state="error" title="Skill 选项加载失败" description="请重试加载 Skill 选项" primaryAction={<Button size="small">重试</Button>} />
              ) : (
                <Select
                  aria-label="绑定Skill"
                  className={fieldWidthClassName}
                  multiple
                  options={fixture.skills.map((skill) => ({ label: skill.name, value: skill.id }))}
                  value={form.skillIds}
                  onChange={(value) => setForm((current) => ({ ...current, skillIds: Array.isArray(value) ? value : [] }))}
                />
              )}
            </span>
          </FormItem>

          <FormItem label="状态" layout="horizontal" required>
            <Switch
              aria-label="状态"
              checked={form.status === 'enable'}
              disabled={isManager}
              onChange={(checked) => setForm((current) => ({ ...current, status: checked ? 'enable' : 'disable' }))}
            />
          </FormItem>
        </div>
      </div>
    </section>
  );
}