zhou zhou
10 小时以前 450c9d39c6eb3765642f977512202e3240ac9b03
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
<template>
  <div class="loc-revise-page art-full-height">
    <ArtSearchBar
      v-model="searchForm"
      :items="searchItems"
      :showExpand="true"
      @search="handleSearch"
      @reset="handleReset"
    />
 
    <ElCard class="art-table-card">
      <ArtTableHeader v-model:columns="columnChecks" :loading="loading" @refresh="loadPageData">
        <template #left>
          <ElSpace wrap>
            <ElButton v-auth="'add'" @click="showDialog('add')" v-ripple>新增库存调整</ElButton>
            <ElButton
              v-auth="'delete'"
              type="danger"
              :disabled="selectedRows.length === 0"
              @click="handleBatchDelete"
              v-ripple
            >
              批量删除
            </ElButton>
            <span v-auth="'list'" class="inline-flex">
              <ListExportPrint
                :preview-visible="previewVisible"
                @update:previewVisible="handlePreviewVisibleChange"
                :report-title="reportTitle"
                :selected-rows="selectedRows"
                :query-params="reportQueryParams"
                :columns="columns"
                :preview-rows="previewRows"
                :preview-meta="resolvedPreviewMeta"
                :total="pagination.total"
                :disabled="loading"
                @export="handleExport"
                @print="handlePrint"
              />
            </span>
          </ElSpace>
        </template>
      </ArtTableHeader>
 
      <ArtTable
        :loading="loading"
        :data="tableData"
        :columns="columns"
        :pagination="pagination"
        @selection-change="handleSelectionChange"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      />
 
      <LocReviseDialog
        v-model:visible="dialogVisible"
        :loc-revise-data="currentLocReviseData"
        :area-options="areaOptions"
        @submit="handleDialogSubmit"
      />
 
      <LocReviseDetailDrawer
        v-model:visible="detailDrawerVisible"
        :loading="detailLoading"
        :summary="detailData"
        :log-loading="logLoading"
        :log-data="logTableData"
        :log-columns="logColumns"
        :log-pagination="logPagination"
        :item-loading="itemLoading"
        :item-data="itemTableData"
        :item-columns="itemColumns"
        :item-pagination="itemPagination"
        :active-log="activeLog"
        @log-size-change="handleLogSizeChange"
        @log-current-change="handleLogCurrentChange"
        @item-size-change="handleItemSizeChange"
        @item-current-change="handleItemCurrentChange"
      />
    </ElCard>
  </div>
</template>
 
<script setup>
  import { computed, h, onMounted, reactive, ref } from 'vue'
  import { ElButton, ElMessage, ElMessageBox, ElTag } from 'element-plus'
  import { useUserStore } from '@/store/modules/user'
  import { useAuth } from '@/hooks/core/useAuth'
  import { useTableColumns } from '@/hooks/core/useTableColumns'
  import { defaultResponseAdapter } from '@/utils/table/tableUtils'
  import { guardRequestWithMessage } from '@/utils/sys/requestGuard'
  import { useCrudPage } from '@/views/system/common/useCrudPage'
  import { usePrintExportPage } from '@/views/system/common/usePrintExportPage'
  import ListExportPrint from '@/components/biz/list-export-print/index.vue'
  import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
  import {
    fetchCompleteLocRevise,
    fetchExportLocReviseReport,
    fetchGetLocReviseDetail,
    fetchGetLocReviseMany,
    fetchLocRevisePage,
    fetchReviseLogItemPage,
    fetchReviseLogPage,
    fetchSaveLocRevise,
    fetchUpdateLocRevise,
    fetchDeleteLocRevise,
    fetchWarehouseAreasList
  } from '@/api/loc-revise'
  import LocReviseDialog from './modules/loc-revise-dialog.vue'
  import LocReviseDetailDrawer from './modules/loc-revise-detail-drawer.vue'
  import { createLocReviseTableColumns } from './locReviseTable.columns'
  import {
    buildLocReviseDialogModel,
    buildLocRevisePageQueryParams,
    buildLocRevisePrintRows,
    buildLocReviseReportMeta,
    buildLocReviseSavePayload,
    buildLocReviseSearchParams,
    buildReviseLogItemPageQueryParams,
    buildReviseLogPageQueryParams,
    createLocReviseFormState,
    createLocReviseSearchState,
    getLocReviseExceStatusOptions,
    getLocReviseTypeOptions,
    LOC_REVISE_REPORT_STYLE,
    LOC_REVISE_REPORT_TITLE,
    normalizeLocReviseRow,
    normalizeReviseLogItemRow,
    normalizeReviseLogRow,
    resolveWarehouseAreaOptions
  } from './locRevisePage.helpers'
 
  defineOptions({ name: 'LocRevise' })
 
  const { hasAuth } = useAuth()
  const userStore = useUserStore()
  const reportTitle = LOC_REVISE_REPORT_TITLE
  const loading = ref(false)
  const tableData = ref([])
  const searchForm = ref(createLocReviseSearchState())
  const areaOptions = ref([])
  const detailDrawerVisible = ref(false)
  const detailLoading = ref(false)
  const detailData = ref({})
  const logLoading = ref(false)
  const logTableData = ref([])
  const itemLoading = ref(false)
  const itemTableData = ref([])
  const activeLog = ref({})
  let handleDeleteAction = null
 
  const pagination = reactive({ current: 1, size: 20, total: 0 })
  const logPagination = reactive({ current: 1, size: 20, total: 0 })
  const itemPagination = reactive({ current: 1, size: 20, total: 0 })
  const reportQueryParams = computed(() => buildLocReviseSearchParams(searchForm.value))
 
  const searchItems = computed(() => [
    {
      label: '关键字',
      key: 'condition',
      type: 'input',
      props: { clearable: true, placeholder: '请输入调整单号' }
    },
    {
      label: '调整单号',
      key: 'code',
      type: 'input',
      props: { clearable: true, placeholder: '请输入调整单号' }
    },
    {
      label: '调整类型',
      key: 'type',
      type: 'select',
      props: { clearable: true, options: getLocReviseTypeOptions() }
    },
    {
      label: '库区名称',
      key: 'areaName',
      type: 'input',
      props: { clearable: true, placeholder: '请输入库区名称' }
    },
    {
      label: '执行状态',
      key: 'exceStatus',
      type: 'select',
      props: {
        clearable: true,
        options: getLocReviseExceStatusOptions().map((item) => ({
          label: item.label,
          value: item.value
        }))
      }
    },
    {
      label: '开始时间',
      key: 'timeStart',
      type: 'date',
      props: { type: 'date', valueFormat: 'YYYY-MM-DD', placeholder: '请选择开始时间' }
    },
    {
      label: '结束时间',
      key: 'timeEnd',
      type: 'date',
      props: { type: 'date', valueFormat: 'YYYY-MM-DD', placeholder: '请选择结束时间' }
    }
  ])
 
  async function openDetail(row) {
    detailDrawerVisible.value = true
    detailLoading.value = true
    activeLog.value = {}
    itemTableData.value = []
    try {
      detailData.value = normalizeLocReviseRow(await fetchGetLocReviseDetail(row.id))
      logPagination.current = 1
      await loadLogData(row.id)
    } catch (error) {
      detailDrawerVisible.value = false
      detailData.value = {}
      ElMessage.error(error?.message || '获取库存调整详情失败')
    } finally {
      detailLoading.value = false
    }
  }
 
  async function openEditDialog(row) {
    try {
      currentLocReviseData.value = buildLocReviseDialogModel(await fetchGetLocReviseDetail(row.id))
      dialogVisible.value = true
      dialogType.value = 'edit'
    } catch (error) {
      ElMessage.error(error?.message || '获取库存调整详情失败')
    }
  }
 
  async function handleComplete(row) {
    try {
      await ElMessageBox.confirm(`确定要完成库存调整单「${row.code || row.id}」吗?`, '完成确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await fetchCompleteLocRevise(row.id)
      await loadPageData()
      if (detailDrawerVisible.value && Number(detailData.value?.id) === Number(row.id)) {
        await openDetail(row)
      }
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error(error?.message || '完成库存调整失败')
      }
    }
  }
 
  const { columns, columnChecks } = useTableColumns(() =>
    createLocReviseTableColumns({
      handleView: openDetail,
      handleEdit: hasAuth('update') ? (row) => openEditDialog(row) : null,
      handleDelete: hasAuth('delete') ? (row) => handleDeleteAction?.(row) : null,
      handleComplete: hasAuth('update') ? (row) => handleComplete(row) : null
    })
  )
 
  const logColumns = computed(() => [
    { type: 'globalIndex', label: '序号', width: 72, align: 'center' },
    { prop: 'reviseCode', label: '调整单号', minWidth: 170, showOverflowTooltip: true },
    { prop: 'locCode', label: '库位编码', minWidth: 140, showOverflowTooltip: true },
    { prop: 'barcode', label: '库位条码', minWidth: 150, showOverflowTooltip: true },
    { prop: 'typeLabel', label: '库位类型', minWidth: 110 },
    { prop: 'useStatusLabel', label: '占用状态', minWidth: 110 },
    { prop: 'updateTimeText', label: '更新时间', minWidth: 170, showOverflowTooltip: true },
    {
      prop: 'operation',
      label: '操作',
      width: 110,
      align: 'right',
      formatter: (row) =>
        h(ArtButtonTable, {
          type: 'view',
          text: '查看明细',
          onClick: () => openLogItems(row)
        })
    }
  ])
 
  const itemColumns = computed(() => [
    { type: 'globalIndex', label: '序号', width: 72, align: 'center' },
    { prop: 'locCode', label: '库位编码', minWidth: 140, showOverflowTooltip: true },
    { prop: 'matnrCode', label: '物料编码', minWidth: 150, showOverflowTooltip: true },
    { prop: 'maktx', label: '物料名称', minWidth: 220, showOverflowTooltip: true },
    { prop: 'unit', label: '单位', width: 90 },
    { prop: 'anfme', label: '原库存', width: 100, align: 'right' },
    { prop: 'reviseQty', label: '调整数量', width: 100, align: 'right' },
    {
      prop: 'diffQty',
      label: '差异数量',
      width: 100,
      align: 'right',
      formatter: (row) =>
        h(
          ElTag,
          {
            type: Number(row.diffQty) === 0 ? 'info' : Number(row.diffQty) > 0 ? 'success' : 'danger',
            effect: 'light'
          },
          () => String(row.diffQty)
        )
    },
    { prop: 'batch', label: '批次', minWidth: 130, showOverflowTooltip: true },
    { prop: 'spec', label: '规格', minWidth: 130, showOverflowTooltip: true },
    { prop: 'model', label: '型号', minWidth: 130, showOverflowTooltip: true }
  ])
 
  function updatePaginationState(target, response, fallbackCurrent, fallbackSize) {
    target.total = Number(response?.total || 0)
    target.current = Number(response?.current || fallbackCurrent || 1)
    target.size = Number(response?.size || fallbackSize || target.size || 20)
  }
 
  async function loadAreaOptions() {
    const records = await guardRequestWithMessage(fetchWarehouseAreasList(), [], {
      timeoutMessage: '库区选项加载超时,已停止等待'
    })
    areaOptions.value = resolveWarehouseAreaOptions(records)
  }
 
  async function loadPageData() {
    loading.value = true
    try {
      const response = await guardRequestWithMessage(
        fetchLocRevisePage(
          buildLocRevisePageQueryParams({
            ...searchForm.value,
            current: pagination.current,
            pageSize: pagination.size
          })
        ),
        { records: [], total: 0, current: pagination.current, size: pagination.size },
        { timeoutMessage: '库存调整加载超时,已停止等待' }
      )
      tableData.value = Array.isArray(response?.records)
        ? response.records.map((record) => normalizeLocReviseRow(record))
        : []
      updatePaginationState(pagination, response, pagination.current, pagination.size)
    } finally {
      loading.value = false
    }
  }
 
  async function loadLogData(reviseId = detailData.value?.id) {
    if (!reviseId) return
    logLoading.value = true
    try {
      const response = await guardRequestWithMessage(
        fetchReviseLogPage(
          buildReviseLogPageQueryParams({
            reviseId,
            current: logPagination.current,
            pageSize: logPagination.size
          })
        ),
        { records: [], total: 0, current: logPagination.current, size: logPagination.size },
        { timeoutMessage: '调整日志加载超时,已停止等待' }
      )
      logTableData.value = Array.isArray(response?.records)
        ? response.records.map((record) => normalizeReviseLogRow(record))
        : []
      updatePaginationState(logPagination, response, logPagination.current, logPagination.size)
 
      if (logTableData.value.length > 0) {
        const nextActiveLog = activeLog.value?.id
          ? logTableData.value.find((item) => Number(item.id) === Number(activeLog.value.id))
          : logTableData.value[0]
        if (nextActiveLog) {
          await openLogItems(nextActiveLog, { silent: true })
        }
      } else {
        activeLog.value = {}
        itemTableData.value = []
        itemPagination.total = 0
      }
    } finally {
      logLoading.value = false
    }
  }
 
  async function openLogItems(row, options = {}) {
    activeLog.value = row || {}
    itemPagination.current = 1
    await loadLogItemsData(options)
  }
 
  async function loadLogItemsData(options = {}) {
    if (!activeLog.value?.id) {
      itemTableData.value = []
      return
    }
    itemLoading.value = true
    try {
      const response = await guardRequestWithMessage(
        fetchReviseLogItemPage(
          buildReviseLogItemPageQueryParams({
            reviseLogId: activeLog.value.id,
            current: itemPagination.current,
            pageSize: itemPagination.size
          })
        ),
        { records: [], total: 0, current: itemPagination.current, size: itemPagination.size },
        { timeoutMessage: options.silent ? '' : '日志明细加载超时,已停止等待' }
      )
      itemTableData.value = Array.isArray(response?.records)
        ? response.records.map((record) => normalizeReviseLogItemRow(record))
        : []
      updatePaginationState(itemPagination, response, itemPagination.current, itemPagination.size)
    } finally {
      itemLoading.value = false
    }
  }
 
  function handleSearch(params) {
    searchForm.value = { ...searchForm.value, ...params }
    pagination.current = 1
    loadPageData()
  }
 
  function handleReset() {
    searchForm.value = createLocReviseSearchState()
    pagination.current = 1
    pagination.size = 20
    loadPageData()
  }
 
  function handleSizeChange(size) {
    pagination.size = size
    pagination.current = 1
    loadPageData()
  }
 
  function handleCurrentChange(current) {
    pagination.current = current
    loadPageData()
  }
 
  function handleLogSizeChange(size) {
    logPagination.size = size
    logPagination.current = 1
    loadLogData()
  }
 
  function handleLogCurrentChange(current) {
    logPagination.current = current
    loadLogData()
  }
 
  function handleItemSizeChange(size) {
    itemPagination.size = size
    itemPagination.current = 1
    loadLogItemsData()
  }
 
  function handleItemCurrentChange(current) {
    itemPagination.current = current
    loadLogItemsData()
  }
 
  const {
    dialogVisible,
    dialogType,
    currentRecord: currentLocReviseData,
    selectedRows,
    handleSelectionChange,
    showDialog,
    handleDialogSubmit,
    handleDelete,
    handleBatchDelete
  } = useCrudPage({
    createEmptyModel: () => createLocReviseFormState(),
    buildEditModel: (record) => buildLocReviseDialogModel(record),
    buildSavePayload: (formData) => buildLocReviseSavePayload(formData),
    saveRequest: fetchSaveLocRevise,
    updateRequest: fetchUpdateLocRevise,
    deleteRequest: fetchDeleteLocRevise,
    entityName: '库存调整',
    resolveRecordLabel: (record) => record?.code || record?.id,
    refreshCreate: loadPageData,
    refreshUpdate: loadPageData,
    refreshRemove: loadPageData
  })
  handleDeleteAction = handleDelete
 
  const {
    previewVisible,
    previewRows,
    previewMeta,
    handlePreviewVisibleChange,
    handleExport,
    handlePrint
  } = usePrintExportPage({
    downloadFileName: 'loc-revise.xlsx',
    requestExport: (payload) =>
      fetchExportLocReviseReport(payload, {
        headers: { Authorization: userStore.accessToken || '' }
      }),
    resolvePrintRecords: async (payload) => {
      if (Array.isArray(payload?.ids) && payload.ids.length > 0) {
        return defaultResponseAdapter(await fetchGetLocReviseMany(payload.ids)).records
      }
      return defaultResponseAdapter(
        await fetchLocRevisePage({
          ...reportQueryParams.value,
          current: 1,
          pageSize: Number(pagination.total) > 0 ? Number(pagination.total) : Number(payload?.pageSize) || 20
        })
      ).records
    },
    buildPreviewRows: (records) => buildLocRevisePrintRows(records),
    buildPreviewMeta: (rows) => {
      const now = new Date()
      return {
        reportTitle,
        reportDate: now.toLocaleDateString('zh-CN'),
        printedAt: now.toLocaleString('zh-CN', { hour12: false }),
        operator: userStore.getUserInfo?.name || userStore.getUserInfo?.username || '',
        count: rows.length,
        reportStyle: { ...LOC_REVISE_REPORT_STYLE }
      }
    }
  })
 
  const resolvedPreviewMeta = computed(() =>
    buildLocReviseReportMeta({
      previewMeta: previewMeta.value,
      count: previewRows.value.length,
      orientation: previewMeta.value?.reportStyle?.orientation || LOC_REVISE_REPORT_STYLE.orientation
    })
  )
 
  onMounted(async () => {
    await loadAreaOptions()
    await loadPageData()
  })
</script>