Ben Lin
2025-03-07 ce374a9f4920a2d0e5ebe81a9872436088db6d55
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
<template>
  <div>
    <a-card
      :title="GetTitle()['tableTitle'][item.name]"
      :bordered="false"
      class="!mt-5"
      v-for="(item, index) in drawers"
    >
      <BasicTable
        @register="useTables[item.name]"
        :beforeEditSubmit="
          ({ record, index, key, value }) =>
            beforeEditSubmit({ record, index, key, value }, item.name)
        "
        @edit-end="
          ({ record, index, key, value }) => handleEditEnd({ record, index, key, value }, item.name)
        "
        @edit-change="onEditChange"
      >
        <template #toolbar>
          <a-button
            v-if="item.showTbButton"
            type="primary"
            v-for="d in buttons.filter((m) => m['BUTTON_TYPE'] == 0)"
            @click="handleCreate(index, item, d)"
            :preIcon="d['ICON_URL']"
            :key="d"
          >
            {{ d['FUNC_NAME'] }}
          </a-button>
          <!-- <a-button v-if="item.showTbButton" @click="openImg" type="primary"> 预览 </a-button> -->
        </template>
        <template #action="{ record }">
          <TableAction :actions="createActions(record, index, item)" />
        </template>
        <template #[item]="{ field }" v-for="item in colSlots" :key="item">
          <a-button
            v-if="field"
            class="mt-1 ml-1"
            size="small"
            @click="handleSelectItem(item)"
            preIcon="search|svg"
          />
          <GeneralModal
            @register="registerItemAdd"
            @success="(d, u) => handleItemSuccess(d, u, item)"
          />
        </template>
      </BasicTable>
      <normalDrawer
        @register="useDrawers[index][item.name]"
        @success="(d, u) => handleSuccess(d, u, item.name)"
      />
    </a-card>
  </div>
</template>
<script lang="ts" setup>
  import { Ref, inject, onMounted, ref, unref, watch } from 'vue';
  import { BasicTable, EditRecordRow, TableAction } from '/@/components/Table';
  import GeneralModal from '/@/views/components/GeneralModal.vue';
  import normalDrawer from '../../normalDrawer.vue';
  import { isFunction, isNullOrEmpty, isNullOrUnDef } from '/@/utils/is';
  import { useModal } from '/@/components/Modal';
  import { useGo } from '/@/hooks/web/usePage';
  import { DeleteEntity, getEntity, SaveEntity } from '/@/api/tigerapi/system';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Card } from 'ant-design-vue';
  import { EntityCustFunctionType } from '/@/api/tigerapi/model/basModel';
  import { useRouter } from 'vue-router';
  import { getRoleButtons } from '/@/api/sys/menu';
  import { CustModalParams } from '/@/api/tigerapi/model/systemModel';
  import { useWebSocketStore } from '/@/store/modules/websocket';
  import { useTabs } from '/@/hooks/web/useTabs';
  import { cloneDeep } from 'lodash-es';
  import { useMessage } from '/@/hooks/web/useMessage';
 
  const { t } = useI18n();
  const ACard = Card;
  const emit = defineEmits(['search', 'opencust', 'gettables']);
  const props = defineProps({
    colSlots: { type: Array as PropType<any[]> },
    useTableData: { type: Object as PropType<{}>, default: { table: [] } },
    entityName: { type: String },
    crudColSlots: { type: Object as PropType<any> },
  });
  /* 主页面注入的变量 */
  const objParams = inject('objParams') as Ref<any>;
  const data = inject('data') as Ref<any>;
  const _useTables = inject('useTables') as Ref<any>;
  const useFormData = inject('useFormData') as Ref<{}>;
  const keyFieldValues = inject('keyFieldValues') as Ref<Recordable[]>;
  const others = ref({});
  const ctype = ref('');
  const { createMessage: msg } = useMessage();
 
  const go = useGo();
  const { currentRoute } = useRouter();
  const [registerItemAdd, { openModal: openItemModal }] = useModal();
  const currentEditKeyRef = ref('');
  const custImport = ref<any[]>([]);
  const EntityCustFunction = ref([
    {
      ActionItem() {},
      EditOperation() {},
      GetCrudForm() {},
      KeyFieldValues() {},
      GetTitle() {},
      GetUseTables() {},
      GetUseDrawers() {},
      CustInitData() {},
      GetNewRow() {},
      CreateAction() {},
      CustEditEnd() {},
    } as unknown as EntityCustFunctionType,
  ]);
  /* 动态import实体名.ts的自定义方法 */
  try {
    custImport.value = await import(`../../entityts/${props.entityName}.ts`);
  } catch (e) {}
  const [
    {
      EditOperation,
      GetCrudForm,
      KeyFieldValues,
      GetTitle,
      GetUseTables,
      GetUseDrawers,
      CustInitData,
      CreateAction,
      CustFunc,
      GetNewRow,
      CustEditEnd,
    },
  ] = isNullOrUnDef(custImport.value['default'])
    ? EntityCustFunction.value
    : custImport.value['default']();
  const buttons = ref<[]>(await getRoleButtons(currentRoute.value.meta.menuCode as string));
  keyFieldValues.value = KeyFieldValues(objParams.value['CODE'], objParams.value['ID']); //获取一些其他有需要提供的值,这里是主页面跳转过来时带的关键字段值
  const drawers = ref<any[]>(objParams.value['drawers']); //是右侧边框列表,里面的name表示是哪一个实体,也就是高级表单中表格的名字,很多方法需要以这个名字为key
  const useTables = GetUseTables(data, emit); //高级表单中各个表格(Table)的useTable方法实现列表
  const useDrawers = GetUseDrawers(); //高级表单中各个表格(Table)的右侧边框(Drawer)的useDrawer方法实现列表
  _useTables.value = useTables; //把useTable的列表响应到从主页面注入的_useTables,这样主页面能拿到useTable的结果,从而可以使用各个表格的内置方法
  const webSocketStore = useWebSocketStore();
  const { refreshPage } = useTabs();
  watch(
    () => webSocketStore.socketMessage,
    (newVal, oldVal) => {
      console.log(oldVal, newVal);
      /* 如果监听到的值不一样,则刷新页面 */
      if (
        newVal != oldVal &&
        !isNullOrEmpty(oldVal) &&
        newVal['Data'] == 'Content' &&
        newVal['IsSuccessed']
      ) {
        // init().then(() => {
        //   refreshPage();
        // });
      }
    },
    { deep: true, immediate: true },
  );
 
  /**
   * @description: 挂载组件完成时
   * @return {*}
   */
  onMounted(async () => {
    init();
  });
 
  /**
   * @description: 初始化数据
   * @return {*}
   */
  async function init() {
    for (const i in drawers.value) {
      let sqlcmd = ' 1 =1 ';
      if (!isNullOrEmpty(keyFieldValues.value[drawers.value[i].code])) {
        sqlcmd += ` And ${drawers.value[i].code} = '${keyFieldValues.value[drawers.value[i].code]}'`;
      }
      /* type: all-表示需要code的所有的值 */
      if (drawers.value[i]['type'] == 'all') {
        if (data.value[drawers.value[i]['keyName']].length > 0) {
          sqlcmd += ` And ${drawers.value[i]['code']} in (${data.value[drawers.value[i]['keyName']].map((value) => `'${value[drawers.value[i]['code']]}'`).join(',')})`;
        } else {
          sqlcmd = ' 1!=1 '; //新增的时候不查数据,查也没有
        }
      }
      const list = await getEntity({
        sqlcmd: sqlcmd,
        entityName: isNullOrEmpty(drawers.value[i].dataType)
          ? drawers.value[i].name
          : drawers.value[i].dataType,
        order: drawers.value[i].order,
      });
      if (!isNullOrEmpty(list.Data) && !isNullOrEmpty(list.Data.Items)) {
        data.value[drawers.value[i].name] = list.Data.Items;
        // 自定义初始化数据
        if (CustInitData && isFunction(CustInitData)) {
          CustInitData(data, keyFieldValues, drawers.value[i].name, useTables);
        }
        useTables[drawers.value[i].name][1].setProps({
          dataSource: [],
        });
        useTables[drawers.value[i].name][1].setProps({
          dataSource: data.value[drawers.value[i].name],
        });
        useTables[drawers.value[i].name][1].reload();
        emit('gettables', useTables);
      }
    }
  }
 
  const imgList = ['http://localhost:8800/files/Template/10位批次条码.png'];
 
  /**
   * @description: 生成列表中操作项的按钮
   * @param {*} record
   * @return {*}
   */
  function createActions(record, index, item) {
    if (!record.editable) {
      const values = useFormData.value['BaseForm'][1].getFieldsValue();
      const type = values['TEMP_TYPE'];
      return [
        {
          label: '编辑',
          disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
          onClick: handleEdit.bind(null, record),
          name: '',
        },
        {
          label: '删除',
          color: 'error',
          disabled:
            type == 0
              ? true
              : currentEditKeyRef.value
                ? currentEditKeyRef.value !== record.key
                : false,
          onClick: handleDel.bind(null, record, index, item),
          name: '',
        },
      ];
    }
    return [
      {
        label: '保存',
        onClick: handleSave.bind(null, record, index, item),
        name: '',
      },
      {
        label: '取消',
        popConfirm: {
          title: '是否取消编辑',
          confirm: handleCancel.bind(null, record, index, item),
        },
        name: '',
      },
    ];
  }
 
  /**
   * @description: 验证表单
   * @return {*}
   */
  async function validate() {
    let validates = {};
    const Keys = Object.getOwnPropertyNames(useFormData.value);
    let i;
    for (i = 0; i < Keys.length; i++) {
      validates[Keys[i]] = await useFormData.value[Keys[i]][1].validate();
    }
    return validates;
  }
 
  /**
   * @description: 打开抽屉方法
   * @param {*} index
   * @param {*} item
   * @return {*}
   */
  function CreateopenDrawer(index, item) {
    validate().then((res) => {
      const Keys = Object.getOwnPropertyNames(useFormData.value);
      for (const i in Keys) {
        keyFieldValues.value[item['code']] = objParams.value['IsID']
          ? res[Keys[i]]['ID']
          : res[Keys[i]][item['code']];
        console.log(i);
      }
      useDrawers[index][item['name']][1].openDrawer(true, {
        isUpdate: false,
        ifSave: objParams.value['ifSave'],
        entityName: item['name'], //props.entityName,
        // formJson: GetCrudForm(item, data), //获取增删改表单字段
        crudColSlots: props.crudColSlots,
        keyFieldValues: keyFieldValues.value,
        data,
        name: item['name'], //drawers列表里面的name,表示是哪一个实体,也就是高级表单中表格的名字
        keyName: item['keyName'],
      });
    });
  }
 
  /**
   * @description: 新增按钮方法
   * @param {*} index
   * @param {*} item
   * @return {*}
   */
  function handleCreate(index, item, d) {
    const _cruds = GetCrudForm();
    let isExistSql = '';
    for (const i in _cruds) {
      if (_cruds[i].isexist == 'Y') {
        isExistSql = _cruds[i].field;
      }
    }
 
    if (isNullOrUnDef(custImport.value['default'])) {
      CreateopenDrawer(index, item);
    } else {
      const result = CreateAction(item.name);
      /* 根据主页面跳转传过来的参数确定新增按钮的执行方法 */
      switch (result.action) {
        case 'go':
          sessionStorage.removeItem(`${result.params.Name}_update_params`);
          // 将对象转换为JSON字符串并保存到sessionStorage
          sessionStorage.setItem(
            `${result.params.Name}_update_params`,
            encodeURI(JSON.stringify(result.params)),
          );
          go(
            `/${result.url}/${encodeURI(JSON.stringify({ sName: `${result.params.Name}_update`, Name: result.params.Name }))}`,
          );
          break;
        case 'drawer':
          CreateopenDrawer(index, item);
          break;
        case 'edit':
          const params: CustModalParams = {
            mValues: {},
            others: keyFieldValues.value,
            cType: item.name,
            values: GetNewRow(item.name),
            initFnName: '',
            FnName: item.FnName,
            data: data,
          };
          /* 自定义方法 */
          CustFunc(params);
          useTables[item.name][1].setProps({
            dataSource: [],
          });
          useTables[item.name][1].setProps({
            dataSource: data.value[item.name],
          });
          useTables[item.name][1].reload();
          break;
      }
    }
  }
 
  /**
   * @description: 新增编辑返回成功方法
   * @param {*} d
   * @param {*} u
   * @param {*} item 页面上循环抽屉列表传入的实体名字,作为各表格相关方法的key,从而调用各表格相关的方法,如:useTables[item][1].setProps
   * @return {*}
   */
  function handleSuccess(d, u, item) {
    if (!isNullOrUnDef(custImport.value)) {
      /* 自定义编辑方法,根据实体名去调用 */
      EditOperation(data, d, u, item);
      useTables[item][1].setProps({
        dataSource: [],
      });
      useTables[item][1].setProps({
        dataSource: data.value[item],
      });
      useTables[item][1].reload();
    }
  }
 
  /**
   * @description: 弹出选择框选择成功后事件
   * @param {*} d
   * @param {*} u
   * @param {*} item 页面上循环抽屉列表传入的实体名字,作为各表格相关方法的key,从而调用各表格相关的方法,如:useTables[item][1].getForm()
   * @return {*}
   */
  function handleItemSuccess(d, u, item) {
    /* 动态import实体名.ts的自定义方法 */
    try {
      import(
        `../entityts/${useTables[item][1].getForm().getFieldsValue()[`${item.replace(/form-/, '').replace(/add/, '')}PSelect_0`]}.ts`
      )
        .then((m) => {
          const [{ GetSelectSuccess }] = m.default();
          useTables[item][1].getForm().setFieldsValue(GetSelectSuccess(d, u));
        })
        .catch(() => {
          useTables[item][1].getForm().setFieldsValue({
            ITEM_CODE: d.values['val'],
          });
        });
    } catch (e) {}
  }
 
  /**
   * @description: 弹出选择框
   * @param {*} item
   * @return {*}
   */
  function handleSelectItem(item) {
    /* 动态import实体名.ts的自定义方法 */
    try {
      import(
        `../entityts/${props.useTableData['table'][1].getForm().getFieldsValue()[`${item.replace(/form-/, '').replace(/add/, '')}PSelect_0`]}.ts`
      )
        .then((m) => {
          const [{ OpenSelectItem }] = m.default();
          OpenSelectItem(openItemModal);
        })
        .catch(() => {
          openItemModal(true, {
            title: '物料列表',
            schemas: [
              {
                field: 'ITEM_CODE',
                component: 'Input',
                label: '物料编码',
                colProps: {
                  span: 12,
                },
              },
            ],
            ItemColumns: [
              {
                title: t('物料编码'),
                dataIndex: 'ITEM_CODE',
                resizable: true,
                sorter: true,
                width: 200,
              },
              {
                title: t('物料名称'),
                dataIndex: 'ITEM_NAME',
                resizable: true,
                sorter: true,
                width: 180,
              },
            ],
            tableName: 'BAS_ITEM',
            rowKey: 'ITEM_CODE',
            searchInfo: { TABLE_NAME: 'BAS_ITEM' },
          });
        });
    } catch (e) {}
  }
 
  /**
   * @description: 单元格编辑完成后事件
   * @param {*} record
   * @param {*} index
   * @param {*} key
   * @param {*} value
   * @param {*} name
   * @return {*}
   */
  function handleEditEnd({ record, index, key, value }: Recordable, name) {
    console.log(record, index, key, value);
    data.value[name][index] = record;
    /* 单元格编辑完成后如果有自定义方法,就调用 */
    if (CustEditEnd && isFunction(CustEditEnd)) {
      CustEditEnd({ record, index, key, value }, name, useTables, data);
    }
    return false;
  }
 
  /**
   * @description: 单元格提交事件
   * @param {*} record
   * @param {*} index
   * @param {*} key
   * @param {*} value
   * @param {*} name
   * @return {*}
   */
  async function beforeEditSubmit({ record, index, key, value }, name) {
    console.log('单元格数据正在准备提交', { record, index, key, value });
    return true;
  }
 
  /**
   * @description: 编辑改变时事件
   * @param {*} column
   * @param {*} value
   * @param {*} record
   * @return {*}
   */
  function onEditChange({ column, value, record }) {
    // 本例
    if (column.dataIndex === 'id') {
      record.editValueRefs.name4.value = `${value}`;
    }
    console.log(column, value, record);
  }
 
  /**
   * @description: 编辑行
   * @param {*} record
   * @return {*}
   */
  function handleEdit(record: EditRecordRow) {
    currentEditKeyRef.value = record.key;
    record.onEdit?.(true);
  }
 
  /**
   * @description: 删除行
   * @param {*} record
   * @return {*}
   */
  function handleDel(record: EditRecordRow, index, item) {
    data.value[item.name] = data.value[item.name].filter((q) => q.ID != record.ID);
    useTables[item.name][1].setProps({
      dataSource: [],
    });
    useTables[item.name][1].setProps({
      dataSource: data.value[item.name],
    });
    useTables[item.name][1].reload();
    // setData();
  }
 
  /**
   * @description: 取消编辑
   * @param {*} record
   * @return {*}
   */
  function handleCancel(record: EditRecordRow, index, item) {
    currentEditKeyRef.value = '';
    record.onEdit?.(false, false);
  }
 
  /**
   * @description: 保存操作
   * @param {*} record
   * @return {*}
   */
  async function handleSave(record: EditRecordRow, index, item) {
    // 校验
    msg.loading({ content: '正在保存...', duration: 0, key: 'saving' });
    const valid = await record.onValid?.();
    if (valid) {
      try {
        const _data = cloneDeep(record.editValueRefs);
        console.log(_data);
        //TODO 此处将数据提交给服务器保存
        if (CustFunc && isFunction(CustFunc)) {
          CustFunc({
            others: others.value,
            cType: item.name,
            values: record,
            data: data,
            FnName: 'SaveRow',
          });
        } else {
          /* 默认保存方法 */
          const action = await SaveEntity(
            record,
            true,
            item.name, //实体名
            // `${isExistSql.value}='${values[isExistSql.value]}'`,
          );
        }
        // 保存之后提交编辑状态
        const pass = await record.onEdit?.(false, true);
        if (pass) {
          currentEditKeyRef.value = '';
        }
        msg.success({ content: t('数据已暂存,要最终保存到数据库请提交'), key: 'saving' });
      } catch (error) {
        msg.error({ content: t('保存失败'), key: 'saving' });
      }
    } else {
      msg.error({ content: t('请填写正确的数据'), key: 'saving' });
    }
  }
</script>