Ben Lin
2024-10-24 5a813f3b28f3cbf1db3a3657ccf83267c6e0d315
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
<template>
  <BasicModal
    :width="width"
    :height="750"
    v-bind="$attrs"
    @register="register"
    :title="title"
    @ok="handleSubmit"
  >
    <div>
      <BasicTable @register="registerTable" @edit-change="onEditChange">
        <template #toolbar>
          <a-button @click="openImg" type="primary"> 预览 </a-button>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <TableAction :actions="createActions(record)" />
          </template>
        </template>
      </BasicTable>
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { FormSchema } from '/@/components/Form/index';
  import {
    BasicTable,
    BasicColumn,
    TableAction,
    useTable,
    EditRecordRow,
    ActionItem,
  } from '/@/components/Table';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { createImgPreview } from '/@/components/Preview';
  import { DeleteEntity, getListByPage, SaveEntity } from '/@/api/tigerapi/system';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { cloneDeep, isFunction } from 'lodash-es';
  import { isNullOrEmpty, isNullOrUnDef } from '/@/utils/is';
  import { CustModalParams } from '/@/api/tigerapi/model/systemModel';
  import { EntityCustFunctionType } from '/@/api/tigerapi/model/basModel';
 
  const { t } = useI18n();
  const title = ref('');
  const tableName = ref('');
  const rowKey = ref('');
  const returnFieldName = ref('');
  const schemas = ref([] as FormSchema[]);
  const which = ref('');
  const width = ref('');
  const entityName = ref('');
  const ctype = ref('');
  const others = ref({});
 
  //列表
  const ItemColumns = ref([] as BasicColumn[]);
  const searchInfo = ref({});
 
  const emit = defineEmits(['success', 'register']);
  const [registerTable, { setProps, getDataSource, reload }] = useTable({
    title: '列表信息',
    api: getListByPage,
    searchInfo: searchInfo,
    columns: ItemColumns,
    scroll: { y: 600 },
    formConfig: {
      labelWidth: 140,
      schemas: schemas.value,
      // submitFunc: () => Search('BAS_LABEL_VAR_WO', data, args[0]), //自定义查询提交按钮的方法,触发查询提交事件
    },
    useSearchForm: false,
    showTableSetting: false,
    bordered: true,
    canResize: false,
    showIndexColumn: false,
    actionColumn: {
      width: 130,
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
    },
  });
  const { createMessage: msg } = useMessage();
  const currentEditKeyRef = ref('');
  const custImport = ref<any[]>([]);
  const EntityCustFunction = ref([
    {
      ActionItem(params, data, ...args) {},
      KeyFieldValues(val, id) {},
      OpenSelectItem(openItemModal: Fn, ...args) {},
      GetSelectSuccess(d, u, ...args) {},
      GetUseForm(...args) {},
      CustFunc(param: CustModalParams) {},
    } as EntityCustFunctionType,
  ]);
  const [register, { setModalProps, closeModal }] = useModalInner((data) => {
    setModalProps({ confirmLoading: false });
    setProps({
      dataSource: [],
    });
    data && onDataReceive(data);
  });
 
  const imgList: any[] = []; //['http://localhost:8800/files/Template/10位批次条码.png'];
  function openImg() {
    let dataSource: any[] = getDataSource();
    const onImgLoad = ({ index, url, dom }) => {
      console.log(`第${index + 1}张图片已加载,URL为:${url}`, dom);
    };
    // 可以使用createImgPreview返回的 PreviewActions 来控制预览逻辑,实现类似幻灯片、自动旋转之类的骚操作
    const Keys = Object.getOwnPropertyNames(others.value);
    let path = '';
    dataSource.map((item) => {
      for (const k in Keys) {
        if (item[Keys[k]] == others.value[Keys[k]] && !isNullOrEmpty(others.value[Keys[k]])) {
          path = item['LABEL_VIEW_PATH'];
          return;
        }
      }
    });
    if(isNullOrEmpty(path)){
      path = dataSource.filter((q) => isNullOrEmpty(q.WORK_ORDER) || isNullOrEmpty(q.PROD_CODE))[0].LABEL_VIEW_PATH;
    }
    createImgPreview({
      imageList: [path],
      defaultWidth: 700,
      rememberState: true,
      onImgLoad,
    });
  }
 
  async function onDataReceive(data) {
    currentEditKeyRef.value = '';
    console.log('Data Received', data);
    // 方式1;
    // setFieldsValue({
    //   field2: data.data,
    //   field1: data.info,
    // });
    searchInfo.value = data?.searchInfo;
    title.value = data?.title;
    schemas.value = data?.schemas;
    ItemColumns.value = data?.ItemColumns;
    width.value = data?.width; //弹框宽度
    tableName.value = data?.tableName;
    rowKey.value = data?.rowKey;
    returnFieldName.value = data?.returnFieldName;
    which.value = data?.which;
    entityName.value = data?.entityName;
    ctype.value = data?.ctype;
    others.value = data?.others;
    // getForm().resetFields();
    /* 动态import实体名.ts的自定义方法 */
    try {
      custImport.value = await import(
        `../tigerprojects/system/lowcode/entityts/${entityName.value}.ts`
      );
    } catch (e) {}
    reload();
  }
 
  /**
   * @description: 编辑行
   * @param {*} record
   * @return {*}
   */
  function handleEdit(record: EditRecordRow) {
    currentEditKeyRef.value = record.key;
    record.onEdit?.(true);
  }
 
  /**
   * @description: 删除行
   * @param {*} record
   * @return {*}
   */
  function handleDel(record: EditRecordRow) {
    if (!isNullOrEmpty(record.WORK_ORDER) || !isNullOrEmpty(record.PROD_CODE)) {
      //删除
      DeleteEntity(record, ctype.value).then((action) => {
        if (action.IsSuccessed) {
          try {
            const data = cloneDeep(record.editValueRefs);
            console.log(data);
            //TODO 此处将数据提交给服务器保存
            const [{ CustFunc }] = isNullOrUnDef(custImport.value['default'])
              ? EntityCustFunction.value
              : custImport.value['default']();
            if (CustFunc && isFunction(CustFunc)) {
              CustFunc({
                others: others.value,
                ctype: 'delete',
                values: record,
              });
            }
          } catch (error) {
            msg.error({ content: t('删除失败'), key: 'saving' });
          }
          reload();
        }
      });
    } else {
      msg.error({ content: t('没有需要删除的变量'), key: 'saving' });
    }
  }
 
  /**
   * @description: 取消编辑
   * @param {*} record
   * @return {*}
   */
  function handleCancel(record: EditRecordRow) {
    currentEditKeyRef.value = '';
    record.onEdit?.(false, false);
  }
 
  /**
   * @description: 生成按钮
   * @param {*} record
   * @return {*}
   */
  function createActions(record: EditRecordRow): ActionItem[] {
    if (!record.editable) {
      return [
        {
          label: '编辑',
          disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
          onClick: handleEdit.bind(null, record),
          name: '',
        },
        {
          label: '删除',
          color: 'error',
          disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
          onClick: handleDel.bind(null, record),
          name: '',
        },
      ];
    }
    return [
      {
        label: '保存',
        onClick: handleSave.bind(null, record),
        name: '',
      },
      {
        label: '取消',
        popConfirm: {
          title: '是否取消编辑',
          confirm: handleCancel.bind(null, record),
        },
        name: '',
      },
    ];
  }
 
  /**
   * @description: 保存操作
   * @param {*} record
   * @return {*}
   */
  async function handleSave(record: EditRecordRow) {
    // 校验
    msg.loading({ content: '正在保存...', duration: 0, key: 'saving' });
    const valid = await record.onValid?.();
    if (valid) {
      try {
        const data = cloneDeep(record.editValueRefs);
        console.log(data);
        //TODO 此处将数据提交给服务器保存
        const [{ CustFunc }, ActionColumn] = isNullOrUnDef(custImport.value['default'])
          ? EntityCustFunction.value
          : custImport.value['default']();
        if (CustFunc && isFunction(CustFunc)) {
          CustFunc({
            others: others.value,
            ctype: ctype.value,
            values: record,
          });
        } else {
          /* 默认保存方法 */
          const action = await SaveEntity(
            record,
            true,
            unref(entityName),
            // `${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' });
    }
  }
 
  /**
   * @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: 完成提交
   * @return {*}
   */
  async function handleSubmit() {
    try {
      var values = '';
      var ids = '';
      closeModal();
      emit('success', {
        isUpdate: unref(false),
        values: { val: values, id: ids },
        returnFieldName: returnFieldName.value,
        which: which.value,
      });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>