forms.tsx 56.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
/**
 * 每种节点一张配置表单(右侧面板的「设置」页)。
 * 引用本体里的东西(对象、指标、函数、动作、角色……)一律用选择器;引用上游数据用 ValueInput / RefPicker;
 * 条件用条件组编辑器;公式用公式编辑器(有补全)。表单按类型生成(函数的输入、动作的参数、对象的属性都带类型)。
 */
import { ChevronDown, ChevronRight, Plus, Trash2 } from "lucide-react";
import { useEffect, useMemo, useState, type ReactNode } from "react";
import { Select } from "@/components/kit";
import { Field, Segmented } from "@/components/ui";
import { RefMulti, RefSelect, TimeInput, useRefOptions } from "@/features/ontology/RefSelect";
import { JsonBox } from "@/features/ontology/common";
import { onto, type CapDef, type DataSchema, type FlowLink, type FlowOutput, type FunctionBrief, type SopBrief, type SopParam,
  type SopSpec, type SopStep } from "@/lib/onto";
import { loadFailed } from "@/store/useAppStore";
import { cn } from "@/lib/utils";
import { ConditionEditor } from "./ConditionEditor";
import { ExprInput, RefPicker, TemplateText, TYPE_TAG, useScope, ValueInput, WithExtra } from "./data";
import { findStep } from "./model";

export type Patch = (p: Partial<SopStep>) => void;
export interface FormProps {
  step: SopStep; patch: Patch; disabled: boolean; spec: SopSpec; defId: string;
  /** 所有步骤的产出(含循环体里的 item)—— 有的表单要看自己或循环的结构 */
  allOutputs: FlowOutput[];
}

const DT: Record<string, string> = { number: "number", integer: "number", decimal: "number", float: "number", boolean: "boolean", date: "date", datetime: "date" };
const asType = (t?: string) => DT[String(t || "").toLowerCase()] || "string";

/** 对象的属性 → 条件编辑器 / 写入表单用的字段表。 */
function useObjectFields(ot: string, writableOnly = false): DataSchema[] {
  const opts = useRefOptions(ot ? (writableOnly ? "property:object_type" : "conditions:object_type") : undefined, ot);
  return useMemo(() => (opts || []).map((o) => ({ name: String(o.value), label: o.label, type: asType(o.type),
    options: o.enum && o.enum.length ? o.enum : undefined })), [opts]);
}

/** 一组「名字 → 值」:名字和类型来自定义(函数输入、动作参数、子流程参数),值可以是常量、引用或公式。 */
export function MapInputs({ rows, value, onChange, disabled, empty = "不需要填" }: {
  rows: { key: string; label: string; type?: string; options?: string[]; required?: boolean; object_type?: string; hint?: string }[];
  value: Record<string, any> | undefined; onChange: (v: Record<string, any>) => void; disabled: boolean; empty?: string;
}) {
  const obj = value || {};
  if (!rows.length) return <p className="text-caption text-muted">{empty}</p>;
  return (
    <div className="space-y-2">
      {rows.map((r) => (
        <div key={r.key} className="grid grid-cols-[6rem_minmax(0,1fr)] items-start gap-2">
          <div className="min-w-0 pt-1.5">
            <p className="truncate text-label" title={`${r.label}(${r.key})`}>{r.label}{r.required && <span className="text-bad"> *</span>}</p>
            <p className="truncate text-[11px] text-muted" title={r.hint}>{TYPE_TAG[r.type || "string"] || r.type}{r.hint ? ` · ${r.hint}` : ""}</p>
          </div>
          <ValueInput value={obj[r.key]} disabled={disabled} type={r.type} options={r.options} object_type={r.object_type}
                      onChange={(v) => {
                        const next = { ...obj };
                        if (v === "" || v === undefined) delete next[r.key]; else next[r.key] = v;
                        onChange(next);
                      }} />
        </div>
      ))}
    </div>
  );
}

function Who({ step, patch, disabled, label }: { step: SopStep; patch: Patch; disabled: boolean; label: string }) {
  const [kind, setKind] = useState<"role" | "user">(step.assignee ? "user" : "role");
  return (
    <Field label={label} required>
      <div className="flex gap-1.5">
        <Select className="input h-8 w-24 shrink-0" disabled={disabled} value={kind}
                onChange={(e) => { setKind(e.target.value as "role" | "user"); patch({ role: "", assignee: "" }); }}>
          <option value="role">角色</option><option value="user">指定的人</option>
        </Select>
        <RefSelect className="flex-1" refKind={kind} value={kind === "user" ? step.assignee : step.role} disabled={disabled}
                   allowCustom={false} onChange={(v) => patch(kind === "user" ? { assignee: String(v || ""), role: "" } : { role: String(v || ""), assignee: "" })} />
      </div>
    </Field>
  );
}

function Section({ title, children, right, defaultOpen = true }: { title: string; children: ReactNode; right?: ReactNode; defaultOpen?: boolean }) {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div className="rounded-lg border border-line">
      <div className="flex items-center gap-1 px-3 py-2">
        <button className="flex min-w-0 flex-1 items-center gap-1 text-left text-label font-medium" onClick={() => setOpen((o) => !o)}>
          {open ? <ChevronDown className="h-3.5 w-3.5 text-muted" /> : <ChevronRight className="h-3.5 w-3.5 text-muted" />}{title}
        </button>
        {right}
      </div>
      {open && <div className="space-y-3 border-t border-line px-3 py-3">{children}</div>}
    </div>
  );
}

// ---------------------------------------------------------------- 查数据
function IncludeEditor({ ot, value, onChange, disabled, depth }: {
  ot: string; value: any[]; onChange: (v: any[]) => void; disabled: boolean; depth: number;
}) {
  const [links, setLinks] = useState<FlowLink[] | null>(null);
  useEffect(() => {
    if (!ot) { setLinks([]); return; }
    void onto.sopLinks(ot).then(setLinks).catch(() => setLinks([]));
  }, [ot]);
  const set = (i: number, p: any) => onChange(value.map((x, j) => (j === i ? { ...x, ...p } : x)));
  return (
    <div className="space-y-2">
      {value.length === 0 && <p className="text-caption text-muted">只查{ot || "这类对象"}本身。要一起拿回关联的数据(明细行、关联单据、所属对象),点下面添加。</p>}
      {value.map((inc, i) => {
        const lk = (links || []).find((l) => [l.link, l.label, l.object_type].includes(inc.link));
        const fields = lk?.fields.filter((f) => !["key", "label"].includes(String(f.name))) || [];
        return (
          <div key={i} className="space-y-2 rounded-lg border border-line bg-ink/[0.015] p-2.5">
            <div className="flex items-center gap-1.5">
              <Select className="input h-8 min-w-0 flex-1" disabled={disabled} value={inc.link}
                      onChange={(e) => { const l = (links || []).find((x) => x.link === e.target.value); set(i, { link: e.target.value, as: inc.as || l?.label || "", mode: l?.single ? "one" : "list", where: null, fields: [] }); }}>
                <option value="">{links === null ? "加载中…" : links.length ? "沿哪条关系" : "这类对象没有关系"}</option>
                {(links || []).map((l) => <option key={`${l.link}-${l.direction}`} value={l.link}>{l.label} → {l.object_type}{l.single ? "(一个)" : "(多个)"}</option>)}
              </Select>
              {!disabled && <button className="btn btn-ghost btn-sm px-1.5" onClick={() => onChange(value.filter((_, j) => j !== i))}><Trash2 className="h-3.5 w-3.5" /></button>}
            </div>
            {inc.link && (
              <>
                <div className="grid grid-cols-2 gap-2">
                  <Field label="放在哪个字段"><input className="input h-8" disabled={disabled} value={inc.as} onChange={(e) => set(i, { as: e.target.value })} /></Field>
                  <Field label="取几个">
                    <Select className="input h-8" disabled={disabled} value={inc.mode} onChange={(e) => set(i, { mode: e.target.value })}>
                      <option value="list">多个(列表)</option><option value="one">一个</option>
                    </Select>
                  </Field>
                </div>
                <Field label="只要满足条件的"><ConditionEditor value={inc.where} fields={fields} disabled={disabled} emptyHint="全部关联的都要" onChange={(v) => set(i, { where: v })} /></Field>
                {inc.mode === "list" && (
                  <Field label="汇总" hint="算在上一层对象上,如「用料行条数」「缺件数量合计」">
                    <div className="space-y-1.5">
                      {(inc.aggs || []).map((a: any, j: number) => (
                        <div key={j} className="flex items-center gap-1">
                          <Select className="input h-8 w-20 shrink-0" disabled={disabled} value={a.fn}
                                  onChange={(e) => set(i, { aggs: inc.aggs.map((x: any, k: number) => (k === j ? { ...x, fn: e.target.value } : x)) })}>
                            <option value="count">条数</option><option value="sum">合计</option><option value="avg">平均</option>
                            <option value="min">最小</option><option value="max">最大</option>
                          </Select>
                          {a.fn !== "count" && (
                            <Select className="input h-8 min-w-0 flex-1" disabled={disabled} value={a.field}
                                    onChange={(e) => set(i, { aggs: inc.aggs.map((x: any, k: number) => (k === j ? { ...x, field: e.target.value } : x)) })}>
                              <option value="">哪个字段</option>
                              {fields.filter((f) => f.type === "number").map((f) => <option key={f.name} value={f.name}>{f.label}</option>)}
                            </Select>
                          )}
                          <input className="input h-8 w-28 shrink-0" disabled={disabled} placeholder="叫什么" value={a.as}
                                 onChange={(e) => set(i, { aggs: inc.aggs.map((x: any, k: number) => (k === j ? { ...x, as: e.target.value } : x)) })} />
                          {!disabled && <button className="btn btn-ghost btn-sm px-1.5" onClick={() => set(i, { aggs: inc.aggs.filter((_: any, k: number) => k !== j) })}><Trash2 className="h-3.5 w-3.5" /></button>}
                        </div>
                      ))}
                      {!disabled && <button className="btn btn-sm" onClick={() => set(i, { aggs: [...(inc.aggs || []), { fn: "count", field: "", as: `${inc.as || "关联"}条数` }] })}><Plus className="h-3.5 w-3.5" />加一个汇总</button>}
                    </div>
                  </Field>
                )}
                {depth < 3 && lk && (
                  <Field label={`再从「${lk.object_type}」带出`}>
                    <IncludeEditor ot={lk.object_type} value={inc.include || []} disabled={disabled} depth={depth + 1} onChange={(v) => set(i, { include: v })} />
                  </Field>
                )}
              </>
            )}
          </div>
        );
      })}
      {!disabled && ot && <button className="btn btn-sm" onClick={() => onChange([...value, { link: "", as: "", mode: "list", where: null, fields: [], aggs: [], include: [] }])}><Plus className="h-3.5 w-3.5" />带出关联对象</button>}
    </div>
  );
}

function QueryForm({ step, patch, disabled }: FormProps) {
  const fields = useObjectFields(step.object_type || "");
  return (
    <>
      <Field label="查哪类对象" required>
        <RefSelect refKind="object_type" value={step.object_type} disabled={disabled} allowCustom={false}
                   onChange={(v) => patch({ object_type: String(v || ""), where: null, fields: [], include: [], sort: [] })} />
      </Field>
      <Field label="查几个">
        <Segmented value={step.mode || "list"} onChange={(v) => !disabled && patch({ mode: v })}
                   options={[{ key: "one", label: "一个(如 按单号查这张单)" }, { key: "list", label: "一批(列表)" }]} />
      </Field>
      <Field label="条件"><ConditionEditor value={step.where} fields={fields} disabled={disabled || !step.object_type} emptyHint="不加条件" onChange={(v) => patch({ where: v })} /></Field>
      <Section title="带出关联对象(一次查多张表)">
        <IncludeEditor ot={step.object_type || ""} value={step.include || []} disabled={disabled} depth={1} onChange={(v) => patch({ include: v })} />
      </Section>
      <Section title="字段、排序与条数" defaultOpen={false}>
        <Field label="只要这些属性" hint="不选就是全部"><RefMulti refKind="conditions:object_type" of={step.object_type} value={step.fields} disabled={disabled} onChange={(v) => patch({ fields: v })} /></Field>
        <div className="grid grid-cols-[minmax(0,1fr)_6.5rem_5rem] gap-2">
          <Field label="排序">
            <Select className="input h-8" disabled={disabled} value={step.sort?.[0]?.property || ""}
                    onChange={(e) => patch({ sort: e.target.value ? [{ property: e.target.value, dir: step.sort?.[0]?.dir || "asc" }] : [] })}>
              <option value="">不排序</option>{fields.map((f) => <option key={f.name} value={f.name}>{f.label}</option>)}
            </Select>
          </Field>
          <Field label="顺序">
            <Select className="input h-8" disabled={disabled || !step.sort?.[0]} value={step.sort?.[0]?.dir || "asc"}
                    onChange={(e) => patch({ sort: [{ property: step.sort[0].property, dir: e.target.value }] })}>
              <option value="asc">从小到大</option><option value="desc">从大到小</option>
            </Select>
          </Field>
          <Field label="最多"><input className="input h-8" type="number" min={1} max={500} disabled={disabled || step.mode === "one"} value={step.limit ?? 50} onChange={(e) => patch({ limit: Number(e.target.value) || 50 })} /></Field>
        </div>
      </Section>
    </>
  );
}

// ---------------------------------------------------------------- 调用函数
function RowFilter({ step, patch, disabled, allOutputs }: FormProps) {
  const own = allOutputs.find((o) => o.id === step.id);
  const items = own?.schema?.fields?.find((f) => f.name === "items");
  const itemOut: FlowOutput[] = items?.items ? [{ id: `${step.id}:row`, var: "item", title: "每一行", kind: "item", scope: "", schema: items.items }] : [];
  return (
    <Field label="只留下满足条件的行" hint="条件左边选「每一行」里的字段">
      <WithExtra extra={itemOut}><ConditionEditor value={step.filter} disabled={disabled} emptyHint="全部留下" onChange={(v) => patch({ filter: v })} /></WithExtra>
    </Field>
  );
}

function MetricForm(props: FormProps) {
  const { step, patch, disabled } = props;
  const a = step.args || {};
  const set = (p: any) => patch({ args: { ...a, ...p } });
  const dims = useRefOptions(a.metric ? "filters:metric" : undefined, a.metric || "") || [];
  return (
    <>
      <Field label="取哪个指标" required>
        <RefSelect refKind="metric" value={a.metric} disabled={disabled} allowCustom={false} onChange={(v) => patch({ args: { metric: String(v || "") }, filter: null })} />
      </Field>
      <Field label="按什么拆开" hint="不选就只有一个总数"><RefMulti refKind="dimension:metric" of={a.metric} value={a.dimensions} disabled={disabled} onChange={(v) => set({ dimensions: v })} /></Field>
      <Field label="统计时间"><TimeInput value={a.time} disabled={disabled} onChange={(v) => set({ time: v })} /></Field>
      {dims.length > 0 && (
        <Field label="只统计哪些">
          <MapInputs rows={dims.map((d) => ({ key: String(d.value), label: d.label }))} value={a.filters} disabled={disabled} onChange={(v) => set({ filters: v })} />
        </Field>
      )}
      <Field label="只取某一个对象的值"><ValueInput value={a.object_key} disabled={disabled} placeholder="对象主键,不填就是全部" onChange={(v) => set({ object_key: v })} /></Field>
      {(a.dimensions || []).length > 0 && <RowFilter {...props} />}
    </>
  );
}

function FnEvalForm({ step, patch, disabled }: FormProps) {
  const a = step.args || {};
  const inputs = useRefOptions(a.name ? "vars:name" : undefined, a.name || "") || [];
  return (
    <>
      <Field label="调用哪个函数" required hint="规则、决策表、统计周期、聚合、模型推理、AI 分析都在这里">
        <RefSelect refKind="function" value={a.name} disabled={disabled} allowCustom={false} onChange={(v) => patch({ args: { name: String(v || ""), args: {} } })} />
      </Field>
      <Field label="输入">
        <MapInputs rows={inputs.map((o: any) => ({ key: String(o.value), label: o.label, type: o.type, required: o.required, options: o.options?.length ? o.options : undefined,
          object_type: o.object_type, hint: o.hint }))}
                   value={a.args} disabled={disabled} empty={a.name ? "这个函数不需要输入" : "先选函数"}
                   onChange={(v) => patch({ args: { ...a, args: v } })} />
      </Field>
    </>
  );
}

const SCHEMA_TYPE: Record<string, string> = { integer: "number", number: "number", boolean: "boolean", array: "list", object: "object" };

function SysFnForm(props: FormProps) {
  const { step, patch, disabled } = props;
  const [fns, setFns] = useState<FunctionBrief[]>([]);
  useEffect(() => { void onto.catalog().then((c) => setFns(c.functions)).catch((e) => { setFns([]); loadFailed(e); }); }, []);
  const fn = fns.find((f) => f.name === step.function);
  const props_ = (fn?.input_schema?.properties || {}) as Record<string, any>;
  const req: string[] = fn?.input_schema?.required || [];
  const a = step.args || {};
  return (
    <>
      <Field label="函数" required>
        <Select className="input h-8" disabled={disabled} value={step.function || ""} onChange={(e) => patch({ function: e.target.value, args: {} })}>
          <option value="">请选择</option>
          {fns.map((f) => <option key={f.name} value={f.name}>{f.title}({f.name})</option>)}
        </Select>
        {fn && <p className="hint">{fn.description}</p>}
      </Field>
      {Object.entries(props_).map(([k, p]) => {
        const ref = String(p["x-ref"] || "");
        const label = String(p.description || k).split("(")[0].split(",")[0];
        const type = Array.isArray(p.type) ? "string" : SCHEMA_TYPE[p.type] || "string";
        return (
          <Field key={k} label={label} required={req.includes(k)}>
            {ref && !ref.includes(":") && !["time", "concept"].includes(ref)
              ? <RefSelect refKind={ref} value={a[k]} disabled={disabled} onChange={(v) => patch({ args: { ...a, [k]: v } })} />
              : (type === "list" || type === "object") && !(typeof a[k] === "string" && a[k].startsWith("$"))
                ? <JsonOrRef value={a[k]} disabled={disabled} type={type} onChange={(v) => patch({ args: { ...a, [k]: v } })} />
                : <ValueInput value={a[k]} disabled={disabled} type={type} options={p.enum} onChange={(v) => patch({ args: { ...a, [k]: v } })} />}
          </Field>
        );
      })}
      {step.function && <RowFilter {...props} />}
    </>
  );
}

/** 结构化参数(列表 / 对象):直接写 JSON(里面的值可以写 $引用),或整个引用上游的一份数据。 */
function JsonOrRef({ value, onChange, disabled, type }: { value: any; onChange: (v: any) => void; disabled: boolean; type: string }) {
  const [ref, setRef] = useState(false);
  if (ref) return <div className="space-y-1"><ValueInput value={value} type={type} disabled={disabled} onChange={onChange} /><button className="text-caption text-brand hover:underline" onClick={() => setRef(false)}>改为直接填写</button></div>;
  return (
    <div className="space-y-1">
      <JsonBox value={value ?? (type === "list" ? [] : {})} small disabled={disabled} onChange={onChange} />
      {!disabled && <button className="text-caption text-brand hover:underline" onClick={() => setRef(true)}>引用上游的数据</button>}
    </div>
  );
}

// ---------------------------------------------------------------- 计算
function ComputeForm({ step, patch, disabled }: FormProps) {
  const sc = useScope();
  const rows: any[] = step.assign || [];
  const set = (i: number, p: any) => patch({ assign: rows.map((r, j) => (j === i ? { ...r, ...p } : r)) });
  const [help, setHelp] = useState(false);
  return (
    <>
      <p className="rounded-md bg-ink/[0.03] px-2.5 py-2 text-caption text-muted">
        每一行算出一个字段,后面的步骤用「本节点 · 字段名」引用;下面的公式可以用上面算好的字段。公式里直接写变量名(不加 $),按 Ctrl+空格 出提示。
      </p>
      {rows.map((r, i) => (
        <div key={i} className="space-y-1.5 rounded-lg border border-line p-2.5">
          <div className="flex items-center gap-1.5">
            <input className="input h-8 w-28 font-mono text-label" disabled={disabled} value={r.name} placeholder="字段名" onChange={(e) => set(i, { name: e.target.value.trim() })} />
            <input className="input h-8 min-w-0 flex-1" disabled={disabled} value={r.label} placeholder="中文名(可不填)" onChange={(e) => set(i, { label: e.target.value })} />
            <Select className="input h-8 w-20 shrink-0" disabled={disabled} value={r.type || "any"} onChange={(e) => set(i, { type: e.target.value })}>
              {["number", "string", "boolean", "date", "list", "object", "any"].map((t) => <option key={t} value={t}>{TYPE_TAG[t]}</option>)}
            </Select>
            {!disabled && <button className="btn btn-ghost btn-sm px-1.5" onClick={() => patch({ assign: rows.filter((_, j) => j !== i) })}><Trash2 className="h-3.5 w-3.5" /></button>}
          </div>
          <ExprInput value={r.expr || ""} disabled={disabled} onChange={(v) => set(i, { expr: v })} />
        </div>
      ))}
      {!disabled && <button className="btn btn-sm" onClick={() => patch({ assign: [...rows, { name: `x${rows.length + 1}`, label: "", type: "number", expr: "" }] })}><Plus className="h-3.5 w-3.5" />再算一个</button>}
      <button className="text-caption text-brand hover:underline" onClick={() => setHelp((h) => !h)}>{help ? "收起" : "能用哪些函数?"}</button>
      {help && (
        <div className="max-h-56 overflow-auto rounded-md border border-line text-caption">
          {(sc.meta?.list_functions || []).map((f) => (
            <div key={f.name} className="grid grid-cols-[11rem_1fr] gap-2 border-b border-line/60 px-2 py-1 last:border-0">
              <code className="truncate font-mono text-brand" title={f.sig}>{f.sig}</code><span className="text-muted">{f.desc}</span>
            </div>
          ))}
        </div>
      )}
    </>
  );
}

// ---------------------------------------------------------------- 条件
function DecisionForm({ step, patch, disabled }: FormProps) {
  const bs: any[] = step.branches || [];
  const set = (i: number, p: any) => patch({ branches: bs.map((b, j) => (j === i ? { ...b, ...p } : b)) });
  return (
    <>
      {bs.map((b, i) => (
        <div key={i} className="space-y-2 rounded-lg border border-warn/30 bg-warn/[0.03] p-2.5">
          <div className="flex items-center gap-1.5">
            <span className="shrink-0 text-label font-medium text-warn">如果</span>
            <input className="input h-8 min-w-0 flex-1" disabled={disabled} value={b.label} placeholder="给这种情况起个名字(显示在连线上)" onChange={(e) => set(i, { label: e.target.value })} />
            {!disabled && bs.length > 1 && <button className="btn btn-ghost btn-sm px-1.5" title="删掉这种情况" onClick={() => patch({ branches: bs.filter((_, j) => j !== i) })}><Trash2 className="h-3.5 w-3.5" /></button>}
          </div>
          <ConditionEditor value={b.cond ?? (b.when && b.when !== "False" ? { expr: b.when } : null)} disabled={disabled}
                           emptyHint="还没写条件(没有条件的分支永远不会走到)" onChange={(v) => set(i, { cond: v, when: "" })} />
        </div>
      ))}
      {!disabled && <button className="btn btn-sm" onClick={() => patch({ branches: [...bs, { label: `情况 ${bs.length + 1}`, cond: null, next: "" }] })}><Plus className="h-3.5 w-3.5" />再加一种情况</button>}
      <p className="rounded-md bg-ink/[0.03] px-2.5 py-2 text-caption text-muted">从上往下判断,走第一个满足的;都不满足走「否则」。每种情况在画布上有一个出口,拖一条线到下一步。</p>
    </>
  );
}

// ---------------------------------------------------------------- 循环
function ForeachForm({ step, patch, disabled, allOutputs }: FormProps) {
  const sc = useScope();
  const item = allOutputs.filter((o) => o.scope === step.id && o.kind === "item");
  const bodyOuts = (step.body?.steps || []).filter((b: SopStep) => b.output);
  return (
    <>
      <Field label="对哪份数据逐条处理" required>
        <RefPicker value={step.items || ""} want="list" disabled={disabled} placeholder="选一份多行数据(列表)" onChange={(v) => patch({ items: v, filter: null })} />
      </Field>
      <Field label="只处理满足条件的">
        <ScopeExtra extra={item}><ConditionEditor value={step.filter} disabled={disabled} emptyHint="每一条都处理" onChange={(v) => patch({ filter: v })} /></ScopeExtra>
      </Field>
      <div className="grid grid-cols-2 gap-2">
        <Field label="一次最多处理" hint={`上限 ${sc.meta?.foreach_limit ?? 200}`}>
          <input className="input h-8" type="number" min={1} max={sc.meta?.foreach_limit ?? 200} disabled={disabled} value={step.limit ?? 20} onChange={(e) => patch({ limit: Number(e.target.value) || 20 })} />
        </Field>
        <Field label="某一条失败了">
          <Select className="input h-8" disabled={disabled} value={step.on_item_error || "continue"} onChange={(e) => patch({ on_item_error: e.target.value })}>
            <option value="continue">跳过,接着处理下一条</option><option value="stop">停下,后面的不处理</option>
          </Select>
        </Field>
      </div>
      <Field label="收集每一条的结果" hint="选循环里某一步的结果,循环结束后得到一个列表(本节点 · 每一条的结果)">
        <Select className="input h-8" disabled={disabled} value={step.collect || ""} onChange={(e) => patch({ collect: e.target.value })}>
          <option value="">不收集</option>
          {bodyOuts.map((b: SopStep) => <option key={b.id} value={b.output}>{b.title}</option>)}
        </Select>
      </Field>
      <p className="rounded-md bg-ink/[0.03] px-2.5 py-2 text-caption text-muted">每一条要做什么,在画布上这个循环框里加节点、连线。循环里用「循环 · 当前这一条」引用这一条的数据。</p>
    </>
  );
}

function ScopeExtra({ extra, children }: { extra: FlowOutput[]; children: ReactNode }) {
  return <WithExtra extra={extra}>{children}</WithExtra>;
}

// ---------------------------------------------------------------- AI
function OutputFields({ value, onChange, disabled, withValue }: {
  value: any[]; onChange: (v: any[]) => void; disabled: boolean; withValue?: boolean;
}) {
  const set = (i: number, p: any) => onChange(value.map((x, j) => (j === i ? { ...x, ...p } : x)));
  return (
    <div className="space-y-1.5">
      {value.map((f, i) => (
        <div key={i} className="space-y-1.5 rounded-md border border-line p-2">
          <div className="flex items-center gap-1.5">
            <input className="input h-8 w-28 font-mono text-label" disabled={disabled} value={f.name} placeholder="英文名" onChange={(e) => set(i, { name: e.target.value.trim() })} />
            <input className="input h-8 min-w-0 flex-1" disabled={disabled} value={f.label} placeholder="中文名" onChange={(e) => set(i, { label: e.target.value })} />
            {!withValue && (
              <Select className="input h-8 w-20 shrink-0" disabled={disabled} value={f.type || "string"} onChange={(e) => set(i, { type: e.target.value })}>
                {["string", "number", "boolean", "date", "list"].map((t) => <option key={t} value={t}>{TYPE_TAG[t]}</option>)}
              </Select>
            )}
            {!disabled && <button className="btn btn-ghost btn-sm px-1.5" onClick={() => onChange(value.filter((_, j) => j !== i))}><Trash2 className="h-3.5 w-3.5" /></button>}
          </div>
          {withValue
            ? <ValueInput value={f.value} disabled={disabled} onChange={(v) => set(i, { value: v })} />
            : f.type === "string" && (
              <input className="input h-8 w-full" disabled={disabled} placeholder="可选值(用逗号隔开;填了 AI 只能从里面选,适合做分类)"
                     value={(f.options || []).join(",")} onChange={(e) => set(i, { options: e.target.value.split(/[,,]/).map((x) => x.trim()).filter(Boolean) })} />
            )}
        </div>
      ))}
      {!disabled && <button className="btn btn-sm" onClick={() => onChange([...value, { name: `f${value.length + 1}`, label: "", type: "string" }])}><Plus className="h-3.5 w-3.5" />加一个字段</button>}
    </div>
  );
}

function SkillForm({ step, patch, disabled }: FormProps) {
  const entries = Object.entries(step.inputs || {});
  const pct = Math.round((step.confirm_below || 0) * 100);
  return (
    <>
      <Field label="让 AI 判断 / 分析什么" required>
        <TemplateText value={step.instruction || ""} disabled={disabled} rows={3} placeholder="如:根据缺件清单和客户情况,判断这单的紧急程度"
                      onChange={(v) => patch({ instruction: v, skill: "" })} />
      </Field>
      <Field label="给它看哪些数据">
        <div className="space-y-1.5">
          {entries.map(([k, v]) => (
            <div key={k} className="flex items-center gap-1.5">
              <input className="input h-8 w-28 shrink-0" disabled={disabled} defaultValue={k} title="这份数据叫什么"
                     onBlur={(e) => {
                       const nk = e.target.value.trim();
                       if (!nk || nk === k) return;
                       patch({ inputs: Object.fromEntries(entries.map(([a, b]) => [a === k ? nk : a, b])) });
                     }} />
              <div className="min-w-0 flex-1"><RefPicker value={String(v || "")} disabled={disabled} onChange={(r) => patch({ inputs: { ...(step.inputs || {}), [k]: r } })} /></div>
              {!disabled && <button className="btn btn-ghost btn-sm px-1.5" onClick={() => { const n = { ...(step.inputs || {}) }; delete n[k]; patch({ inputs: n }); }}><Trash2 className="h-3.5 w-3.5" /></button>}
            </div>
          ))}
          {!disabled && <button className="btn btn-sm" onClick={() => patch({ inputs: { ...(step.inputs || {}), [`数据${entries.length + 1}`]: "" } })}><Plus className="h-3.5 w-3.5" />加一份数据</button>}
        </div>
      </Field>
      <Field label="要它按哪些字段回答" hint="定义了字段,后面的条件就能按 AI 的回答分支,如 紧急程度 = 高">
        <OutputFields value={step.outputs || []} disabled={disabled} onChange={(v) => patch({ outputs: v })} />
      </Field>
      <Section title="把握不足时转人工确认" defaultOpen={!!step.confirm_below}>
        <div className="grid grid-cols-2 gap-2">
          <Field label="把握低于" hint="0 表示不转人工">
            <div className="flex items-center gap-1">
              <input className="input h-8" type="number" min={0} max={100} step={5} disabled={disabled} value={pct} onChange={(e) => patch({ confirm_below: Math.max(0, Math.min(100, Number(e.target.value) || 0)) / 100 })} />
              <span className="text-label text-muted">%</span>
            </div>
          </Field>
          <Field label="由谁确认"><RefSelect refKind="role" value={step.confirm_role} disabled={disabled || !pct} allowCustom={false} onChange={(v) => patch({ confirm_role: String(v || "") })} /></Field>
        </div>
        <p className="text-caption text-muted">AI 的回答一律标「由 AI 判断」,运行记录里看得到它的依据和把握;转人工后以人确认 / 更正的为准。</p>
      </Section>
    </>
  );
}

// ---------------------------------------------------------------- 人
const FIELD_TYPE_LABEL: Record<string, string> = { text: "文字", number: "数字", boolean: "是 / 否", choice: "单选", date: "日期" };

function FormFields({ value, onChange, disabled }: { value: any[]; onChange: (v: any[]) => void; disabled: boolean }) {
  const set = (i: number, p: any) => onChange(value.map((f, j) => (j === i ? { ...f, ...p } : f)));
  return (
    <div className="space-y-1.5">
      {value.length === 0 && <p className="text-caption text-muted">不用填,对方点「完成」就行。</p>}
      {value.map((f, i) => (
        <div key={i} className="rounded-md border border-line p-2">
          <div className="flex items-center gap-1.5">
            <input className="input h-8 min-w-0 flex-1" placeholder="要对方填什么" disabled={disabled} value={f.label} onChange={(e) => set(i, { label: e.target.value })} />
            <Select className="input h-8 w-24 shrink-0" disabled={disabled} value={f.type || "text"} onChange={(e) => set(i, { type: e.target.value })}>
              {Object.entries(FIELD_TYPE_LABEL).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
            </Select>
            <label className="flex shrink-0 items-center gap-1 text-caption text-muted">
              <input type="checkbox" disabled={disabled} checked={!!f.required} onChange={(e) => set(i, { required: e.target.checked })} />必填
            </label>
            {!disabled && <button className="btn btn-ghost btn-sm px-1.5" onClick={() => onChange(value.filter((_, j) => j !== i))}><Trash2 className="h-3.5 w-3.5" /></button>}
          </div>
          {f.type === "choice" && (
            <input className="input mt-1.5 h-8 w-full" placeholder="选项,用逗号隔开,如:高, 中, 低" disabled={disabled} value={(f.options || []).join(", ")}
                   onChange={(e) => set(i, { options: e.target.value.split(/[,,]/).map((x) => x.trim()).filter(Boolean) })} />
          )}
        </div>
      ))}
      {!disabled && <button className="btn btn-sm" onClick={() => onChange([...value, { label: "", type: "text", required: false }])}><Plus className="h-3.5 w-3.5" />加一项</button>}
    </div>
  );
}

function TaskForm({ step, patch, disabled }: FormProps) {
  return (
    <>
      <Who label="交给谁" step={step} patch={patch} disabled={disabled} />
      <Field label="要他做什么"><TemplateText value={step.instructions || ""} disabled={disabled} rows={3} onChange={(v) => patch({ instructions: v })} /></Field>
      <Field label="要他填什么"><FormFields value={step.form || []} disabled={disabled} onChange={(v) => patch({ form: v })} /></Field>
      <Field label="几小时内完成" hint="0 表示不限时">
        <input className="input h-8 w-28" type="number" min={0} disabled={disabled} value={step.sla_hours ?? 0} onChange={(e) => patch({ sla_hours: Number(e.target.value) || 0 })} />
      </Field>
    </>
  );
}

function NotifyForm({ step, patch, disabled }: FormProps) {
  return (
    <>
      <Who label="通知谁" step={step} patch={patch} disabled={disabled} />
      <Field label="标题" required><TemplateText value={step.subject || ""} disabled={disabled} rows={1} onChange={(v) => patch({ subject: v })} /></Field>
      <Field label="内容" hint="插入的多行数据会显示成表格"><TemplateText value={step.body || ""} disabled={disabled} rows={4} onChange={(v) => patch({ body: v })} /></Field>
    </>
  );
}

// ---------------------------------------------------------------- 动作
const APPROVAL_TEXT: Record<string, string> = { auto: "不用审批,提交即执行(仍留审计、可撤销)。", conditional: "满足条件时直接执行,否则要等人批。", manual: "要等人审批,批了流程才往下走;被驳回走「被驳回」出口(没连线就结束)。" };

function ActionForm({ step, patch, disabled }: FormProps) {
  const [defs, setDefs] = useState<CapDef[]>([]);
  useEffect(() => { void onto.capDefs("action", true).then(setDefs).catch((e) => { setDefs([]); loadFailed(e); }); }, []);
  const def = defs.find((d) => d.name === step.action || d.display_name === step.action || d.id === step.action);
  const params: any[] = def?.spec?.params || [];
  const T: Record<string, string> = { integer: "number", enum: "string", text: "string", list: "list" };
  return (
    <>
      <Field label="执行哪个动作" required>
        <RefSelect refKind="action" value={step.action} disabled={disabled} allowCustom={false} onChange={(v) => patch({ action: String(v || ""), params: {} })} />
      </Field>
      {def && <p className="rounded-md bg-ink/[0.03] px-2.5 py-2 text-caption text-muted">{APPROVAL_TEXT[def.spec?.approval?.mode || "manual"]}</p>}
      {def?.spec?.target_type && (
        <Field label="对哪个对象做" required>
          <ValueInput value={step.object_key} disabled={disabled} type="object" object_type={def.spec.target_type} onChange={(v) => patch({ object_key: v })} />
        </Field>
      )}
      <Field label="动作的参数">
        <MapInputs rows={params.map((p) => ({ key: p.name, label: p.label || p.name, required: !!p.required, type: T[p.type] || p.type,
          options: p.enum?.length ? p.enum : undefined, object_type: p.object_type, hint: p.unit }))}
                   value={step.params} disabled={disabled} empty={step.action ? "这个动作不需要参数" : "先选动作"} onChange={(v) => patch({ params: v })} />
      </Field>
    </>
  );
}

// ---------------------------------------------------------------- 写数据
const OP_LABEL: Record<string, string> = { create: "新建一条", update: "修改", create_rows: "按行批量新建(明细)" };

function OpValues({ op, set, disabled }: { op: any; set: (p: any) => void; disabled: boolean }) {
  const fields = useObjectFields(op.object_type || "", op.op === "update");
  const vals = op.values || {};
  const [showAll, setShowAll] = useState(false);
  const shown = showAll ? fields : fields.filter((f) => vals[String(f.name)] !== undefined || fields.length <= 8);
  if (!op.object_type) return <p className="text-caption text-muted">先选写哪类对象</p>;
  if (!fields.length) return <p className="text-caption text-muted">{op.op === "update" ? "这类对象没有开放修改的属性(在对象属性里勾上「可修改」)" : "加载中…"}</p>;
  return (
    <div className="space-y-2">
      <MapInputs rows={shown.map((f) => ({ key: String(f.name), label: f.label || String(f.name), type: f.type, options: f.options }))}
                 value={vals} disabled={disabled} onChange={(v) => set({ values: v })} />
      {fields.length > shown.length && <button className="text-caption text-brand hover:underline" onClick={() => setShowAll(true)}>显示全部 {fields.length} 个属性</button>}
    </div>
  );
}

function WriteForm({ step, patch, disabled, allOutputs }: FormProps) {
  const ops: any[] = step.ops || [];
  const set = (i: number, p: any) => patch({ ops: ops.map((o, j) => (j === i ? { ...o, ...p } : o)) });
  const appr = step.approval || { mode: "manual", approver_roles: [], auto_when: "" };
  const sc = useScope();
  return (
    <>
      <p className="rounded-md bg-ink/[0.03] px-2.5 py-2 text-caption text-muted">
        这里的几条写入放在<b>同一个事务</b>里:任何一条失败,前面写进去的全部回滚。后面的写入可以引用前面新建出来的主键(「本次写入 · 名字 · key」),主单 + 明细一次写完。
      </p>
      {ops.map((op, i) => {
        // 这一条能用的额外数据:前面写入的结果;按行新建时的「这一行」
        const prev: FlowOutput[] = ops.slice(0, i).filter((o) => o.as).length ? [{
          id: `${step.id}:ops`, var: "ops", title: "本次写入", kind: "item", scope: "",
          schema: { type: "object", fields: ops.slice(0, i).filter((o) => o.as).map((o) => (o.op === "create_rows"
            ? { name: o.as, label: `${o.as}(多条)`, type: "array", items: { type: "object", fields: [{ name: "key", label: "主键", type: "string" }] } }
            : { name: o.as, label: o.as, type: "object", fields: [{ name: "key", label: "主键", type: "string" }] })) },
        }] : [];
        let rowOut: FlowOutput[] = [];
        if (op.op === "create_rows" && op.rows) {
          const head = String(op.rows).replace(/^\$/, "").split(/[.[]/)[0];
          const src = [...(sc.extra || []), ...sc.outputs].find((o) => o.var === head);
          const path = String(op.rows).replace(/^\$/, "").split(".").slice(1);
          let s = src?.schema;
          for (const p of path) s = s?.type === "array" ? s.items?.fields?.find((f) => f.name === p) : s?.fields?.find((f) => f.name === p);
          if (s?.type !== "array") s = s?.fields?.find((f) => f.name === "items") || s;
          rowOut = [{ id: `${step.id}:row`, var: "row", title: "这一行", kind: "item", scope: "", schema: s?.items || { type: "any" } }];
        }
        return (
          <div key={i} className="space-y-2.5 rounded-lg border border-bad/25 bg-bad/[0.02] p-2.5">
            <div className="flex items-center gap-1.5">
              <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-bad/10 text-caption font-medium text-bad">{i + 1}</span>
              <Select className="input h-8 min-w-0 flex-1" disabled={disabled} value={op.op}
                      onChange={(e) => set(i, { op: e.target.value, values: {}, key: "", rows: "" })}>
                {Object.entries(OP_LABEL).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
              </Select>
              {!disabled && <button className="btn btn-ghost btn-sm px-1.5" title="删掉这条写入" onClick={() => patch({ ops: ops.filter((_, j) => j !== i) })}><Trash2 className="h-3.5 w-3.5" /></button>}
            </div>
            <Field label="写哪类对象" required>
              <RefSelect refKind="object_type" value={op.object_type} disabled={disabled} allowCustom={false} onChange={(v) => set(i, { object_type: String(v || ""), values: {} })} />
            </Field>
            <WithExtra extra={[...prev, ...rowOut]}>
              {op.op === "update" && (
                <Field label="改哪一个" required>
                  <ValueInput value={op.key} disabled={disabled} type="object" object_type={op.object_type} onChange={(v) => set(i, { key: v })} />
                </Field>
              )}
              {op.op === "create_rows" && (
                <Field label="按哪份数据逐行新建" required hint="下面的字段可以引用「这一行」里的列">
                  <RefPicker value={op.rows || ""} want="list" disabled={disabled} onChange={(v) => set(i, { rows: v })} />
                </Field>
              )}
              <Field label={op.op === "update" ? "改成什么" : "各字段的值"}>
                <OpValues op={op} set={(p) => set(i, p)} disabled={disabled} />
              </Field>
            </WithExtra>
            <div className="grid grid-cols-2 gap-2">
              <Field label="给这条写入起个名字" hint="后面的写入、后面的步骤用它引用新建的主键">
                <input className="input h-8 font-mono" disabled={disabled} value={op.as || ""} placeholder="如 po" onChange={(e) => set(i, { as: e.target.value.trim() })} />
              </Field>
              <Field label="只在满足时才写" hint="公式,不填就一定写">
                <ExprInput value={op.when || ""} disabled={disabled} placeholder="如 calc.缺口 > 0" onChange={(v) => set(i, { when: v })} />
              </Field>
            </div>
          </div>
        );
      })}
      {!disabled && (
        <button className="btn btn-sm" onClick={() => patch({ ops: [...ops, { op: ops.length ? "create_rows" : "create", object_type: "", values: {}, as: ops.length ? `rows${ops.length}` : "main" }] })}>
          <Plus className="h-3.5 w-3.5" />再写一张表
        </button>
      )}
      <Section title="审批">
        <Field label="审批方式">
          <Select className="input h-8" disabled={disabled} value={appr.mode} onChange={(e) => patch({ approval: { ...appr, mode: e.target.value } })}>
            <option value="manual">人工审批</option><option value="conditional">满足条件自动执行,否则人工审批</option><option value="auto">不用审批,直接执行</option>
          </Select>
        </Field>
        {appr.mode !== "auto" && (
          <Field label="谁来批"><RefMulti refKind="role" value={appr.approver_roles} disabled={disabled} onChange={(v) => patch({ approval: { ...appr, approver_roles: v } })} /></Field>
        )}
        {appr.mode === "conditional" && (
          <Field label="满足什么条件自动执行" hint="可以用流程里的数据,也可以用 eff.字段(这一单要写入的值)">
            <ExprInput value={appr.auto_when || ""} disabled={disabled} placeholder="如 calc.总金额 < 5000" onChange={(v) => patch({ approval: { ...appr, auto_when: v } })} />
          </Field>
        )}
        <p className="text-caption text-muted">{APPROVAL_TEXT[appr.mode]}</p>
      </Section>
      {void allOutputs}
    </>
  );
}

// ---------------------------------------------------------------- 子流程 / 结束
function SubflowForm({ step, patch, disabled, defId }: FormProps) {
  const [list, setList] = useState<SopBrief[]>([]);
  const [params, setParams] = useState<SopParam[]>([]);
  useEffect(() => { void onto.sops({}).then((r) => setList(r.filter((d) => d.id !== defId))).catch((e) => { setList([]); loadFailed(e); }); }, [defId]);
  useEffect(() => {
    if (!step.sop) { setParams([]); return; }
    void onto.sop(step.sop).then((d) => setParams(d.spec.params || [])).catch((e) => { setParams([]); loadFailed(e); });
  }, [step.sop]);
  return (
    <>
      <Field label="调用哪张流程卡" required>
        <Select className="input h-8" disabled={disabled} value={step.sop || ""} onChange={(e) => patch({ sop: e.target.value, params: {} })}>
          <option value="">请选择</option>
          {list.map((d) => <option key={d.id} value={d.id}>{d.title}{d.current_version ? "" : "(未发布)"}</option>)}
        </Select>
      </Field>
      <Field label="给它的参数">
        <MapInputs rows={params.map((p) => ({ key: p.name, label: p.label || p.name, required: p.required && (p.default ?? "") === "", type: p.type, object_type: p.object_type, options: p.options }))}
                   value={step.params} disabled={disabled} empty={step.sop ? "那张流程卡不需要参数" : "先选流程卡"} onChange={(v) => patch({ params: v })} />
      </Field>
      <p className="text-caption text-muted">子流程「结束」节点定义的输出,就是这一步的结果。</p>
    </>
  );
}

function EndForm({ step, patch, disabled }: FormProps) {
  return (
    <>
      <Field label="结果说明" hint="显示在运行记录里,可以插入数据"><TemplateText value={step.outcome || ""} disabled={disabled} rows={1} onChange={(v) => patch({ outcome: v })} /></Field>
      <Field label="流程输出" hint="运行结果里能看到;被别的流程当子流程调用时,就是交给它的数据">
        <OutputFields value={step.outputs || []} disabled={disabled} withValue onChange={(v) => patch({ outputs: v })} />
      </Field>
    </>
  );
}

const FORMS: Record<string, (p: FormProps) => ReactNode> = {
  query: QueryForm, compute: ComputeForm, decision: DecisionForm, foreach: ForeachForm, skill: SkillForm,
  human_task: TaskForm, notify: NotifyForm, action: ActionForm, write: WriteForm, subprocess: SubflowForm, end: EndForm,
};

export function StepForm(props: FormProps) {
  const { step } = props;
  let Form = FORMS[step.type];
  if (step.type === "function") Form = step.function === "metric.query" ? MetricForm : step.function === "function.eval" ? FnEvalForm : SysFnForm;
  return <div className="space-y-4">{Form ? <Form {...props} /> : null}</div>;
}

// ---------------------------------------------------------------- 出错时
export function ErrorForm({ step, patch, disabled }: { step: SopStep; patch: Patch; disabled: boolean }) {
  const e = step.error || { mode: "stop", retry: 0 };
  const set = (p: any) => patch({ error: { ...e, ...p } });
  const retryable = ["function", "query", "skill", "compute", "notify"].includes(step.type);
  const timeoutable = ["function", "query", "skill", "compute"].includes(step.type);
  return (
    <div className="space-y-4">
      <div className="grid grid-cols-2 gap-2">
        <Field label="失败后自动重试" hint={retryable ? "最多 3 次" : "这一步会改数据或等人,不自动重试"}>
          <input className="input h-8" type="number" min={0} max={3} disabled={disabled || !retryable} value={e.retry || 0} onChange={(x) => set({ retry: Number(x.target.value) || 0 })} />
        </Field>
        <Field label="超时(秒)" hint={timeoutable ? "0 表示不限" : "不适用"}>
          <input className="input h-8" type="number" min={0} max={600} disabled={disabled || !timeoutable} value={e.timeout || 0} onChange={(x) => set({ timeout: Number(x.target.value) || 0 })} />
        </Field>
      </div>
      <Field label="还是失败的话">
        <Select className="input h-8" disabled={disabled} value={e.mode} onChange={(x) => set({ mode: x.target.value })}>
          <option value="stop">整个流程停下,标为失败</option>
          <option value="default">用一个默认值当作这一步的结果,接着往下走</option>
          <option value="branch">走「出错」出口(在画布上连一条线)</option>
        </Select>
      </Field>
      {e.mode === "default" && <Field label="默认值"><ValueInput value={e.default} disabled={disabled} onChange={(v) => set({ default: v })} /></Field>}
      {e.mode === "branch" && <p className="text-caption text-muted">走出错分支时,后面的步骤可以用 error.message 拿到出错原因。</p>}
    </div>
  );
}

// ---------------------------------------------------------------- 开始节点:流程参数
const PARAM_TYPE: Record<string, string> = { string: "文字", number: "数字", date: "日期", boolean: "是 / 否", object: "一个对象", period: "统计周期", choice: "单选", list: "多行数据(明细)" };

export function ParamsEditor({ value, onChange, disabled }: { value: SopParam[]; onChange: (v: SopParam[]) => void; disabled: boolean }) {
  const set = (i: number, p: Partial<SopParam>) => onChange(value.map((x, j) => (j === i ? { ...x, ...p } : x)));
  return (
    <div className="space-y-3">
      {value.length === 0 && <p className="text-label text-muted">不用填什么,点运行就开始。</p>}
      {value.map((p, i) => (
        <div key={i} className="relative space-y-2.5 rounded-lg border border-line p-3 pr-10">
          <div className="grid grid-cols-[minmax(0,1fr)_9rem] gap-2">
            <Field label="名称" required><input className="input h-8" disabled={disabled} value={p.label} onChange={(e) => set(i, { label: e.target.value })} /></Field>
            <Field label="类型">
              <Select className="input h-8" disabled={disabled} value={p.type} onChange={(e) => set(i, { type: e.target.value, ...(e.target.value === "list" && !p.columns?.length ? { columns: [{ name: "c1", label: "", type: "string" }] } : {}) })}>
                {Object.entries(PARAM_TYPE).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
              </Select>
            </Field>
          </div>
          <p className="text-caption text-muted">流程里引用它:<code className="font-mono">${p.name}</code></p>
          {p.type === "object" && (
            <Field label="哪类对象" required><RefSelect refKind="object_type" value={p.object_type} disabled={disabled} allowCustom={false} onChange={(v) => set(i, { object_type: String(v || "") })} /></Field>
          )}
          {p.type === "choice" && (
            <Field label="可选项" hint="用逗号隔开">
              <input className="input h-8" disabled={disabled} value={(p.options || []).join(",")} onChange={(e) => set(i, { options: e.target.value.split(/[,,]/).map((x) => x.trim()).filter(Boolean) })} />
            </Field>
          )}
          {p.type === "list" && (
            <Field label="每一行有哪些列" hint="运行时按表格填,如 配件、数量、单价">
              <div className="space-y-1.5">
                {(p.columns || []).map((c, j) => (
                  <div key={j} className="flex items-center gap-1">
                    <input className="input h-8 w-24 font-mono text-label" disabled={disabled} value={c.name} placeholder="英文名"
                           onChange={(e) => set(i, { columns: (p.columns || []).map((x, k) => (k === j ? { ...x, name: e.target.value.trim() } : x)) })} />
                    <input className="input h-8 min-w-0 flex-1" disabled={disabled} value={c.label} placeholder="中文名"
                           onChange={(e) => set(i, { columns: (p.columns || []).map((x, k) => (k === j ? { ...x, label: e.target.value } : x)) })} />
                    <Select className="input h-8 w-20 shrink-0" disabled={disabled} value={c.type}
                            onChange={(e) => set(i, { columns: (p.columns || []).map((x, k) => (k === j ? { ...x, type: e.target.value } : x)) })}>
                      <option value="string">文字</option><option value="number">数字</option><option value="date">日期</option><option value="boolean">是否</option>
                    </Select>
                    {!disabled && <button className="btn btn-ghost btn-sm px-1.5" onClick={() => set(i, { columns: (p.columns || []).filter((_, k) => k !== j) })}><Trash2 className="h-3.5 w-3.5" /></button>}
                  </div>
                ))}
                {!disabled && <button className="btn btn-sm" onClick={() => set(i, { columns: [...(p.columns || []), { name: `c${(p.columns || []).length + 1}`, label: "", type: "string" }] })}><Plus className="h-3.5 w-3.5" />加一列</button>}
              </div>
            </Field>
          )}
          <Field label="填写说明"><input className="input h-8" disabled={disabled} value={p.description || ""} placeholder="告诉运行的人这一项怎么填" onChange={(e) => set(i, { description: e.target.value })} /></Field>
          <div className="grid grid-cols-[minmax(0,1fr)_7rem] gap-2">
            {!["object", "boolean", "list"].includes(p.type) ? (
              <Field label="默认值"><input className="input h-8" disabled={disabled} value={p.default ?? ""} onChange={(e) => set(i, { default: e.target.value })} /></Field>
            ) : <span />}
            <Field label="必填">
              <Select className="input h-8" disabled={disabled} value={p.required ? "1" : "0"} onChange={(e) => set(i, { required: e.target.value === "1" })}>
                <option value="1">是</option><option value="0">否</option>
              </Select>
            </Field>
          </div>
          {!disabled && <button className="absolute right-2 top-2 rounded p-1.5 text-muted hover:bg-bad/10 hover:text-bad" title="删除" onClick={() => onChange(value.filter((_, j) => j !== i))}><Trash2 className="h-3.5 w-3.5" /></button>}
        </div>
      ))}
      {!disabled && (
        <button className="btn btn-sm" onClick={() => {
          let n = value.length + 1;
          while (value.some((x) => x.name === `p${n}`)) n += 1;
          onChange([...value, { name: `p${n}`, label: "", type: "string", object_type: "", calendar: "", options: [], required: true }]);
        }}><Plus className="h-3.5 w-3.5" />加一项</button>
      )}
    </div>
  );
}

/** 这一步的结果长什么样(输出页):字段树 + 最近一次运行的样例值。 */
export function SchemaTree({ schema, sample, depth = 0 }: { schema?: DataSchema; sample?: any; depth?: number }) {
  if (!schema) return <p className="text-caption text-muted">这一步不产出数据。</p>;
  const fields = schema.type === "array" ? schema.items?.fields : schema.fields;
  const sampleOf = (name: string) => {
    const s = schema.type === "array" ? (Array.isArray(sample) ? sample[0] : sample?.items?.[0]) : sample;
    return s && typeof s === "object" ? s[name] : undefined;
  };
  if (!fields?.length) return depth ? null : <p className="text-caption text-muted">结构要运行后才知道({TYPE_TAG[schema.type] || schema.type})。</p>;
  return (
    <div className={cn(depth > 0 && "ml-3 border-l border-line pl-2")}>
      {fields.map((f) => {
        const v = sampleOf(String(f.name));
        const shown = v === undefined ? "" : typeof v === "object" ? (Array.isArray(v) ? `${v.length} 条` : "{…}") : String(v);
        return (
          <div key={f.name}>
            <div className="flex items-center gap-1.5 py-0.5 text-label">
              <span className="min-w-0 truncate">{f.label || f.name}</span>
              <code className="shrink-0 font-mono text-caption text-muted">{f.name}</code>
              <span className="shrink-0 rounded bg-ink/5 px-1 text-[11px] text-muted">{TYPE_TAG[f.type] || f.type}</span>
              {shown && <span className="ml-auto min-w-0 truncate text-caption text-ok" title={shown}>{shown}</span>}
            </div>
            {(f.type === "object" || f.type === "array") && depth < 3 && <SchemaTree schema={f} sample={v} depth={depth + 1} />}
          </div>
        );
      })}
    </div>
  );
}

export { findStep };