刘光辉
13 小时以前 0dfe84494048ce27ba8449831782128412d3eb13
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
import { fetchFillData } from '../api/template-fill';
import { buildDraftFields } from '../domain/draft';
import { parsePluginContext } from '../domain/plugin-context';
import type { FieldChange } from '../domain/types';
import type { OnlyOfficeBridge } from '../onlyoffice/bridge';
import { useFillerStore } from '../stores/filler';
 
const SDK_READY_TIMEOUT_MS = 5_000;
 
export function useTemplateFiller(bridge: OnlyOfficeBridge) {
  const store = useFillerStore();
  let context: ReturnType<typeof parsePluginContext> | null = null;
  let initialized = false;
  const readyTimeout = setTimeout(() => {
    if (!initialized) {
      store.status = 'error';
      store.message = 'ONLYOFFICE SDK 初始化超时';
    }
  }, SDK_READY_TIMEOUT_MS);
  async function initialize() {
    initialized = true;
    clearTimeout(readyTimeout);
    try {
      context = parsePluginContext(bridge.getRuntimeOptions());
      const [data, fields] = await Promise.all([fetchFillData(context), bridge.inspectFields()]);
      store.fields = buildDraftFields(fields, data); store.status = 'ready'; store.message = '已连接';
    } catch (error) { store.status = 'error'; store.message = error instanceof Error ? error.message : String(error); }
  }
  async function apply() {
    if (!context?.canFill) return;
    const changes: FieldChange[] = store.fields.filter((field) => field.draftValue !== field.documentValue).map((field) => ({ tag: field.tag, type: field.type, value: field.draftValue }));
    if (!changes.length) return;
    store.status = 'working';
    try {
      const results = await bridge.applyFields(changes);
      store.applyResults(results); store.status = 'ready'; store.message = results.every((item) => item.ok) ? '已应用到文档' : '部分字段应用失败';
    } catch (error) {
      store.status = 'error';
      store.message = error instanceof Error ? error.message : String(error);
    }
  }
  const cleanup = bridge.bindLifecycle({ onReady: () => void initialize(), onThemeChanged: () => undefined });
  return {
    store,
    apply,
    dispose: () => {
      clearTimeout(readyTimeout);
      cleanup();
    },
    canFill: () => Boolean(context?.canFill),
  };
}