yyb
13 小时以前 352f7bbb74f1b6c57b3d3e576849d0565932fbd4
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
import {
  getApprovalTemplateDetail,
  listApprovalTemplate,
  TEMPLATE_TYPE_CUSTOM,
} from "@/api/officeProcessAutomation/approvalTemplate.js";
import { computed, reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import {
  fetchBusinessTypeOptions,
  mapEnabledFromApi,
  unwrapTemplateList,
} from "../approve-template/approveTemplateConstants.js";
import {
  createEmptySubmitForm,
  mapSubmitTemplateCard,
  matchBusinessTypeValue,
} from "../approve-list/approveListConstants.js";
import {
  getApprovalModuleConfig,
  getModuleMatchingBusinessTypes,
  resolveModuleBusinessType,
} from "./approvalModuleRegistry.js";
import {
  buildFormPayloadRules,
  buildTemplateBindingFromDetail,
  validateTemplateBinding,
} from "./approvalTemplateBindingUtils.js";
 
/**
 * 审批模板绑定(业务模块固定类型 / 审批列表通用)
 *
 * @param {object} options
 * @param {string} [options.moduleKey] 业务模块 key,见 approvalModuleRegistry
 * @param {string|number} [options.businessType] 直接指定类型(优先级高于 moduleKey)
 * @param {'module'|'universal'} [options.mode] module=仅本类型模板;universal=需先选类型
 */
export function useApprovalTemplateBinding(options = {}) {
  const { moduleKey = null, businessType: fixedBusinessType = null, mode = moduleKey ? "module" : "universal" } =
    options;
 
  const isUniversal = mode === "universal" && !moduleKey && fixedBusinessType == null;
 
  const allTemplates = ref([]);
  const businessTypeOptions = ref([]);
  const selectedBusinessType = ref(fixedBusinessType ?? "");
  const templatesLoading = ref(false);
  const step = ref(isUniversal ? 1 : 1);
 
  const bindingForm = reactive(createEmptySubmitForm(""));
 
  const moduleConfig = computed(() => getApprovalModuleConfig(moduleKey));
 
  const resolvedBusinessType = computed(() => {
    if (fixedBusinessType != null && fixedBusinessType !== "") return fixedBusinessType;
    if (selectedBusinessType.value != null && selectedBusinessType.value !== "") {
      return selectedBusinessType.value;
    }
    if (moduleKey) {
      return resolveModuleBusinessType(moduleKey, businessTypeOptions.value);
    }
    return "";
  });
 
  const matchingBusinessTypes = computed(() => {
    if (fixedBusinessType != null && fixedBusinessType !== "") return [fixedBusinessType];
    if (isUniversal) {
      const t = selectedBusinessType.value;
      return t != null && t !== "" ? [t] : [];
    }
    if (moduleKey) {
      return getModuleMatchingBusinessTypes(moduleKey, businessTypeOptions.value);
    }
    const t = resolvedBusinessType.value;
    return t != null && t !== "" ? [t] : [];
  });
 
  const templateCards = computed(() => {
    const types = matchingBusinessTypes.value;
    if (!types.length) return [];
    return allTemplates.value.filter((card) =>
      types.some(
        (t) =>
          matchBusinessTypeValue(card.businessType, t) ||
          matchBusinessTypeValue(card.approvalType, t)
      )
    );
  });
 
  const activeTemplate = computed(() => bindingForm.templateSnapshot || null);
 
  const formFields = computed(() => {
    const tplFields = activeTemplate.value?.fields;
    if (tplFields?.length) return tplFields;
    return bindingForm.formFieldDefs || [];
  });
 
  const formRules = computed(() => buildFormPayloadRules(formFields.value));
 
  const hasTemplateBound = computed(() => Boolean(activeTemplate.value?.templateId || bindingForm.templateId));
 
  function businessTypeLabel(type) {
    if (type == null || type === "") return "";
    const hit = businessTypeOptions.value.find((x) => matchBusinessTypeValue(x.value, type));
    return hit?.label || moduleConfig.value?.label || "";
  }
 
  const selectedBusinessTypeLabel = computed(() => businessTypeLabel(resolvedBusinessType.value));
 
  function countTemplatesByBusinessType(type) {
    const types =
      moduleKey && !fixedBusinessType
        ? getModuleMatchingBusinessTypes(moduleKey, businessTypeOptions.value)
        : [type];
    return allTemplates.value.filter((card) =>
      types.some(
        (t) =>
          matchBusinessTypeValue(card.businessType, t) ||
          matchBusinessTypeValue(card.approvalType, t)
      )
    ).length;
  }
 
  async function loadTemplates() {
    templatesLoading.value = true;
    try {
      const [typeOptions, customRes] = await Promise.all([
        fetchBusinessTypeOptions(),
        listApprovalTemplate(TEMPLATE_TYPE_CUSTOM),
      ]);
      businessTypeOptions.value = typeOptions;
      allTemplates.value = unwrapTemplateList(customRes)
        .filter((row) => mapEnabledFromApi(row.enabled))
        .map(mapSubmitTemplateCard);
 
      if (moduleKey && !fixedBusinessType) {
        const resolved = resolveModuleBusinessType(moduleKey, typeOptions);
        if (resolved != null && resolved !== "") selectedBusinessType.value = resolved;
      }
    } catch {
      businessTypeOptions.value = [];
      allTemplates.value = [];
      ElMessage.error("加载审批模板失败");
    } finally {
      templatesLoading.value = false;
    }
  }
 
  function resetBinding() {
    step.value = isUniversal ? 1 : 1;
    if (!fixedBusinessType && !moduleKey) selectedBusinessType.value = "";
    else if (moduleKey) {
      selectedBusinessType.value =
        fixedBusinessType ?? resolveModuleBusinessType(moduleKey, businessTypeOptions.value) ?? "";
    }
    Object.assign(bindingForm, createEmptySubmitForm(""));
  }
 
  function pickBusinessType(type) {
    if (!countTemplatesByBusinessType(type)) {
      ElMessage.warning("该类型下暂无可用审批模板");
      return;
    }
    selectedBusinessType.value = type;
    step.value = 2;
  }
 
  function backToBusinessTypePick() {
    selectedBusinessType.value = "";
    step.value = 1;
  }
 
  function backToTemplatePick() {
    step.value = isUniversal ? 2 : 1;
  }
 
  async function pickTemplate(card) {
    if (!card?.id) return false;
    templatesLoading.value = true;
    try {
      const res = await getApprovalTemplateDetail(card.id);
      const applied = buildTemplateBindingFromDetail(res);
      Object.assign(bindingForm, {
        templateKey: String(card.id),
        ...applied,
      });
      step.value = isUniversal ? 3 : 2;
      return true;
    } catch {
      ElMessage.error("加载模板详情失败");
      return false;
    } finally {
      templatesLoading.value = false;
    }
  }
 
  /** 直接以详情行绑定(编辑回显) */
  function applyBindingState(state) {
    if (!state) return;
    Object.assign(bindingForm, createEmptySubmitForm(""), state);
    step.value = isUniversal ? 3 : 2;
  }
 
  async function validateBinding(formRef) {
    if (formRef?.validate) {
      try {
        await formRef.validate();
      } catch {
        return { ok: false };
      }
    }
    if (!hasTemplateBound.value) {
      return { ok: false, message: "请选择审批模板" };
    }
    return validateTemplateBinding({ flowNodes: bindingForm.flowNodes });
  }
 
  function getBindingPayload() {
    return {
      templateId: bindingForm.templateId,
      templateName: bindingForm.templateName,
      businessType: bindingForm.businessType ?? resolvedBusinessType.value,
      templateSnapshot: bindingForm.templateSnapshot,
      formFieldDefs: bindingForm.formFieldDefs,
      formPayload: bindingForm.formPayload,
      flowNodes: bindingForm.flowNodes,
      templateAttachments: bindingForm.templateAttachments,
      storageBlobDTOs: bindingForm.storageBlobDTOs,
    };
  }
 
  return {
    isUniversal,
    moduleConfig,
    step,
    bindingForm,
    allTemplates,
    businessTypeOptions,
    selectedBusinessType,
    resolvedBusinessType,
    selectedBusinessTypeLabel,
    templateCards,
    activeTemplate,
    formFields,
    formRules,
    hasTemplateBound,
    templatesLoading,
    loadTemplates,
    resetBinding,
    pickBusinessType,
    backToBusinessTypePick,
    backToTemplatePick,
    pickTemplate,
    applyBindingState,
    validateBinding,
    getBindingPayload,
    countTemplatesByBusinessType,
    businessTypeLabel,
  };
}