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),
|
};
|
}
|