刘光辉
6 小时以前 cf11e63b659afcc9792ab3e395f1b45d844431a8
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
<script lang="ts" setup>
import { computed, inject, nextTick, provide, reactive, ref, toRefs, unref } from 'vue';
 
import { useMessage } from '@jnpf/hooks';
import { BasicPopup, usePopupInner } from '@jnpf/ui/popup';
import { createAsyncComponent, getDateTimeUnit, getScriptFunc } from '@jnpf/utils';
 
import { useUserStore } from '@vben/stores';
 
import dayjs from 'dayjs';
import { cloneDeep } from 'lodash-es';
 
import { createAuditCorrelationId } from '#/api/onlineDev/auditHeaders';
import { createModel, launchFlow } from '#/api/onlineDev/visualDev';
import { getDataInterfaceRes } from '#/api/systemData/dataInterface';
import { createAuditRequestOnlineUtils, createSignedAuditRequestOnlineUtils } from '#/components/FormGenerator/src/helper/auditDisplay';
import { buildDisplayOnlySubmitData } from '#/components/FormGenerator/src/helper/displayOnly';
import { $t } from '#/locales';
import { useBaseStore } from '#/store';
import { onlineUtils as defaultOnlineUtils, getLaunchFlowParamList, getParamList } from '#/utils/jnpf';
import { normalizeOrganizationConfig, resolveCurrentOrganizationDefaultIds } from '#/utils/organizationConfig';
 
import { createFormScopedOnlineUtils } from '../formOnlineUtils';
import CustomForm from '../list/CustomForm.vue';
 
interface State {
  formConf: any;
  config: any;
  loading: boolean;
  btnLoading: boolean;
  key: number;
  reviewPassed: boolean;
  reviewVisible: boolean;
  formRuntimeVersion: number;
}
 
defineEmits(['register']);
const { createConfirm, createMessage } = useMessage();
const userStore = useUserStore();
const baseStore = useBaseStore();
const [registerPopup, { changeLoading, setPopupProps }] = usePopupInner(init);
const parserRef = ref<any>(null);
const customFormRef = ref<any>(null);
let formActionVersion = 0;
const inheritedOnlineUtils = inject<any>('onlineUtils', defaultOnlineUtils);
const { onlineUtils: formOnlineUtils, resetLoading: resetFormLoading } = createFormScopedOnlineUtils(inheritedOnlineUtils, (loading, tip) => {
  setPopupProps({ loading, loadingText: loading ? tip : '' });
});
provide('onlineUtils', formOnlineUtils);
const state = reactive<State>({
  formConf: {},
  config: {},
  loading: false,
  btnLoading: false,
  key: Date.now(),
  reviewPassed: true,
  reviewVisible: true,
  formRuntimeVersion: 0,
});
const { formConf, key, loading, config, btnLoading } = toRefs(state);
const Parser = createAsyncComponent(() => import('#/components/FormGenerator/src/components/Parser.vue'));
 
const getOkText = computed(() => {
  const text = state.formConf.confirmButtonTextI18nCode
    ? $t(state.formConf.confirmButtonTextI18nCode, state.formConf.confirmButtonText)
    : state.formConf.confirmButtonText;
  return text || $t('common.okText');
});
const getReviewText = computed(() => {
  const text = state.formConf.reviewButtonTextI18nCode
    ? $t(state.formConf.reviewButtonTextI18nCode, state.formConf.reviewButtonText)
    : state.formConf.reviewButtonText;
  return text || $t('common.reviewText');
});
 
const getFormCustomBtns = computed(() => {
  void state.formRuntimeVersion;
  if (state.loading || !parserRef.value) return [];
  return (state.formConf.formCustomBtns || []).filter((item) => item.show !== false && getFormCustomBtnEnable(item));
});
 
function fillFormData(form, data) {
  const userInfo = userStore.getUserInfo;
  const currDate = new Date();
  const loop = (list) => {
    for (const item of list) {
      if (item.__vModel__ && item.__config__.defaultCurrent) {
        if (item.__config__.jnpfKey === 'datePicker') {
          item.__config__.defaultValue = dayjs(currDate).startOf(getDateTimeUnit(item.format)).valueOf();
        }
        if (item.__config__.jnpfKey === 'timePicker') {
          item.__config__.defaultValue = dayjs(currDate).format(item.format || 'HH:mm:ss');
        }
        if (item.__config__.jnpfKey === 'organizeSelect' && !Object.prototype.hasOwnProperty.call(data, item.__vModel__)) {
          item.__config__.defaultValue = resolveCurrentOrganizationDefaultIds(
            userInfo,
            normalizeOrganizationConfig(baseStore.getSysConfig).currentOrganizationDefaultLevel,
            !!item.multiple,
          );
        }
        if (item.__config__.jnpfKey === 'userSelect' && userInfo?.userId) {
          item.__config__.defaultValue = item.multiple ? [userInfo.userId] : userInfo.userId;
        }
        if (item.__config__.jnpfKey === 'usersSelect' && userInfo?.userId) {
          item.__config__.defaultValue = [`${userInfo.userId}--user`];
        }
        if (item.__config__.jnpfKey === 'posSelect' && userInfo?.positionIds?.length) {
          item.__config__.defaultValue = item.multiple ? userInfo.positionIds : userInfo.positionId;
        }
        if (item.__config__.jnpfKey === 'sign' && userInfo?.signImg) {
          item.__config__.defaultValue = userInfo.signImg;
        }
      }
      if (item.__config__ && item.__config__.children && Array.isArray(item.__config__.children)) {
        loop(item.__config__.children);
      }
    }
  };
  loop(form.fields);
  form.formData = data;
}
function init(data) {
  formActionVersion++;
  resetFormLoading();
  changeLoading(true);
  state.loading = true;
  state.config = data;
  state.formConf = data.formData ? JSON.parse(data.formData) : {};
  state.formConf.category = data.category || state.formConf.category;
  state.reviewVisible = !!state.formConf.hasReviewBtn && !state.formConf.reviewBtnConfig?.noShow;
  state.reviewPassed = !state.reviewVisible || !!state.formConf.reviewBtnConfig?.biz_review_optional;
  fillFormData(state.formConf, {});
  nextTick(() => {
    changeLoading(false);
    state.loading = false;
    state.key = Date.now();
  });
}
function submitForm(data, callback, scriptParameter = {}, auditDisplayFields = [], getAuditDisplayFields?, auditBizSign?: string) {
  if (!data) return;
  state.btnLoading = true;
  const formData = buildDisplayOnlySubmitData(state.formConf.fields, data);
  const dataForm = { auditDisplayFields, data: JSON.stringify(formData) };
  if (state.formConf.funcs?.customSubmit) {
    runCustomSubmit(formData, scriptParameter, auditDisplayFields, getAuditDisplayFields, auditBizSign)
      .then((res) => {
        if (res?.msg) createMessage.success(res.msg);
        if (callback && typeof callback === 'function') callback(res?.data?.id);
        state.btnLoading = false;
        handleReset();
      })
      .catch(() => {
        state.btnLoading = false;
      });
    return;
  }
  createModel(state.config.modelId, dataForm, auditBizSign)
    .then((res) => {
      createMessage.success(res.msg);
      if (callback && typeof callback === 'function') callback(res?.data?.id);
      state.btnLoading = false;
      handleReset();
    })
    .catch(() => {
      state.btnLoading = false;
    });
}
function getLatestSubmitData(formData, scriptParameter) {
  return buildDisplayOnlySubmitData(state.formConf.fields, scriptParameter?.formData || formData);
}
function syncLatestSubmitData(formData, scriptParameter) {
  const latestFormData = getLatestSubmitData(formData, scriptParameter);
  Object.keys(formData).forEach((key) => delete formData[key]);
  Object.assign(formData, latestFormData);
}
function runCustomSubmit(formData, scriptParameter, auditDisplayFields, getAuditDisplayFields?, auditBizSign?: string) {
  const func: any = getScriptFunc(state.formConf.funcs?.customSubmitFunc);
  if (!func) return Promise.reject();
  const auditCorrelationId = auditBizSign || createAuditCorrelationId();
  const setFormData = (prop, value) => {
    scriptParameter?.setFormData?.(prop, value);
    syncLatestSubmitData(formData, scriptParameter);
  };
  const formContext = {
    id: '',
    isEdit: false,
    submit: (resolve, reject) => {
      const latestFormData = getLatestSubmitData(formData, scriptParameter);
      const latestAuditDisplayFields = typeof getAuditDisplayFields === 'function' ? getAuditDisplayFields(latestFormData) : auditDisplayFields;
      const dataForm = { auditDisplayFields: latestAuditDisplayFields, data: JSON.stringify(latestFormData) };
      createModel(state.config.modelId, dataForm, auditCorrelationId)
        .then((res) => {
          resolve?.(res);
        })
        .catch((error) => {
          reject?.(error);
        });
    },
  };
  const scopedOnlineUtils = createAuditRequestOnlineUtils(
    scriptParameter?.onlineUtils,
    () => {
      const latestFormData = getLatestSubmitData(formData, scriptParameter);
      return typeof getAuditDisplayFields === 'function' ? getAuditDisplayFields(latestFormData) : auditDisplayFields;
    },
    () => {
      if (auditBizSign) return auditBizSign;
      const latestFormData = getLatestSubmitData(formData, scriptParameter);
      return latestFormData.biz_sign ?? latestFormData.biz_sign_jnpfId;
    },
    auditCorrelationId,
  );
  try {
    return Promise.resolve(func({ ...scriptParameter, formData, setFormData, formContext, onlineUtils: scopedOnlineUtils }));
  } catch {
    return Promise.reject();
  }
}
function handleReset() {
  formActionVersion++;
  state.reviewVisible = !!state.formConf.hasReviewBtn && !state.formConf.reviewBtnConfig?.noShow;
  state.reviewPassed = !state.reviewVisible || !!state.formConf.reviewBtnConfig?.biz_review_optional;
  fillFormData(state.formConf, {});
  nextTick(() => {
    getParser().handleReset();
  });
}
function handleSubmit() {
  if (state.config.isPreview) return createMessage.warning('功能预览不支持数据保存');
  getParser().handleSubmit();
}
function handleReview() {
  getParser().handleReview();
}
function getParser() {
  const parser = unref(parserRef);
  if (!parser) throw new Error('parser is null!');
  return parser;
}
function getRuntimeParameter() {
  return getParser().getRuntimeParameter?.() || { formData: {}, onlineUtils: formOnlineUtils };
}
function handleFormRuntimeChange() {
  state.formRuntimeVersion++;
}
function getFormCustomBtnEnable(item) {
  const enableFunc = item?.actionConfig?.enableFunc;
  if (!enableFunc || !parserRef.value) return true;
  const func: any = getScriptFunc(enableFunc);
  if (!func) return true;
  try {
    const parameter = getRuntimeParameter();
    return !!func({ data: parameter.formData, ...parameter });
  } catch (error) {
    console.error('[FormPopup] custom button enable rule error:', error);
    return false;
  }
}
function getFormCustomButtonText(customBtn) {
  return customBtn.labelI18nCode ? $t(customBtn.labelI18nCode, customBtn.label) : customBtn.label;
}
function getFormCustomButtonSignMetaData(customBtn) {
  const { formData } = getRuntimeParameter();
  return {
    biz_button: getFormCustomButtonText(customBtn),
    biz_data: [cloneDeep(formData)],
    biz_form_id: state.config.modelId || '',
    biz_module: '',
    biz_title: '',
    is_biz_form: true,
    is_review_button: false,
  };
}
async function formCustomBtnsHandle(customBtn) {
  if (state.config.isPreview) return createMessage.warning('功能预览不支持执行操作');
  if (!getFormCustomBtns.value.includes(customBtn)) return;
  const actionVersion = formActionVersion;
  const actionConfig = customBtn?.actionConfig || {};
  if (actionConfig.enableFormValidate !== false && !(await getParser().handleValidate())) return;
  if (actionVersion !== formActionVersion || !getFormCustomBtns.value.includes(customBtn)) return;
  if (!actionConfig.biz_sign_enabled || actionConfig.btnType == 2) {
    try {
      return await executeFormCustomBtn(customBtn);
    } catch (error: any) {
      createMessage.error(error?.message || '执行操作失败');
      return;
    }
  }
  const { onlineUtils } = getRuntimeParameter();
  onlineUtils.sign({
    isFaceToFace: false,
    metaData: getFormCustomButtonSignMetaData(customBtn),
    onCancel: () => {},
    onSubmit: (signData) => {
      if (actionVersion !== formActionVersion) return;
      return executeFormCustomBtn(customBtn, signData, true);
    },
  });
}
function executeFormCustomBtn(customBtn, signData?: any, hasBizSign = false) {
  const actionConfig = customBtn.actionConfig || {};
  if (actionConfig.btnType == 1) return handleFormCustomPopup(actionConfig);
  if (actionConfig.btnType == 2) return handleFormCustomScript(customBtn, signData, hasBizSign);
  if (actionConfig.btnType == 3) return handleFormCustomInterface(actionConfig);
  if (actionConfig.btnType == 4) return handleFormCustomLaunchFlow(customBtn);
}
function handleFormCustomPopup(actionConfig) {
  const { formData } = getRuntimeParameter();
  customFormRef.value?.init({
    ...actionConfig,
    menuId: actionConfig.modelId,
    record: formData,
    recordModelId: state.config.modelId,
  });
}
function getFormCustomButtonSign(customBtn, signData?: any, hasBizSign = false) {
  const actionVersion = formActionVersion;
  return (callback: (data: any) => Promise<void> | void) => {
    if (typeof callback !== 'function') return;
    const executeCallback = (currentSignData?: any, signed = false) => {
      if (actionVersion !== formActionVersion) return;
      const parameter = getRuntimeParameter();
      const callbackOnlineUtils = signed ? createSignedAuditRequestOnlineUtils(parameter.onlineUtils, () => currentSignData?.biz_sign) : parameter.onlineUtils;
      return callback({
        ...parameter,
        ...currentSignData,
        bizSign: signed ? currentSignData?.biz_sign : undefined,
        data: parameter.formData,
        onlineUtils: callbackOnlineUtils,
        signData: currentSignData,
      });
    };
    if (actionVersion !== formActionVersion) return;
    if (!customBtn?.actionConfig?.biz_sign_enabled) return executeCallback();
    if (hasBizSign) return executeCallback(signData, true);
    const { onlineUtils } = getRuntimeParameter();
    return onlineUtils.sign({
      isFaceToFace: false,
      metaData: getFormCustomButtonSignMetaData(customBtn),
      onCancel: () => {},
      onSubmit: (currentSignData) => executeCallback(currentSignData, true),
    });
  };
}
function handleFormCustomScript(customBtn, signData?: any, hasBizSign = false) {
  const parameter = getRuntimeParameter();
  const scopedOnlineUtils = hasBizSign ? createSignedAuditRequestOnlineUtils(parameter.onlineUtils, () => signData?.biz_sign) : parameter.onlineUtils;
  const func: any = getScriptFunc(customBtn.actionConfig.func);
  if (!func) return;
  return func({
    ...parameter,
    bizSign: hasBizSign ? signData?.biz_sign : undefined,
    data: parameter.formData,
    onlineUtils: scopedOnlineUtils,
    sign: getFormCustomButtonSign(customBtn, signData, hasBizSign),
  });
}
function handleFormCustomInterface(actionConfig) {
  const execute = () => {
    const { formData } = getRuntimeParameter();
    const query = { paramList: getParamList(actionConfig.templateJson, { ...formData, id: formData.id || '' }) || [] };
    return getDataInterfaceRes(actionConfig.interfaceId, query).then((res) => createMessage.success(res.msg));
  };
  if (!actionConfig.useConfirm) return execute();
  createConfirm({
    iconType: 'warning',
    title: $t('common.tipTitle'),
    content: actionConfig.confirmTitle || '确认执行此操作?',
    onOk: execute,
  });
}
function handleFormCustomLaunchFlow(customBtn) {
  const launchFlowCfg = cloneDeep(customBtn.actionConfig.launchFlow);
  const { formData } = getRuntimeParameter();
  const query = {
    template: launchFlowCfg.flowId,
    btnCode: customBtn.value,
    currentUser: launchFlowCfg.currentUser,
    customUser: launchFlowCfg.customUser,
    initiator: launchFlowCfg.initiator,
    hasPermission: launchFlowCfg.hasPermission,
    dataList: [getLaunchFlowParamList(launchFlowCfg.transferList, formData)],
  };
  return launchFlow(state.config.modelId, query).then((res) => createMessage.success(res.msg));
}
</script>
<template>
  <BasicPopup v-bind="$attrs" @register="registerPopup" :show-back-icon="false" :show-cancel-btn="false" :title="config.fullName">
    <template #insertToolbar>
      <a-button v-if="state.reviewVisible" class="mr-[10px]" @click="handleReview">{{ getReviewText }}</a-button>
      <a-button
        v-if="formConf.hasConfirmBtn !== false"
        type="primary"
        @click="handleSubmit"
        :disabled="state.reviewVisible && !state.reviewPassed"
        :loading="btnLoading">
        {{ getOkText }}
      </a-button>
      <a-button
        v-for="item in getFormCustomBtns"
        :key="item.value"
        class="ml-[10px]"
        :type="item.actionConfig?.buttonType || undefined"
        :pre-icon="item.actionConfig?.btnIcon"
        @click="formCustomBtnsHandle(item)">
        {{ getFormCustomButtonText(item) }}
      </a-button>
      <a-button type="warning" class="ml-[10px]" @click="handleReset">{{ $t('common.resetText') }}</a-button>
    </template>
    <div class="jnpf-form-bottom-space p-[10px]" :style="{ margin: '0 auto', width: formConf.fullScreenWidth || '100%' }">
      <Parser
        ref="parserRef"
        :form-conf="formConf"
        :is-preview="state.config.isPreview"
        :model-id="state.config.modelId"
        @review-status-change="state.reviewPassed = $event"
        @review-visibility-change="state.reviewVisible = $event"
        @runtime-change="handleFormRuntimeChange"
        @submit="submitForm"
        :key="key"
        v-if="!loading" />
    </div>
  </BasicPopup>
  <CustomForm ref="customFormRef" />
</template>