2914 lines
91 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<div class="product-details">
<div class="header-actions">
<div class="left-actions">
<el-button size="small" type="primary" @click="openAddItemDialog">新增商品</el-button>
<el-button size="small" @click="openBatchImportDialog">批量导入商品</el-button>
<el-button
size="small"
type="danger"
:disabled="!canBatchDelete"
:loading="batchDeletingDetails"
@click="confirmBatchDeleteDetails"
>
批量删除
</el-button>
<el-button size="small" @click="loadProductData">刷新</el-button>
<el-radio-group v-model="matchFilter" size="small" class="match-filter-group">
<el-radio-button value="all">全部</el-radio-button>
<el-radio-button value="matched">已匹配</el-radio-button>
<el-radio-button value="unmatched">未匹配</el-radio-button>
</el-radio-group>
<!-- <el-button size="small" disabled>导出</el-button> -->
</div>
<div class="right-actions">
<!-- 可以在这里添加搜索框或其他操作 -->
</div>
</div>
<div class="left-col product-detail-table-wrap">
<upper-table
table-id="storage-receiving-product-detail"
:data="filteredTableData"
:columns="productquick"
:show-selection="true"
:selectable="canDeleteDetailRow"
:pagination="pagination"
:query-time="queryTime"
@selection-change="handleSelectionChange"
@row-click="handleRowClick"
@page-size-change="handlePageSizeChange"
@page-change="handlePageChange"
@row-contextmenu="handleContextMenu"
>
<template #column-images="{ row }">
<div class="image-slot" style="display: flex; gap: 4px; flex-wrap: wrap;">
<template v-if="row.images && row.images.length > 0">
<el-image
v-for="(img, index) in row.images"
:key="img.id || index"
style="width: 40px; height: 40px"
:src="img.url"
:preview-src-list="row.images.map((i: any) => i.url)"
:initial-index="index"
fit="cover"
preview-teleported
/>
</template>
<el-image
v-else-if="row.image"
style="width: 40px; height: 40px"
:src="row.image"
:preview-src-list="[row.image]"
fit="cover"
preview-teleported
/>
<span v-else>--</span>
</div>
</template>
<template #column-storage_status="{ row }">
<el-tag
:type="formatProductStorageStatus(row.storage_status).config.tagType"
size="small"
effect="light"
>
{{ formatProductStorageStatus(row.storage_status).text }}
</el-tag>
</template>
<template #column-match_status="{ row }">
<el-tag
:type="row.system_product_id ? 'success' : 'info'"
size="small"
effect="light"
>
{{ row.system_product_id ? '已匹配' : '未匹配' }}
</el-tag>
</template>
<template #column-actions="{ row }">
<div class="product-detail-row-actions">
<template v-if="!isRowReadOnly(row)">
<el-button
type="warning"
link
size="small"
@click.stop="openBindDialog(row)"
>
明细绑定
</el-button>
<el-button
type="primary"
link
size="small"
@click.stop="openEditDialog(row)"
>
编辑
</el-button>
<el-button
v-if="!isMatchedRow(row)"
type="primary"
link
size="small"
@click.stop="openAddDrawer(row)"
>
创建商品
</el-button>
<el-button
v-if="canDeleteDetailRow(row)"
type="danger"
link
size="small"
:loading="isDeletingRow(row)"
@click.stop="confirmDeleteDetail(row)"
>
删除
</el-button>
</template>
<span v-else class="readonly-op">--</span>
</div>
</template>
<template #column-product_name="{ row }">
<span>
{{ row.product_name }}
<span v-if="isExpired(row.expiry_date)" style="color: #f56c6c;">(已过期)</span>
</span>
</template>
<template #column-production_date="{ row }">
<span class="clickable-date-cell" :class="{ 'is-readonly': isRowReadOnly(row) }" @click.stop="handleDateCellClick(row)">
{{ row.production_date || '--' }}
</span>
</template>
<template #column-expiry_date="{ row }">
<span class="clickable-date-cell" :class="{ 'is-readonly': isRowReadOnly(row) }" @click.stop="handleDateCellClick(row)">
{{ row.expiry_date || '--' }}
</span>
</template>
<template #column-validity_period="{ row }">
{{ formatValidity(row.production_date, row.expiry_date) }}
</template>
</upper-table>
</div>
<!-- 添加商品抽屉(复用 stock add.vue) -->
<el-drawer v-model="addDrawerVisible" title="创建商品" :append-to-body="true" size="800px">
<AddProduct ref="addCompRef" :initialStore="addDrawerStore" :storeDisabled="true" />
</el-drawer>
<el-dialog v-model="dateDialogVisible" title="日期修改" align-center width="420px" append-to-body>
<el-form :model="dateForm" label-width="90px">
<el-form-item label="生产日期">
<el-date-picker
v-model="dateForm.production_date"
type="date"
value-format="YYYY-MM-DD"
placeholder="请选择生产日期"
style="width: 100%;"
/>
</el-form-item>
<el-form-item label="到期日期">
<el-date-picker
v-model="dateForm.expiry_date"
type="date"
value-format="YYYY-MM-DD"
placeholder="请选择到期日期"
style="width: 100%;"
/>
</el-form-item>
</el-form>
<template #footer>
<el-button @click="dateDialogVisible = false">取消</el-button>
<el-button type="primary" :loading="dateSaving" @click="submitDateChange">保存</el-button>
</template>
</el-dialog>
<el-dialog v-model="editDialogVisible" :title="editDialogTitle" align-center width="760px" append-to-body>
<el-form :model="editForm" label-width="110px" size="small" class="edit-detail-form">
<el-row :gutter="12">
<el-col :span="6"><el-form-item><template #label>实际收货数量<span class="required-mark">*</span></template><el-input v-model="editForm.actual_quantity" clearable @input="handleQuantityLinkage('actual_quantity')" /></el-form-item></el-col>
<el-col :span="6"><el-form-item><template #label>箱数<span class="required-mark">*</span></template><el-input v-model="editForm.box_quantity" clearable @input="handleQuantityLinkage('box_quantity')" /></el-form-item></el-col>
<el-col :span="6"><el-form-item><template #label>箱规<span class="required-mark">*</span></template><el-input v-model="editForm.boxes_per_pallet" clearable @input="handleQuantityLinkage('boxes_per_pallet')" /></el-form-item></el-col>
<el-col :span="6"><el-form-item><template #label>剩余不满一箱<span class="required-mark">*</span></template><el-input v-model="editForm.box_remainder" clearable @input="handleQuantityLinkage('box_remainder')" /></el-form-item></el-col>
<el-col :span="12"><el-form-item label="托盘数"><el-input v-model="editForm.pallet_quantity" clearable /></el-form-item></el-col>
<el-col :span="12">
<el-form-item>
<template #label>批次号<span v-if="hasSkuSelected && isBatchManaged" class="required-mark">*</span></template>
<el-input v-model="editForm.batch_number" clearable />
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item>
<template #label>生产日期<span v-if="hasSkuSelected && isShelfLifeManaged" class="required-mark">*</span></template>
<el-date-picker
v-model="editForm.production_date"
type="date"
value-format="YYYY-MM-DD"
style="width:100%"
@change="onEditProductionDateChange"
/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item>
<template #label>到期日期<span v-if="hasSkuSelected && isShelfLifeManaged" class="required-mark">*</span></template>
<el-date-picker
v-model="editForm.expiry_date"
type="date"
value-format="YYYY-MM-DD"
style="width:100%"
@change="onEditExpiryDateChange"
/>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="库位">
<el-input :model-value="spaceDisplayName" readonly>
<template #append>
<el-button @click="openSpacePicker">选择系统库位</el-button>
</template>
</el-input>
</el-form-item>
</el-col>
<el-col :span="12"><el-form-item label="毛重/重量(g)"><el-input-number v-model="editForm.weight" :min="0" :precision="0" :controls="false" style="width: 100%" /></el-form-item></el-col>
<el-col :span="12">
<el-form-item label="SKU">
<el-input v-model="editForm.system_product_id" readonly>
<template #append>
<el-button @click="openEditSystemProductPicker">查询系统商品</el-button>
</template>
</el-input>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item>
<template #label>条码<span v-if="!hasSkuSelected" class="required-mark">*</span></template>
<el-input v-model="editForm.barcode" clearable :disabled="hasSkuSelected" />
</el-form-item>
</el-col>
<el-col :span="24">
<el-form-item>
<template #label>商品名称<span v-if="!hasSkuSelected" class="required-mark">*</span></template>
<el-input v-model="editForm.product_name" clearable :disabled="hasSkuSelected" />
</el-form-item>
</el-col>
<el-col :span="12"><el-form-item label="箱长"><el-input v-model="editForm.box_length" clearable /></el-form-item></el-col>
<el-col :span="12"><el-form-item label="箱宽"><el-input v-model="editForm.box_width" clearable /></el-form-item></el-col>
<el-col :span="12"><el-form-item label="箱高"><el-input v-model="editForm.box_height" clearable /></el-form-item></el-col>
<el-col :span="12"><el-form-item label="实测箱重(g)"><el-input-number v-model="editForm.box_weight" :min="0" :precision="0" :controls="false" style="width: 100%" /></el-form-item></el-col>
<el-col :span="24"><el-form-item label="备注"><el-input v-model="editForm.remark" type="textarea" :rows="3" clearable /></el-form-item></el-col>
</el-row>
</el-form>
<template #footer>
<el-button @click="editDialogVisible = false">取消</el-button>
<el-button type="primary" :loading="editSaving" @click="submitEditDetail">保存</el-button>
</template>
</el-dialog>
<el-dialog
v-model="bindDialogVisible"
title="明细绑定"
align-center
width="640px"
append-to-body
destroy-on-close
@closed="resetBindForm"
>
<el-form :model="bindForm" label-width="130px" size="small">
<el-form-item
v-for="field in bindDetailProductFormConfig"
:key="field.prop"
:required="field.required"
>
<template #label>{{ field.label }}</template>
<template v-if="field.type === 'display'">
<span class="bind-display-value">{{ formatBindDisplayValue(field.prop) }}</span>
</template>
<template v-else-if="field.type === 'product-picker'">
<div class="bind-product-picker">
<el-input :model-value="bindSelectedProductDisplay" readonly placeholder="请选择系统商品">
<template #append>
<el-button @click="openBindSystemProductPicker">查询系统商品</el-button>
</template>
</el-input>
<p v-if="field.hint" class="picker-hint">{{ field.hint }}</p>
</div>
</template>
</el-form-item>
</el-form>
<template #footer>
<el-button @click="bindDialogVisible = false">取消</el-button>
<el-button type="primary" :loading="bindSaving" @click="submitBindDetail">确认绑定</el-button>
</template>
</el-dialog>
<el-dialog v-model="systemProductPickerVisible" title="查询系统商品" align-center width="980px" append-to-body destroy-on-close>
<div class="system-product-picker">
<div class="picker-toolbar">
<el-input v-model="systemProductKeyword" placeholder="输入商品名称或条码" clearable style="width: 320px" @keyup.enter="querySystemProducts(1)">
<template #append>
<el-button :icon="Search" :loading="systemProductLoading" @click="querySystemProducts(1)">查询</el-button>
</template>
</el-input>
<span v-if="boundStoreId" class="picker-hint">已按收货单货主过滤:{{ boundStoreName || ('ID ' + boundStoreId) }}</span>
<span v-else class="picker-hint">当前收货单未绑定货主,查询不过滤货主</span>
</div>
<div class="picker-table-wrap">
<UpperTable
:data="systemProductResults"
:loading="systemProductLoading"
:show-selection="true"
:multiple-selection="systemProductSelection"
:pagination="{ currentPage: systemProductPagination.page, pageSize: systemProductPagination.pageSize, total: systemProductPagination.total }"
:columns="[
{ prop: 'id', label: '系统商品ID', width: '120' },
{ prop: 'item_name', label: '商品名称', minWidth: '220' },
{ prop: 'barcodes', label: '条码', width: '180' },
{ prop: 'store_name', label: '货主', width: '180' },
{ prop: 'weight', label: '重量(g)', width: '110', align: 'right' }
]"
@selection-change="handleSystemProductSelectionChange"
@row-click="handleSystemProductRowClick"
@page-change="querySystemProducts"
@page-size-change="onSystemProductPageSizeChange"
/>
</div>
</div>
<template #footer>
<el-button @click="systemProductPickerVisible = false">取消</el-button>
<el-button type="primary" @click="applySelectedSystemProduct">使用选中商品</el-button>
</template>
</el-dialog>
<el-dialog v-model="spacePickerVisible" title="选择系统库位" align-center width="900px" append-to-body destroy-on-close>
<div class="system-product-picker">
<div class="picker-toolbar">
<el-input v-model="spaceKeyword" placeholder="输入库位名称或编码" clearable style="width: 320px" @keyup.enter="querySpaces(1)">
<template #append>
<el-button :icon="Search" :loading="spaceLoading" @click="querySpaces(1)">查询</el-button>
</template>
</el-input>
</div>
<div class="picker-table-wrap">
<UpperTable
:data="spaceResults"
:loading="spaceLoading"
:show-selection="true"
:multiple-selection="spaceSelection"
:pagination="{ currentPage: spacePagination.page, pageSize: spacePagination.pageSize, total: spacePagination.total }"
:columns="[
{ prop: 'id', label: '库位ID', width: '120' },
{ prop: 'display_name', label: '显示名称', minWidth: '220' },
{ prop: 'space_name', label: '默认名称', minWidth: '220' },
{ prop: 'space_code', label: '库位编码', width: '180' }
]"
@selection-change="handleSpaceSelectionChange"
@row-click="handleSpaceRowClick"
@page-change="querySpaces"
@page-size-change="onSpacePageSizeChange"
/>
</div>
</div>
<template #footer>
<el-button @click="spacePickerVisible = false">取消</el-button>
<el-button type="primary" @click="applySelectedSpace">使用选中库位</el-button>
</template>
</el-dialog>
<el-dialog v-model="batchImportDialogVisible" title="批量导入商品" align-center width="1020px" append-to-body destroy-on-close>
<div class="batch-import-toolbar">
<input
ref="batchImportInputRef"
type="file"
accept=".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
style="display:none"
@change="onBatchImportFileChange"
/>
<el-button @click="triggerBatchImportSelect">选择Excel</el-button>
<el-button @click="downloadBatchImportTemplate">下载模板</el-button>
<el-button @click="clearBatchImportData">清除数据</el-button>
<el-button :loading="batchRetryFailedLoading" @click="retryFailedBatchRows">只重试失败</el-button>
<el-button type="primary" :loading="batchImportLoading" @click="submitBatchImportCreate">导入</el-button>
<span class="picker-hint">已选文件:{{ batchImportFileName || '未选择' }}</span>
</div>
<div class="picker-table-wrap">
<UpperTable
:data="batchImportPreviewRows"
:show-selection="false"
:pagination="{ currentPage: 1, pageSize: 200, total: batchImportPreviewRows.length }"
:columns="[
{ prop: 'row_no', label: '行号', width: '80' },
{ prop: 'system_product_id', label: 'SKU', width: '120' },
{ prop: 'barcode', label: '条码', width: '160' },
{ prop: 'product_name', label: '商品名称', minWidth: '180' },
{ prop: 'actual_quantity', label: '实际收货数量', width: '120' },
{ prop: 'box_quantity', label: '箱数', width: '90' },
{ prop: 'boxes_per_pallet', label: '箱规', width: '90' },
{ prop: 'box_remainder', label: '剩余不满一箱', width: '130' },
{ prop: 'space_keyword', label: '库位条码或名称', width: '160' },
{ prop: 'import_status', label: '状态', width: '100' },
{ prop: 'import_message', label: '结果说明', minWidth: '200' },
{ prop: 'retry_action', label: '操作', width: '140' },
{ prop: 'remark', label: '备注', minWidth: '180' }
]"
>
<template #column-system_product_id="{ row }">
<div class="batch-cell-action">
<span>{{ row.system_product_id || '--' }}</span>
<el-button type="primary" link size="small" @click="openBatchRowSkuPicker(row)">选择商品</el-button>
</div>
</template>
<template #column-space_keyword="{ row }">
<div class="batch-cell-action">
<span>{{ row.space_keyword || '--' }}</span>
<el-button type="primary" link size="small" @click="openBatchRowSpacePicker(row)">选择库位</el-button>
</div>
</template>
<template #column-retry_action="{ row }">
<el-button v-if="row.import_status === '失败'" type="primary" link size="small" @click="retryBatchImportRow(row)">重试</el-button>
<span v-else>--</span>
</template>
</UpperTable>
</div>
<div class="batch-import-summary">
已生成基础新增数组:{{ batchImportAddItems.length }} 条
</div>
<template #footer>
<el-button @click="batchImportDialogVisible = false">关闭</el-button>
</template>
</el-dialog>
<!-- 右键菜单 -->
<div v-if="menuVisible" :style="{ top: menuTop + 'px', left: menuLeft + 'px' }" class="context-menu">
<div
v-if="currentRow && !isRowReadOnly(currentRow)"
class="menu-item"
@click="handleContextMenuBind"
>
明细绑定
</div>
<div class="menu-item" @click="handleProductDetail">货品详情</div>
</div>
<!-- 货品详情弹窗 -->
<div v-if="windowVisible" class="product-window detail-window" :class="{ 'is-fullscreen': isFullscreen }" :style="windowStyle">
<div class="window-header" @mousedown="startDrag">
<span class="window-title">货品详情 - {{ currentRow?.item_name }}</span>
<div class="window-actions">
<el-button link :icon="isFullscreen ? CopyDocument : FullScreen" @click="toggleFullscreen" :title="isFullscreen ? '还原' : '最大化'" />
<el-button link :icon="Close" @click="windowVisible = false" title="关闭" />
</div>
</div>
<div class="window-body">
<div class="window-tabs">
<div
v-for="tab in windowtopbar"
:key="tab.key"
class="tab-item"
:class="{ active: activeWindowTab === tab.key }"
@click="activeWindowTab = tab.key"
>
{{ tab.label }}
</div>
</div>
<div class="window-content">
<KeepAlive>
<component
:is="currentWindowComponent"
:row="currentRow"
ref="basicRef"
/>
</KeepAlive>
</div>
<div class="window-footer">
<el-button size="small" @click="resetForm" disabled>重置</el-button>
<el-button size="small" type="primary" @click="saveProductDetail" disabled>保存</el-button>
</div>
</div>
</div>
<!-- <aside class="right-col">
<div class="right-panel">
<div class="panel-actions">
<el-button disabled>重置</el-button>
<el-button type="primary" @click="handleSave" :loading="saveLoading" disabled>
保存
</el-button>
</div>
</div>
</aside> -->
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, reactive, watch } from 'vue'
import {
productdetail,
productquick,
productsnapshop,
windowtopbar,
formatProductStorageStatus,
bindDetailProductFormConfig
} from '../receiving-config'
import { ElMessage, ElMessageBox } from 'element-plus'
import { FullScreen, Close, CopyDocument, Search } from '@element-plus/icons-vue'
import UpperTable from '@/components/UpperTable/index.vue'
import AddProduct from '@/views/stock/stock/component/add.vue'
import * as receivingApi from '@/api/storage_receiving/receiving'
import * as stockApi from '@/api/stock/stock'
import * as indexApi from '@/api/index/index'
import * as warehouseApi from '@/api/warehouse/warehouse'
import { buildStockQuery } from '@/utils/stockQueryBuilder'
import * as XLSX from 'xlsx'
import basic from '../window/basic.vue'
import log from '../window/log.vue'
import product from '../window/product.vue'
const props = defineProps<{
id?: string | number,
productData?: any[],
loading?: boolean,
productTotal?: number,
row?: any
}>()
const tableData = ref<any[]>([])
const multipleSelection = ref<any[]>([])
const matchFilter = ref('all')
const filteredTableData = computed(() => {
if (matchFilter.value === 'matched') {
return tableData.value.filter(item => !!item.system_product_id)
} else if (matchFilter.value === 'unmatched') {
return tableData.value.filter(item => !item.system_product_id)
}
return tableData.value
})
const isMatchedRow = (row: any) => {
const status = String(row?.match_status || '').toLowerCase()
return !!row?.system_product_id || row?.is_matched === true || row?.is_matched === 1 || status === 'matched' || status === '已匹配'
}
const isReadOnlyStatus = (status: any) => {
const normalized = String(status || '').toLowerCase().trim()
return normalized === 'completed' || normalized === 'cancelled' || normalized === 'canceled' || normalized === '已完成' || normalized === '已作废'
}
/** 仅以收货单头状态判断是否只读;明细行的 status/receiving_status 为行级收货状态,不能用于禁用操作列 */
const isReceivingDocumentReadOnly = computed(() => {
return isReadOnlyStatus(props.row?.status || props.row?.receiving_status)
})
const isRowReadOnly = (_row?: any) => {
return isReceivingDocumentReadOnly.value
}
const getDetailIdFromRow = (row?: any) => {
const id = Number(row?.detail_id ?? row?.id)
if (!Number.isFinite(id) || id <= 0) return undefined
return id
}
const isRowNotStored = (row?: any) => {
const storageStatus = String(row?.storage_status ?? '').toLowerCase().trim()
if (!storageStatus) {
const storedQuantity = Number(row?.stored_quantity ?? row?.inbound_quantity ?? 0)
return !Number.isFinite(storedQuantity) || storedQuantity <= 0
}
if (storageStatus === 'waiting' || storageStatus === '待入库' || storageStatus === 'none' || storageStatus === '未入库') return true
if (storageStatus === 'all' || storageStatus === '全部入库' || storageStatus === 'partial' || storageStatus === '部分入库') {
return false
}
const storedQuantity = Number(row?.stored_quantity ?? row?.inbound_quantity ?? 0)
return !Number.isFinite(storedQuantity) || storedQuantity <= 0
}
const canDeleteDetailRow = (row?: any) => {
if (!row || isRowReadOnly(row)) return false
return isRowNotStored(row)
}
const showReadOnlyTip = () => {
ElMessage.warning('该收货单状态下商品明细为只读,不可操作')
}
const DAY_MS = 24 * 60 * 60 * 1000
const getDate = (value?: string) => {
if (!value) return null
const d = new Date(value)
return isNaN(d.getTime()) ? null : d
}
const isExpired = (expiryDate?: string) => {
const expiry = getDate(expiryDate)
if (!expiry) return false
return expiry.getTime() < Date.now()
}
const formatValidity = (productionDate?: string, expiryDate?: string) => {
const start = getDate(productionDate)
const end = getDate(expiryDate)
if (!start || !end) return '--'
const diff = Math.floor((end.getTime() - start.getTime()) / DAY_MS)
if (!Number.isFinite(diff)) return '--'
return `${diff}天`
}
const calcDiffYears = (start: Date, end: Date) => {
let years = end.getFullYear() - start.getFullYear()
const monthDiff = end.getMonth() - start.getMonth()
const dayDiff = end.getDate() - start.getDate()
if (monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)) {
years -= 1
}
return years
}
const calcDiffMonths = (start: Date, end: Date) => {
let months = (end.getFullYear() - start.getFullYear()) * 12 + (end.getMonth() - start.getMonth())
if (end.getDate() < start.getDate()) {
months -= 1
}
return months
}
// 分页相关
const pagination = reactive({
currentPage: 1,
pageSize: 20,
total: 0
})
const queryTime = ref(0)
// 监听外部数据变化
watch(() => props.productData, (newVal) => {
// 始终将父组件传入的数据同步到表格,空数组也应清空表格数据
if (Array.isArray(newVal)) {
tableData.value = [...newVal]
pagination.total = props.productTotal ?? newVal.length
} else {
tableData.value = []
pagination.total = props.productTotal ?? 0
}
}, { immediate: true })
const emit = defineEmits(['page-change', 'page-size-change', 'refresh-product'])
const handlePageSizeChange = (val: number) => {
pagination.pageSize = val
emit('page-size-change', val)
}
const handlePageChange = (val: number) => {
pagination.currentPage = val
emit('page-change', val)
}
const loadProductData = () => {
// 请求父组件刷新商品数据
emit('refresh-product')
}
const isDeletingRow = (row?: any) => {
const detailId = getDetailIdFromRow(row)
if (!detailId) return false
return deletingDetailId.value === detailId
}
const confirmBatchDeleteDetails = async () => {
if (isReceivingDocumentReadOnly.value) {
showReadOnlyTip()
return
}
const rowsToDelete = multipleSelection.value.filter((row) => canDeleteDetailRow(row))
if (!rowsToDelete.length) {
ElMessage.warning('请先选择可删除的未入库明细')
return
}
const detailIds = rowsToDelete
.map((row) => getDetailIdFromRow(row))
.filter((id): id is number => id !== undefined)
if (!detailIds.length) {
ElMessage.warning('缺少有效的收货明细ID')
return
}
try {
await ElMessageBox.confirm(
`确认删除选中的 ${detailIds.length} 条收货明细吗?删除后将回算统计数据。`,
'批量删除确认',
{
type: 'warning',
confirmButtonText: '确认删除',
cancelButtonText: '取消'
}
)
} catch {
return
}
batchDeletingDetails.value = true
let successCount = 0
let failCount = 0
let lastError = ''
try {
for (const detailId of detailIds) {
try {
const res: any = await receivingApi.deleteDetail({ detail_id: detailId })
if (res && (res.code === 200 || res.flag === 'success')) {
successCount += 1
} else {
failCount += 1
lastError = res?.message || '删除失败'
}
} catch (error) {
failCount += 1
lastError = '删除失败'
console.error('批量删除收货明细失败', error)
}
}
if (successCount > 0) {
multipleSelection.value = []
loadProductData()
}
if (failCount === 0) {
ElMessage.success(`已成功删除 ${successCount} 条明细`)
} else if (successCount === 0) {
ElMessage.error(lastError || `删除失败,共 ${failCount} 条`)
} else {
ElMessage.warning(`删除完成:成功 ${successCount} 条,失败 ${failCount} 条`)
}
} finally {
batchDeletingDetails.value = false
}
}
const confirmDeleteDetail = async (row: any) => {
if (isRowReadOnly(row)) {
showReadOnlyTip()
return
}
if (!isRowNotStored(row)) {
ElMessage.warning('仅未入库明细支持删除')
return
}
const detailId = getDetailIdFromRow(row)
if (!detailId) {
ElMessage.warning('缺少有效的收货明细ID')
return
}
try {
await ElMessageBox.confirm(
'确认删除该收货明细吗?删除后将回算统计数据。',
'删除确认',
{
type: 'warning',
confirmButtonText: '确认删除',
cancelButtonText: '取消'
}
)
} catch {
return
}
deletingDetailId.value = detailId
try {
const res: any = await receivingApi.deleteDetail({ detail_id: detailId })
if (res && (res.code === 200 || res.flag === 'success')) {
ElMessage.success(res?.message || '删除成功')
loadProductData()
} else {
ElMessage.error(res?.message || '删除失败')
}
} catch (error) {
console.error('删除收货明细失败', error)
ElMessage.error('删除收货明细失败')
} finally {
deletingDetailId.value = null
}
}
async function fetchReceivingDetail() {
try {
const params = {
id: props.id,
pagination: { page: pagination.currentPage, pageSize: pagination.pageSize }
}
const res: any = await receivingApi.getReceivingDetail(params)
if (res && res.code === 200 && res.data) {
const receivingData = res.data.receiving || {}
if (Array.isArray(receivingData.details)) {
tableData.value = receivingData.details
pagination.total = receivingData.pagination?.total || receivingData.details.length || 0
} else {
tableData.value = []
pagination.total = 0
}
} else {
tableData.value = []
pagination.total = 0
}
} catch (e) {
console.error('加载商品明细失败', e)
tableData.value = []
pagination.total = 0
ElMessage.error('加载商品明细失败')
}
}
// 监听 props.loading
watch(() => props.loading, (val) => {
if (!val && (!props.productData || props.productData.length === 0)) {
// tableData.value = [...mockProductData]
// pagination.total = mockProductData.length
}
})
// 监听 props.productTotal
watch(() => props.productTotal, (val) => {
if (val !== undefined) {
pagination.total = val
}
})
const handleRowClick = (row: any) => {
currentRow.value = row
}
// 标签页相关
const activeWindowTab = ref('basic')
const windowComponentMap: Record<string, any> = {
basic: basic,
// product: product,
logs: log
}
const currentWindowComponent = computed(() => windowComponentMap[activeWindowTab.value])
const basicRef = ref<any>(null)
// 右键菜单相关
const menuVisible = ref(false)
const menuTop = ref(0)
const menuLeft = ref(0)
const currentRow = ref<any>(null)
// 窗口控制
const windowVisible = ref(false)
const isFullscreen = ref(false)
const position = ref({ x: 350, y: 250 })
const isDragging = ref(false)
const dragOffset = ref({ x: 0, y: 0 })
// 添加商品抽屉
const addDrawerVisible = ref(false)
const addDrawerStore = ref<any>(null)
const addCompRef = ref<any>(null)
const dateDialogVisible = ref(false)
const dateSaving = ref(false)
const editingDateRow = ref<any>(null)
const dateForm = reactive({
production_date: '',
expiry_date: ''
})
const editDialogVisible = ref(false)
const editSaving = ref(false)
const editingDetailRow = ref<any>(null)
const editDialogMode = ref<'edit' | 'add'>('edit')
const bindDialogVisible = ref(false)
const bindSaving = ref(false)
const bindingDetailRow = ref<any>(null)
const systemProductPickerTarget = ref<'edit' | 'bind' | 'batch-sku'>('edit')
const bindForm = reactive({
detail_id: '',
product_name: '',
barcode: '',
current_system_product_id: '',
current_system_product_name: '',
system_product_id: '',
selected_product_name: '',
selected_barcode: ''
})
const editForm = reactive<any>({
actual_quantity: '',
batch_number: '',
production_date: '',
expiry_date: '',
shelf_life_days: '',
inbound_min_days: '',
box_quantity: '',
boxes_per_pallet: '',
pallet_quantity: '',
space_id: '',
remark: '',
system_product_id: '',
barcode: '',
product_name: '',
box_width: '',
box_height: '',
box_length: '',
box_remainder: '',
box_weight: '',
weight: '',
space_display_name: '',
is_shelf_life_mgmt: '',
is_batch_mgmt: ''
})
const systemProductPickerVisible = ref(false)
const systemProductLoading = ref(false)
const systemProductKeyword = ref('')
const systemProductResults = ref<any[]>([])
const systemProductSelection = ref<any[]>([])
const systemProductPagination = reactive({ page: 1, pageSize: 10, total: 0 })
const spacePickerVisible = ref(false)
const spaceLoading = ref(false)
const spaceKeyword = ref('')
const spaceResults = ref<any[]>([])
const spaceSelection = ref<any[]>([])
const spacePagination = reactive({ page: 1, pageSize: 10, total: 0 })
const batchImportDialogVisible = ref(false)
const batchImportLoading = ref(false)
const batchImportInputRef = ref<HTMLInputElement | null>(null)
const batchImportSourceFile = ref<File | null>(null)
const batchImportFileName = ref('')
const batchImportPreviewRows = ref<any[]>([])
const batchImportAddItems = ref<any[]>([])
const batchImportEditingRow = ref<any>(null)
const batchImportPickerMode = ref<'space' | 'sku' | ''>('')
const batchRetryFailedLoading = ref(false)
const deletingDetailId = ref<number | null>(null)
const batchDeletingDetails = ref(false)
const canBatchDelete = computed(() => {
if (isReceivingDocumentReadOnly.value) return false
return multipleSelection.value.some((row) => canDeleteDetailRow(row))
})
const spaceDisplayName = computed(() => {
return String(editForm.space_display_name || '').trim() || (String(editForm.space_id || '').trim() ? `ID ${editForm.space_id}` : '')
})
const hasSkuSelected = computed(() => {
return String(editForm.system_product_id ?? '').trim() !== ''
})
const editDialogTitle = computed(() => (editDialogMode.value === 'add' ? '新增商品明细' : '编辑收货明细'))
const toBoolFlag = (val: any) => {
if (val === null || val === undefined || val === '') return false
if (typeof val === 'boolean') return val
if (typeof val === 'number') return val === 1
const normalized = String(val).trim().toLowerCase()
return normalized === '1' || normalized === 'y' || normalized === 'yes' || normalized === 'true' || normalized === '是'
}
const isShelfLifeManaged = computed(() => toBoolFlag(editForm.is_shelf_life_mgmt))
const isBatchManaged = computed(() => toBoolFlag(editForm.is_batch_mgmt))
const bindSelectedProductDisplay = computed(() => {
const id = String(bindForm.system_product_id ?? '').trim()
if (!id) return ''
const name = String(bindForm.selected_product_name ?? '').trim()
const barcode = String(bindForm.selected_barcode ?? '').trim()
const parts = [`ID ${id}`]
if (name) parts.push(name)
if (barcode) parts.push(barcode)
return parts.join(' / ')
})
const formatBindDisplayValue = (prop: string) => {
const val = String(bindForm[prop as keyof typeof bindForm] ?? '').trim()
if (!val) return '--'
if (prop === 'current_system_product_id' && bindForm.current_system_product_name) {
return `${val}(${bindForm.current_system_product_name})`
}
return val
}
const resetBindForm = () => {
bindingDetailRow.value = null
bindForm.detail_id = ''
bindForm.product_name = ''
bindForm.barcode = ''
bindForm.current_system_product_id = ''
bindForm.current_system_product_name = ''
bindForm.system_product_id = ''
bindForm.selected_product_name = ''
bindForm.selected_barcode = ''
}
const boundStoreId = computed(() => {
const candidates = [
bindingDetailRow.value?.store_id,
bindingDetailRow.value?.store?.id,
bindingDetailRow.value?.receiving?.store_id,
bindingDetailRow.value?.receiving?.store?.id,
editingDetailRow.value?.store_id,
editingDetailRow.value?.store?.id,
editingDetailRow.value?.receiving?.store_id,
editingDetailRow.value?.receiving?.store?.id,
props.row?.store_id,
props.row?.store?.id
]
for (const c of candidates) {
const n = Number(c)
if (Number.isFinite(n) && n > 0) return n
}
return undefined
})
const boundStoreName = computed(() => {
return (
bindingDetailRow.value?.store?.store_remask ||
bindingDetailRow.value?.store?.store_name ||
bindingDetailRow.value?.receiving?.store?.store_remask ||
bindingDetailRow.value?.receiving?.store?.store_name ||
editingDetailRow.value?.store?.store_remask ||
editingDetailRow.value?.store?.store_name ||
editingDetailRow.value?.receiving?.store?.store_remask ||
editingDetailRow.value?.receiving?.store?.store_name ||
props.row?.store?.store_remask ||
props.row?.store?.store_name ||
props.row?.store_name ||
''
)
})
const resetEditForm = () => {
Object.keys(editForm).forEach((k) => {
editForm[k] = ''
})
}
const getSpaceDisplayName = (space: any) => {
const customName = String(space?.custom_name ?? space?.customName ?? '').trim()
if (customName) return customName
return String(space?.space_name ?? space?.name ?? space?.space_code ?? '').trim()
}
const resolveSpaceDisplayNameById = async (spaceId: any) => {
const rawId = String(spaceId ?? '').trim()
if (!rawId) return ''
const parsedId = Number(rawId)
if (!Number.isFinite(parsedId) || parsedId <= 0) return ''
try {
const info: any = await warehouseApi.getSpaceInfo(parsedId)
const direct = info?.data || info
return getSpaceDisplayName(direct)
} catch (error) {
console.error('按ID获取库位名称失败', error)
return ''
}
}
const parseNonNegativeInteger = (val: any): number | undefined => {
if (val === null || val === undefined) return undefined
const text = String(val).trim()
if (!text) return undefined
const num = Number(text)
if (!Number.isFinite(num)) return undefined
return Math.max(0, Math.floor(num))
}
const setEditFieldInteger = (field: string, value: number | undefined) => {
editForm[field] = value === undefined ? '' : String(value)
}
const parseDaysInteger = (val: any) => {
const text = String(val ?? '').trim()
if (!text) return undefined
const num = Number(text)
if (!Number.isFinite(num)) return undefined
return Math.max(0, Math.floor(num))
}
const toDateStart = (dateStr?: string) => {
const d = getDate(dateStr)
if (!d) return null
const next = new Date(d)
next.setHours(0, 0, 0, 0)
return next
}
const formatDateYMD = (date: Date) => {
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
}
const shiftDateByDays = (dateStr: string, days: number) => {
const base = toDateStart(dateStr)
if (!base || !Number.isFinite(days)) return ''
const next = new Date(base)
next.setDate(next.getDate() + Math.floor(days))
return formatDateYMD(next)
}
const getTodayStart = () => {
const today = new Date()
today.setHours(0, 0, 0, 0)
return today
}
const getExpiryRemainingDays = (expiryDate?: string) => {
const expiry = toDateStart(expiryDate)
if (!expiry) return undefined
const today = getTodayStart()
return Math.floor((expiry.getTime() - today.getTime()) / DAY_MS)
}
const validateInboundMinDaysConstraint = (showMessage = true) => {
if (!hasSkuSelected.value || !isShelfLifeManaged.value) return true
const inboundMinDays = parseDaysInteger(editForm.inbound_min_days)
if (inboundMinDays === undefined || inboundMinDays <= 0) return true
const expiryDate = String(editForm.expiry_date ?? '').trim()
if (!expiryDate) return true
const remainingDays = getExpiryRemainingDays(expiryDate)
if (remainingDays === undefined) return true
if (remainingDays >= inboundMinDays) return true
if (showMessage) {
ElMessage.error(`保质期低于${inboundMinDays}天,商品已设置禁止入库`)
}
return false
}
const onEditProductionDateChange = () => {
if (!hasSkuSelected.value || !isShelfLifeManaged.value) {
validateInboundMinDaysConstraint(true)
return
}
const shelfLifeDays = parseDaysInteger(editForm.shelf_life_days)
const productionDate = String(editForm.production_date ?? '').trim()
const expiryDate = String(editForm.expiry_date ?? '').trim()
if (shelfLifeDays !== undefined && shelfLifeDays > 0 && productionDate && !expiryDate) {
editForm.expiry_date = shiftDateByDays(productionDate, shelfLifeDays)
}
validateInboundMinDaysConstraint(true)
}
const onEditExpiryDateChange = () => {
if (!hasSkuSelected.value || !isShelfLifeManaged.value) {
validateInboundMinDaysConstraint(true)
return
}
const shelfLifeDays = parseDaysInteger(editForm.shelf_life_days)
const productionDate = String(editForm.production_date ?? '').trim()
const expiryDate = String(editForm.expiry_date ?? '').trim()
if (shelfLifeDays !== undefined && shelfLifeDays > 0 && expiryDate && !productionDate) {
editForm.production_date = shiftDateByDays(expiryDate, -shelfLifeDays)
}
validateInboundMinDaysConstraint(true)
}
const handleQuantityLinkage = (source: 'actual_quantity' | 'box_quantity' | 'boxes_per_pallet' | 'box_remainder') => {
const total = parseNonNegativeInteger(editForm.actual_quantity)
const boxCount = parseNonNegativeInteger(editForm.box_quantity)
const boxSpec = parseNonNegativeInteger(editForm.boxes_per_pallet)
const remainderRaw = parseNonNegativeInteger(editForm.box_remainder)
if (!boxSpec || boxSpec <= 0) {
return
}
if (source === 'actual_quantity' || (source === 'boxes_per_pallet' && total !== undefined)) {
const safeTotal = total ?? 0
const nextBoxCount = Math.floor(safeTotal / boxSpec)
const nextRemainder = safeTotal % boxSpec
setEditFieldInteger('box_quantity', nextBoxCount)
setEditFieldInteger('box_remainder', nextRemainder)
setEditFieldInteger('actual_quantity', safeTotal)
return
}
let safeBoxCount = boxCount ?? 0
let safeRemainder = remainderRaw ?? 0
if (safeRemainder >= boxSpec) {
safeBoxCount += Math.floor(safeRemainder / boxSpec)
safeRemainder = safeRemainder % boxSpec
}
const nextTotal = safeBoxCount * boxSpec + safeRemainder
setEditFieldInteger('box_quantity', safeBoxCount)
setEditFieldInteger('box_remainder', safeRemainder)
setEditFieldInteger('actual_quantity', nextTotal)
}
const openEditDialog = (row: any) => {
if (isRowReadOnly(row)) {
showReadOnlyTip()
return
}
editDialogMode.value = 'edit'
editingDetailRow.value = row
editForm.actual_quantity = row?.actual_quantity ?? row?.quantity ?? ''
editForm.batch_number = row?.batch_number ?? ''
editForm.production_date = row?.production_date ?? ''
editForm.expiry_date = row?.expiry_date ?? ''
editForm.box_quantity = row?.box_quantity ?? ''
editForm.boxes_per_pallet = row?.boxes_per_pallet ?? ''
editForm.pallet_quantity = row?.pallet_quantity ?? ''
editForm.space_id = row?.space_id ?? ''
editForm.space_display_name =
String(row?.space_custom_name ?? '').trim() ||
String(row?.space_name ?? '').trim() ||
String(row?.space_code ?? '').trim() ||
(row?.space_id ? `ID ${row.space_id}` : '')
editForm.remark = row?.remark ?? ''
editForm.system_product_id = row?.system_product_id ?? ''
editForm.barcode = row?.barcode ?? row?.barcodes ?? ''
editForm.product_name = row?.product_name ?? row?.item_name ?? ''
editForm.box_width = row?.box_width ?? ''
editForm.box_height = row?.box_height ?? ''
editForm.box_length = row?.box_length ?? ''
editForm.box_remainder = row?.box_remainder ?? ''
editForm.box_weight = row?.box_weight ?? ''
editForm.weight = row?.weight ?? ''
editForm.is_shelf_life_mgmt =
row?.is_shelf_life_mgmt ??
row?.is_shelf_life_manage ??
row?.is_validity_mgmt ??
row?.system_product?.is_shelf_life_mgmt ??
row?.system_product?.is_shelf_life_manage ??
''
editForm.shelf_life_days =
row?.shelf_life_days ??
row?.system_product?.shelf_life_days ??
''
editForm.is_batch_mgmt =
row?.is_batch_mgmt ??
row?.is_batch_manage ??
row?.system_product?.is_batch_mgmt ??
row?.system_product?.is_batch_manage ??
''
editForm.inbound_min_days =
row?.inbound_min_days ??
row?.system_product?.inbound_min_days ??
''
const shouldResolveSpaceName =
!!String(editForm.space_id ?? '').trim() &&
!String(row?.space_custom_name ?? '').trim() &&
!String(row?.space_name ?? '').trim() &&
!String(row?.space_code ?? '').trim()
if (shouldResolveSpaceName) {
void resolveSpaceDisplayNameById(editForm.space_id).then((name) => {
if (!name) return
if (editingDetailRow.value?.id !== row?.id) return
editForm.space_display_name = name
})
}
if (String(editForm.production_date ?? '').trim() && !String(editForm.expiry_date ?? '').trim()) {
onEditProductionDateChange()
} else if (String(editForm.expiry_date ?? '').trim() && !String(editForm.production_date ?? '').trim()) {
onEditExpiryDateChange()
} else {
validateInboundMinDaysConstraint(false)
}
handleQuantityLinkage('actual_quantity')
editDialogVisible.value = true
}
const openBindDialog = (row: any) => {
if (isRowReadOnly(row)) {
showReadOnlyTip()
return
}
const detailId = getDetailIdFromRow(row)
if (!detailId) {
ElMessage.warning('缺少有效的收货明细ID')
return
}
bindingDetailRow.value = row
bindForm.detail_id = String(detailId)
bindForm.product_name = row?.product_name ?? row?.item_name ?? ''
bindForm.barcode = normalizeBarcodeString(row?.barcodes, row?.barcode) || ''
bindForm.current_system_product_id = row?.system_product_id ? String(row.system_product_id) : ''
bindForm.current_system_product_name =
row?.system_product?.item_name ??
row?.system_product_name ??
row?.matched_product_name ??
''
bindForm.system_product_id = ''
bindForm.selected_product_name = ''
bindForm.selected_barcode = ''
bindDialogVisible.value = true
}
const openBindSystemProductPicker = async () => {
systemProductPickerTarget.value = 'bind'
await openSystemProductPicker()
}
const submitBindDetail = async () => {
const detailId = Number(bindForm.detail_id)
const systemProductId = Number(bindForm.system_product_id)
if (!Number.isFinite(detailId) || detailId <= 0) {
ElMessage.warning('缺少有效的明细ID')
return
}
if (!Number.isFinite(systemProductId) || systemProductId <= 0) {
ElMessage.warning('请选择要绑定的系统商品')
return
}
bindSaving.value = true
try {
const res: any = await receivingApi.bindDetailProduct({
detail_id: detailId,
id: detailId,
system_product_id: systemProductId
})
if (res && (res.code === 200 || res.flag === 'success')) {
const boundName = res?.data?.product_name || bindForm.selected_product_name || ''
ElMessage.success(res?.message || (boundName ? `绑定成功:${boundName}` : '明细绑定成功'))
bindDialogVisible.value = false
resetBindForm()
loadProductData()
} else {
ElMessage.error(res?.message || '明细绑定失败')
}
} catch (error) {
console.error('明细绑定失败', error)
ElMessage.error('明细绑定失败')
} finally {
bindSaving.value = false
}
}
const openAddItemDialog = () => {
if (isReadOnlyStatus(props.row?.status || props.row?.receiving_status)) {
showReadOnlyTip()
return
}
editDialogMode.value = 'add'
editingDetailRow.value = null
resetEditForm()
editDialogVisible.value = true
}
const openBatchImportDialog = () => {
batchImportDialogVisible.value = true
}
const openBatchRowSpacePicker = async (row: any) => {
batchImportEditingRow.value = row
batchImportPickerMode.value = 'space'
await openSpacePicker()
}
const openBatchRowSkuPicker = async (row: any) => {
batchImportEditingRow.value = row
batchImportPickerMode.value = 'sku'
systemProductPickerTarget.value = 'batch-sku'
await openSystemProductPicker()
}
const triggerBatchImportSelect = () => {
batchImportInputRef.value?.click()
}
const onBatchImportFileChange = (evt: Event) => {
const input = evt.target as HTMLInputElement
const file = input?.files?.[0]
if (!file) return
const lowerName = String(file.name || '').toLowerCase()
if (!lowerName.endsWith('.xlsx')) {
ElMessage.warning('仅支持 .xlsx 文件')
input.value = ''
return
}
batchImportSourceFile.value = file
batchImportFileName.value = file.name
void generateBatchImportList()
input.value = ''
}
const downloadBatchImportTemplate = () => {
const headers = [
'SKU',
'条码',
'商品名称',
'实际收货数量',
'箱规',
'托盘数',
'批次号',
'生产日期',
'到期日期',
'库位条码或名称',
'毛重/重量',
'箱长',
'箱宽',
'箱高',
'实测箱重',
'备注'
]
const sample = ['', '', '', 0, 1, '', '', '', '', '', '', '', '', '', '', '']
const ws = XLSX.utils.aoa_to_sheet([headers, sample])
const wb = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(wb, ws, '批量导入商品')
XLSX.writeFile(wb, `收货商品导入模板_${Date.now()}.xlsx`)
}
const pickImportValue = (row: Record<string, any>, keys: string[]) => {
for (const key of keys) {
if (Object.prototype.hasOwnProperty.call(row, key)) {
const v = row[key]
if (v !== null && v !== undefined && String(v).trim() !== '') {
return v
}
}
}
return ''
}
const toImportNumber = (val: any) => {
const text = String(val ?? '').trim()
if (!text) return undefined
const num = Number(text)
return Number.isFinite(num) ? num : undefined
}
const toImportString = (val: any) => {
if (Array.isArray(val)) {
const parts = val
.map((item) => String(item ?? '').trim())
.filter((item) => !!item)
return parts.length ? parts.join(',') : undefined
}
if (val && typeof val === 'object') {
const candidates = [val.barcode, val.code, val.value]
for (const candidate of candidates) {
const text = String(candidate ?? '').trim()
if (text) return text
}
return undefined
}
const text = String(val ?? '').trim()
return text || undefined
}
const normalizeBarcodeString = (barcodes: any, fallback?: any) => {
const barcodeFromList = toImportString(barcodes)
if (barcodeFromList) return barcodeFromList
return toImportString(fallback) || ''
}
const normalizeQuantityByTotalAndSpec = (itemPayload: any) => {
const total = Number(itemPayload?.actual_quantity)
const boxSpec = Number(itemPayload?.boxes_per_pallet)
if (!Number.isFinite(total) || !Number.isFinite(boxSpec) || boxSpec <= 0) return
const safeTotal = Math.max(0, Math.floor(total))
const safeSpec = Math.max(1, Math.floor(boxSpec))
itemPayload.actual_quantity = safeTotal
itemPayload.boxes_per_pallet = safeSpec
itemPayload.box_quantity = Math.floor(safeTotal / safeSpec)
itemPayload.box_remainder = safeTotal % safeSpec
}
const buildSystemProductSearchParams = (keyword: string, storeId?: number) => {
const params: Record<string, any> = {}
if (Number.isFinite(storeId) && (storeId as number) > 0) {
params.store_id = { operator: 'eq', value: storeId }
}
const text = String(keyword || '').trim()
if (!text) return params
if (/^\d{6,}$/.test(text)) {
params.barcode = { operator: 'contains', value: text, type: 'text' }
} else if (/^\d+$/.test(text)) {
params.id = { operator: 'eq', value: Number(text), type: 'number' }
} else {
params.item_name = { operator: 'contains', value: text, type: 'text' }
}
return params
}
const querySystemProductById = async (skuId: number) => {
if (!Number.isFinite(skuId) || skuId <= 0) return null
try {
const where = buildStockQuery({
id: { operator: 'eq', value: skuId, type: 'number' }
})
const res: any = await stockApi.stockWarehouse({ page: 1, pageSize: 1 }, where)
const list = res?.data?.list || []
return list[0] || null
} catch (error) {
console.error('按SKU查询商品失败', error)
return null
}
}
const generateBatchImportList = async () => {
if (!batchImportSourceFile.value) {
ElMessage.warning('请先选择Excel文件')
return
}
batchImportLoading.value = true
try {
const buffer = await batchImportSourceFile.value.arrayBuffer()
const wb = XLSX.read(buffer, { type: 'array' })
const firstName = wb.SheetNames[0]
if (!firstName) {
ElMessage.warning('Excel中没有可读取的工作表')
return
}
const ws = wb.Sheets[firstName]
if (!ws) {
ElMessage.warning('工作表读取失败')
return
}
const rawRows = XLSX.utils.sheet_to_json<Record<string, any>>(ws, { defval: '' })
const previewRows: any[] = []
const addItems: any[] = []
for (let index = 0; index < rawRows.length; index += 1) {
const row = (rawRows[index] || {}) as Record<string, any>
const itemPayload: any = {}
const systemProductId = toImportNumber(pickImportValue(row, ['SKU', '系统商品ID', 'system_product_id']))
const barcode = toImportString(pickImportValue(row, ['条码', 'barcode', 'barcodes']))
const productName = toImportString(pickImportValue(row, ['商品名称', 'product_name', 'item_name']))
const actualQuantity = toImportNumber(pickImportValue(row, ['实际收货数量', 'actual_quantity']))
const boxQuantity = toImportNumber(pickImportValue(row, ['箱数', 'box_quantity']))
const boxSpec = toImportNumber(pickImportValue(row, ['箱规', 'boxes_per_pallet']))
const boxRemainder = toImportNumber(pickImportValue(row, ['剩余不满一箱', 'box_remainder']))
const palletQuantity = toImportNumber(pickImportValue(row, ['托盘数', 'pallet_quantity']))
const batchNumber = toImportString(pickImportValue(row, ['批次号', 'batch_number']))
const productionDate = toImportString(pickImportValue(row, ['生产日期', 'production_date']))
const expiryDate = toImportString(pickImportValue(row, ['到期日期', 'expiry_date']))
const spaceKeyword = toImportString(pickImportValue(row, ['库位条码或名称', '库位名称', '库位条码', '库位ID', 'space_id', 'space_code', 'space_name']))
const weight = toImportNumber(pickImportValue(row, ['毛重/重量', 'weight']))
const boxLength = toImportNumber(pickImportValue(row, ['箱长', 'box_length']))
const boxWidth = toImportNumber(pickImportValue(row, ['箱宽', 'box_width']))
const boxHeight = toImportNumber(pickImportValue(row, ['箱高', 'box_height']))
const boxWeight = toImportNumber(pickImportValue(row, ['实测箱重', 'box_weight']))
const remark = toImportString(pickImportValue(row, ['备注', 'remark']))
if (systemProductId !== undefined) itemPayload.system_product_id = systemProductId
if (barcode !== undefined) itemPayload.barcode = barcode
if (productName !== undefined) itemPayload.product_name = productName
if (actualQuantity !== undefined) itemPayload.actual_quantity = actualQuantity
if (boxSpec !== undefined) itemPayload.boxes_per_pallet = boxSpec
if (palletQuantity !== undefined) itemPayload.pallet_quantity = palletQuantity
if (batchNumber !== undefined) itemPayload.batch_number = batchNumber
if (productionDate !== undefined) itemPayload.production_date = productionDate
if (expiryDate !== undefined) itemPayload.expiry_date = expiryDate
if (weight !== undefined) itemPayload.weight = weight
if (boxLength !== undefined) itemPayload.box_length = boxLength
if (boxWidth !== undefined) itemPayload.box_width = boxWidth
if (boxHeight !== undefined) itemPayload.box_height = boxHeight
if (boxWeight !== undefined) itemPayload.box_weight = boxWeight
if (remark !== undefined) itemPayload.remark = remark
normalizeQuantityByTotalAndSpec(itemPayload)
if (systemProductId !== undefined) {
const product = await querySystemProductById(systemProductId)
if (product) {
itemPayload.product_name = product.item_name || product.product_name || itemPayload.product_name
itemPayload.barcode = normalizeBarcodeString(product.barcodes, product.barcode) || itemPayload.barcode
}
}
let resolvedSpaceKeyword = spaceKeyword ?? ''
if (spaceKeyword) {
const resolvedSpace = await resolveSpaceByKeyword(spaceKeyword)
if (resolvedSpace.id) {
itemPayload.space_id = resolvedSpace.id
}
if (resolvedSpace.displayName) {
resolvedSpaceKeyword = resolvedSpace.displayName
}
}
if (Object.keys(itemPayload).length === 0) return
previewRows.push({
row_no: index + 2,
system_product_id: itemPayload.system_product_id ?? '',
barcode: itemPayload.barcode ?? '',
product_name: itemPayload.product_name ?? '',
actual_quantity: itemPayload.actual_quantity ?? '',
box_quantity: itemPayload.box_quantity ?? '',
boxes_per_pallet: itemPayload.boxes_per_pallet ?? '',
box_remainder: itemPayload.box_remainder ?? '',
space_keyword: resolvedSpaceKeyword,
import_status: '待导入',
import_message: '',
remark: itemPayload.remark ?? '',
item_payload: itemPayload
})
}
batchImportPreviewRows.value = previewRows
addItems.push(...previewRows.map((r) => ({ item: { ...(r.item_payload || {}) } })))
batchImportAddItems.value = addItems
ElMessage.success(`已生成 ${addItems.length} 条基础新增数据`)
} catch (error) {
console.error('解析导入文件失败', error)
ElMessage.error('解析导入文件失败')
} finally {
batchImportLoading.value = false
}
}
const clearBatchImportData = () => {
batchImportPreviewRows.value = []
batchImportAddItems.value = []
batchImportSourceFile.value = null
batchImportFileName.value = ''
}
const resolveSpaceByKeyword = async (keyword: string): Promise<{ id?: number; displayName?: string }> => {
const text = String(keyword || '').trim()
if (!text) return {}
const numericId = Number(text)
if (Number.isFinite(numericId) && numericId > 0) {
try {
const info: any = await warehouseApi.getSpaceInfo(numericId)
const direct = info?.data || info
const resolvedId = Number(direct?.id ?? numericId)
return {
id: Number.isFinite(resolvedId) && resolvedId > 0 ? resolvedId : numericId,
displayName: getSpaceDisplayName(direct)
}
} catch (error) {
console.error('按ID获取库位信息失败', error)
}
}
const res: any = await indexApi.searchSpace({ keyword: text, page: 1, pageSize: 20 })
const data = res && (res.data || res.list || res)
const list = Array.isArray(data?.list) ? data.list : Array.isArray(data) ? data : []
if (!list.length) return {}
const exact = list.find((item: any) => {
const code = String(item?.space_code ?? '').trim()
const customName = String(item?.custom_name ?? item?.customName ?? '').trim()
const name = String(item?.space_name ?? item?.name ?? '').trim()
return code === text || customName === text || name === text
}) || list[0]
const id = Number(exact?.id)
return {
id: Number.isFinite(id) && id > 0 ? id : undefined,
displayName: getSpaceDisplayName(exact)
}
}
const submitBatchImportCreate = async () => {
const receivingId = Number(props.id ?? props.row?.id)
if (!Number.isFinite(receivingId) || receivingId <= 0) {
ElMessage.warning('缺少有效的收货单ID,无法导入')
return
}
if (!batchImportPreviewRows.value.length) {
ElMessage.warning('请先选择Excel并生成列表')
return
}
batchImportLoading.value = true
let successCount = 0
try {
for (const row of batchImportPreviewRows.value) {
const ok = await importSingleBatchRow(row, receivingId)
if (ok) successCount += 1
}
ElMessage.success(`导入完成:成功 ${successCount} 条,共 ${batchImportPreviewRows.value.length} 条`)
if (successCount > 0) {
loadProductData()
}
} finally {
batchImportLoading.value = false
batchImportAddItems.value = batchImportPreviewRows.value.map((r) => ({
receiving_id: receivingId,
item: { ...(r.item_payload || {}) }
}))
}
}
const importSingleBatchRow = async (row: any, receivingId: number): Promise<boolean> => {
const item = { ...(row.item_payload || {}) }
const keyword = String(row.space_keyword || '').trim()
try {
normalizeQuantityByTotalAndSpec(item)
const skuId = Number(item.system_product_id)
if (Number.isFinite(skuId) && skuId > 0) {
const product = await querySystemProductById(skuId)
if (product) {
item.product_name = product.item_name || product.product_name || item.product_name
item.barcode = normalizeBarcodeString(product.barcodes, product.barcode) || item.barcode
}
}
if (!item.space_id) {
if (keyword) {
const resolvedSpace = await resolveSpaceByKeyword(keyword)
if (!resolvedSpace.id) {
row.import_status = '失败'
row.import_message = `库位未匹配: ${keyword}`
return false
}
item.space_id = resolvedSpace.id
if (resolvedSpace.displayName) {
row.space_keyword = resolvedSpace.displayName
}
} else {
item.space_id = 1
}
}
row.item_payload = item
const payload = { receiving_id: receivingId, item }
const res: any = await receivingApi.addDetail(payload)
if (res && (res.code === 200 || res.flag === 'success')) {
row.import_status = '成功'
row.import_message = res?.message || '创建成功'
return true
}
row.import_status = '失败'
row.import_message = res?.message || '创建失败'
return false
} catch (error: any) {
row.import_status = '失败'
row.import_message = error?.message || '创建失败'
return false
}
}
const retryFailedBatchRows = async () => {
const receivingId = Number(props.id ?? props.row?.id)
if (!Number.isFinite(receivingId) || receivingId <= 0) {
ElMessage.warning('缺少有效的收货单ID,无法重试')
return
}
const failedRows = batchImportPreviewRows.value.filter((r) => r.import_status === '失败')
if (!failedRows.length) {
ElMessage.warning('当前没有失败行可重试')
return
}
batchRetryFailedLoading.value = true
let successCount = 0
try {
for (const row of failedRows) {
const ok = await importSingleBatchRow(row, receivingId)
if (ok) successCount += 1
}
ElMessage.success(`重试完成:成功 ${successCount} 条,共 ${failedRows.length} 条`)
if (successCount > 0) {
loadProductData()
}
} finally {
batchRetryFailedLoading.value = false
}
}
const retryBatchImportRow = async (row: any) => {
const receivingId = Number(props.id ?? props.row?.id)
if (!Number.isFinite(receivingId) || receivingId <= 0) {
ElMessage.warning('缺少有效的收货单ID,无法重试')
return
}
const ok = await importSingleBatchRow(row, receivingId)
if (ok) {
ElMessage.success(`第 ${row.row_no} 行重试成功`)
loadProductData()
}
}
const openEditSystemProductPicker = async () => {
systemProductPickerTarget.value = 'edit'
await openSystemProductPicker()
}
const openSystemProductPicker = async () => {
systemProductPickerVisible.value = true
systemProductSelection.value = []
await querySystemProducts(1)
}
const openSpacePicker = async () => {
spacePickerVisible.value = true
spaceSelection.value = []
await querySpaces(1)
}
const handleSpaceSelectionChange = (val: any[]) => {
spaceSelection.value = val
}
const handleSpaceRowClick = (row: any) => {
spaceSelection.value = [row]
}
const onSpacePageSizeChange = (size: number) => {
spacePagination.pageSize = size
querySpaces(1)
}
const querySpaces = async (page = 1) => {
spaceLoading.value = true
try {
const keyword = String(spaceKeyword.value || '').trim()
const res: any = await indexApi.searchSpace({ keyword, page, pageSize: spacePagination.pageSize })
const data = res && (res.data || res.list || res)
const list = Array.isArray(data?.list) ? data.list : Array.isArray(data) ? data : []
spaceResults.value = list.map((item: any) => ({
...item,
display_name: getSpaceDisplayName(item),
space_name: item.space_name || item.name || item.space_code || ''
}))
spacePagination.total = data?.pagination?.total || data?.total || spaceResults.value.length
spacePagination.page = page
} catch (error) {
console.error('查询库位失败', error)
ElMessage.error('查询库位失败')
spaceResults.value = []
spacePagination.total = 0
} finally {
spaceLoading.value = false
}
}
const applySelectedSpace = () => {
if (spaceSelection.value.length !== 1) {
ElMessage.warning('请选择一个库位')
return
}
const picked = spaceSelection.value[0]
if (batchImportPickerMode.value === 'space' && batchImportEditingRow.value) {
const row = batchImportEditingRow.value
const display = getSpaceDisplayName(picked) || picked?.space_code || ''
row.space_keyword = display
row.import_status = '待导入'
row.import_message = ''
row.item_payload = {
...(row.item_payload || {}),
space_id: Number(picked?.id) || 1
}
batchImportPickerMode.value = ''
batchImportEditingRow.value = null
spacePickerVisible.value = false
return
}
editForm.space_id = picked?.id ?? ''
editForm.space_display_name = getSpaceDisplayName(picked)
spacePickerVisible.value = false
}
const handleSystemProductSelectionChange = (val: any[]) => {
systemProductSelection.value = val
}
const handleSystemProductRowClick = (row: any) => {
systemProductSelection.value = [row]
}
const onSystemProductPageSizeChange = (size: number) => {
systemProductPagination.pageSize = size
querySystemProducts(1)
}
const querySystemProducts = async (page = 1) => {
systemProductLoading.value = true
try {
const paginationParam = { page, pageSize: systemProductPagination.pageSize }
const where = buildStockQuery(
buildSystemProductSearchParams(systemProductKeyword.value, boundStoreId.value)
)
const res: any = await stockApi.stockWarehouse(paginationParam, where)
if (res && (res.code === 200 || res.flag === 'success') && res.data) {
systemProductResults.value = res.data.list || []
systemProductPagination.total = res.data.pagination?.total || res.data.total || systemProductResults.value.length
systemProductPagination.page = page
} else {
systemProductResults.value = []
systemProductPagination.total = 0
systemProductPagination.page = page
if (res?.message) {
ElMessage.error(res.message)
}
}
} catch (error) {
console.error('查询系统商品失败', error)
ElMessage.error('查询系统商品失败')
systemProductResults.value = []
systemProductPagination.total = 0
} finally {
systemProductLoading.value = false
}
}
const applySelectedSystemProduct = () => {
if (systemProductSelection.value.length !== 1) {
ElMessage.warning('请选择一条系统商品记录')
return
}
const picked = systemProductSelection.value[0] || {}
if (batchImportPickerMode.value === 'sku' && batchImportEditingRow.value) {
const row = batchImportEditingRow.value
row.system_product_id = picked.id ?? row.system_product_id
row.barcode = normalizeBarcodeString(picked.barcodes, picked.barcode) || row.barcode
row.product_name = picked.item_name || picked.product_name || row.product_name
row.import_status = '待导入'
row.import_message = ''
row.item_payload = {
...(row.item_payload || {}),
system_product_id: picked.id ?? row.item_payload?.system_product_id,
barcode: normalizeBarcodeString(picked.barcodes, picked.barcode) || row.item_payload?.barcode,
product_name: picked.item_name || picked.product_name || row.item_payload?.product_name,
weight: picked.weight ?? picked.gross_weight ?? row.item_payload?.weight,
box_length: picked.box_length ?? picked.length ?? row.item_payload?.box_length,
box_width: picked.box_width ?? picked.width ?? row.item_payload?.box_width,
box_height: picked.box_height ?? picked.height ?? row.item_payload?.box_height,
box_weight: picked.box_weight ?? picked.gross_weight ?? row.item_payload?.box_weight,
boxes_per_pallet: picked.boxes_per_pallet ?? row.item_payload?.boxes_per_pallet
}
batchImportPickerMode.value = ''
batchImportEditingRow.value = null
systemProductPickerTarget.value = 'edit'
systemProductPickerVisible.value = false
return
}
if (systemProductPickerTarget.value === 'bind') {
bindForm.system_product_id = picked.id ? String(picked.id) : ''
bindForm.selected_product_name = picked.item_name || picked.product_name || ''
bindForm.selected_barcode = normalizeBarcodeString(picked.barcodes, picked.barcode) || ''
systemProductPickerVisible.value = false
ElMessage.success('已选择系统商品,请点击确认绑定')
return
}
editForm.system_product_id = picked.id ?? editForm.system_product_id
editForm.barcode = normalizeBarcodeString(picked.barcodes, picked.barcode) || editForm.barcode
editForm.product_name = picked.item_name || picked.product_name || editForm.product_name
editForm.weight = picked.weight ?? picked.gross_weight ?? editForm.weight
editForm.box_length = picked.box_length ?? picked.length ?? editForm.box_length
editForm.box_width = picked.box_width ?? picked.width ?? editForm.box_width
editForm.box_height = picked.box_height ?? picked.height ?? editForm.box_height
editForm.box_weight = picked.box_weight ?? picked.gross_weight ?? editForm.box_weight
editForm.boxes_per_pallet = picked.boxes_per_pallet ?? editForm.boxes_per_pallet
editForm.is_shelf_life_mgmt =
picked.is_shelf_life_mgmt ??
picked.is_shelf_life_manage ??
picked.is_validity_mgmt ??
editForm.is_shelf_life_mgmt
editForm.shelf_life_days =
picked.shelf_life_days ??
editForm.shelf_life_days
editForm.is_batch_mgmt =
picked.is_batch_mgmt ??
picked.is_batch_manage ??
editForm.is_batch_mgmt
editForm.inbound_min_days =
picked.inbound_min_days ??
editForm.inbound_min_days
handleQuantityLinkage('boxes_per_pallet')
if (String(editForm.production_date ?? '').trim() && !String(editForm.expiry_date ?? '').trim()) {
onEditProductionDateChange()
} else if (String(editForm.expiry_date ?? '').trim() && !String(editForm.production_date ?? '').trim()) {
onEditExpiryDateChange()
} else {
validateInboundMinDaysConstraint(false)
}
systemProductPickerVisible.value = false
ElMessage.success('已使用系统商品属性回填表单')
}
const parseNumberIfValid = (val: any) => {
if (val === null || val === undefined) return undefined
const text = String(val).trim()
if (!text) return undefined
const num = Number(text)
return Number.isFinite(num) ? num : undefined
}
const stringIfNonEmpty = (val: any) => {
if (val === null || val === undefined) return undefined
const text = String(val).trim()
return text ? text : undefined
}
const validateRequiredQuantityFields = () => {
const requiredFields: Array<{ key: keyof typeof editForm; label: string }> = [
{ key: 'actual_quantity', label: '实际收货数量' },
{ key: 'box_quantity', label: '箱数' },
{ key: 'boxes_per_pallet', label: '箱规' },
{ key: 'box_remainder', label: '剩余不满一箱' }
]
for (const field of requiredFields) {
const text = String(editForm[field.key] ?? '').trim()
if (!text) {
ElMessage.warning(`请填写${field.label}`)
return false
}
}
const total = parseNumberIfValid(editForm.actual_quantity)
const boxCount = parseNumberIfValid(editForm.box_quantity)
const boxSpec = parseNumberIfValid(editForm.boxes_per_pallet)
const remainder = parseNumberIfValid(editForm.box_remainder)
if (
total === undefined ||
boxCount === undefined ||
boxSpec === undefined ||
remainder === undefined
) {
ElMessage.warning('数量字段必须为有效数字')
return false
}
if (boxSpec <= 0) {
ElMessage.warning('箱规必须大于 0')
return false
}
if (remainder >= boxSpec) {
ElMessage.warning('剩余不满一箱数量必须小于箱规')
return false
}
const expectedTotal = boxCount * boxSpec + remainder
if (expectedTotal !== total) {
ElMessage.warning('数量关系不正确,请确保:实际收货数量 = 箱数 × 箱规 + 剩余不满一箱')
return false
}
return true
}
const validateSkuDependentFields = () => {
if (hasSkuSelected.value) {
return true
}
const barcode = String(editForm.barcode ?? '').trim()
const productName = String(editForm.product_name ?? '').trim()
if (!barcode) {
ElMessage.warning('未选择 SKU 时,条码为必填')
return false
}
if (!productName) {
ElMessage.warning('未选择 SKU 时,商品名称为必填')
return false
}
return true
}
const validateManagementDependentFields = () => {
if (!hasSkuSelected.value) {
return true
}
if (isBatchManaged.value) {
const batchNumber = String(editForm.batch_number ?? '').trim()
if (!batchNumber) {
ElMessage.warning('该商品开启批次管理,批次号为必填')
return false
}
}
if (isShelfLifeManaged.value) {
const productionDate = String(editForm.production_date ?? '').trim()
const expiryDate = String(editForm.expiry_date ?? '').trim()
if (!productionDate) {
ElMessage.warning('该商品开启效期管理,生产日期为必填')
return false
}
if (!expiryDate) {
ElMessage.warning('该商品开启效期管理,到期日期为必填')
return false
}
}
return true
}
const submitEditDetail = async () => {
if (!validateSkuDependentFields()) {
return
}
if (!validateManagementDependentFields()) {
return
}
if (!validateInboundMinDaysConstraint(true)) {
return
}
if (!validateRequiredQuantityFields()) {
return
}
const receivingId = Number(
editingDetailRow.value?.receiving_id ?? props.id ?? props.row?.id
)
if (!Number.isFinite(receivingId) || receivingId <= 0) {
ElMessage.warning('缺少有效的收货单ID')
return
}
const detailId = Number(editingDetailRow.value?.id)
if (editDialogMode.value === 'edit' && (!Number.isFinite(detailId) || detailId <= 0)) {
ElMessage.warning('缺少有效的收货明细ID')
return
}
if (editForm.expiry_date) {
const expiryTime = new Date(editForm.expiry_date).getTime()
if (Number.isFinite(expiryTime)) {
const today = new Date()
today.setHours(0, 0, 0, 0)
if (expiryTime < today.getTime()) {
ElMessage.warning('到期日期不能早于当前日期')
return
}
}
}
const itemPayload: any = {}
// 重量字段必须为整数(g)
for (const wf of ['weight', 'box_weight'] as const) {
const raw = editForm[wf]
if (raw !== '' && raw !== null && raw !== undefined) {
const n = Number(raw)
if (!Number.isInteger(n) || n < 0) {
ElMessage.warning(`${wf === 'weight' ? '毛重/重量' : '实测箱重'}必须为非负整数(g)`)
return
}
}
}
const numberFields = [
'actual_quantity',
'box_quantity',
'boxes_per_pallet',
'pallet_quantity',
'space_id',
'system_product_id',
'box_width',
'box_height',
'box_length',
'box_remainder',
'box_weight',
'weight'
]
numberFields.forEach((field) => {
const parsed = parseNumberIfValid(editForm[field])
if (parsed !== undefined) itemPayload[field] = parsed
})
const stringFields = ['batch_number', 'production_date', 'expiry_date', 'remark', 'barcode', 'product_name']
stringFields.forEach((field) => {
const parsed = stringIfNonEmpty(editForm[field])
if (parsed !== undefined) itemPayload[field] = parsed
})
const payload: any =
editDialogMode.value === 'add'
? {
receiving_id: receivingId,
item: itemPayload
}
: {
id: detailId,
receiving_id: receivingId,
...itemPayload
}
editSaving.value = true
try {
const res: any =
editDialogMode.value === 'add'
? await receivingApi.addDetail(payload)
: await receivingApi.detailChange(payload)
if (res && (res.code === 200 || res.flag === 'success')) {
ElMessage.success(res?.message || (editDialogMode.value === 'add' ? '新增明细成功' : '明细更新成功'))
editDialogVisible.value = false
resetEditForm()
loadProductData()
} else {
ElMessage.error(res?.message || (editDialogMode.value === 'add' ? '新增明细失败' : '明细更新失败'))
}
} catch (error) {
console.error(editDialogMode.value === 'add' ? '新增收货明细失败' : '更新收货明细失败', error)
ElMessage.error(editDialogMode.value === 'add' ? '新增收货明细失败' : '更新收货明细失败')
} finally {
editSaving.value = false
}
}
const windowStyle = computed(() => {
if (isFullscreen.value) return {}
return {
top: `${position.value.y}px`,
left: `${position.value.x}px`,
}
})
const openAddDrawer = (row?: any) => {
if (isRowReadOnly(row)) {
showReadOnlyTip()
return
}
// row here is product row, but store info comes from parent receiving row (props.row)
addDrawerStore.value = props.row?.store || { id: props.row?.store_id, name: props.row?.store_name }
if (row) {
multipleSelection.value = [row]
}
addDrawerVisible.value = true
// allow child to initialize with store after mount
setTimeout(() => {
if (addCompRef.value) {
if (typeof addCompRef.value.resetForm === 'function') {
addCompRef.value.resetForm()
}
const formData = addCompRef.value.formData
if (!formData) return
if (addDrawerStore.value) {
formData.store_id = addDrawerStore.value.id || addDrawerStore.value.store_id || addDrawerStore.value.storeId
formData.store_name = addDrawerStore.value.name || addDrawerStore.value.store_name || ''
}
// 如果勾选了一个商品,自动填充相关字段
if (multipleSelection.value.length === 1) {
const item = multipleSelection.value[0]
formData.item_name = item.item_name || item.product_name || ''
const barcode = item.barcodes || item.barcode || ''
formData.barcode = barcode
formData.item_code = barcode || item.item_code || ''
// 解析可能存在的规格/属性 snapshot
if (item.product_snapshot) {
try {
const snap = typeof item.product_snapshot === 'string' ? JSON.parse(item.product_snapshot) : item.product_snapshot
if (snap.spec) formData.sku_property = snap.spec
if (snap.brand) formData.brand_name = snap.brand
} catch (e) {}
}
// 尝试填充箱规或体积(如果明细存在)
if (item.box_length) formData.length = item.box_length
if (item.box_width) formData.width = item.box_width
if (item.box_height) formData.height = item.box_height
if (item.weight) formData.gross_weight = item.weight
}
}
}, 100)
}
const handleDateCellClick = (row: any) => {
if (isRowReadOnly(row)) {
showReadOnlyTip()
return
}
openDateDialog(row)
}
const openDateDialog = (row: any) => {
if (isRowReadOnly(row)) {
showReadOnlyTip()
return
}
editingDateRow.value = row
dateForm.production_date = row?.production_date || ''
dateForm.expiry_date = row?.expiry_date || ''
dateDialogVisible.value = true
if (row?.expiry_date && isExpired(row.expiry_date)) {
ElMessageBox.alert(
`商品名称:${row?.product_name || '--'}已过期,请移除拒绝收货。`,
'过期提醒',
{ type: 'warning' }
)
}
}
const submitDateChange = async () => {
if (!editingDateRow.value?.id) {
ElMessage.warning('缺少明细ID,无法保存')
return
}
const receivingId = Number(
editingDateRow.value.receiving_id ?? props.id ?? props.row?.id
)
if (!receivingId) {
ElMessage.warning('缺少收货单ID,无法保存')
return
}
if (!dateForm.production_date || !dateForm.expiry_date) {
ElMessage.warning('请选择生产日期和到期日期')
return
}
if (new Date(dateForm.expiry_date).getTime() < new Date(dateForm.production_date).getTime()) {
ElMessage.warning('到期日期不能早于生产日期')
return
}
const detailId = Number(editingDateRow.value.id)
if (!Number.isFinite(detailId) || detailId <= 0) {
ElMessage.warning('缺少有效的明细ID')
return
}
dateSaving.value = true
try {
// 与 bindDetailProduct 一致:服务端以 detail_id 定位明细;部分实现不读取 id 字段
const res: any = await receivingApi.detailChange({
detail_id: detailId,
id: detailId,
receiving_id: receivingId,
production_date: dateForm.production_date,
expiry_date: dateForm.expiry_date
})
if (res && (res.code === 200 || res.flag === 'success')) {
ElMessage.success(res.message || '日期修改成功')
dateDialogVisible.value = false
loadProductData()
} else {
ElMessage.error(res?.message || '日期修改失败')
}
} catch (e) {
console.error('日期修改失败', e)
} finally {
dateSaving.value = false
}
}
const handleSelectionChange = (val: any[]) => {
multipleSelection.value = val
}
const handleContextMenu = (row: any, column: any, event: MouseEvent) => {
if (isRowReadOnly(row)) {
event.preventDefault()
return
}
event.preventDefault()
currentRow.value = row
menuTop.value = event.clientY
menuLeft.value = event.clientX
menuVisible.value = true
}
const closeMenu = () => {
menuVisible.value = false
}
const handleContextMenuBind = () => {
if (currentRow.value) {
openBindDialog(currentRow.value)
}
closeMenu()
}
const handleProductDetail = () => {
if (currentRow.value) {
windowVisible.value = true
// 重置为居中位置
isFullscreen.value = false
// 以样式中定义的默认窗口大小居中(width:1250, height:700)
const winW = 1250
const winH = 700
const x = Math.max(0, Math.floor((window.innerWidth - winW) / 2))
const y = Math.max(0, Math.floor((window.innerHeight - winH) / 2))
position.value = { x, y }
}
closeMenu()
}
const tableRowClassName = (row: any) => {
return 'clickable-row'
}
const toggleFullscreen = () => {
isFullscreen.value = !isFullscreen.value
}
// 拖拽逻辑
const startDrag = (e: MouseEvent) => {
if (isFullscreen.value) return
isDragging.value = true
dragOffset.value = {
x: e.clientX - position.value.x,
y: e.clientY - position.value.y
}
window.addEventListener('mousemove', onDrag)
window.addEventListener('mouseup', stopDrag)
}
const onDrag = (e: MouseEvent) => {
if (!isDragging.value) return
position.value = {
x: Math.max(0, e.clientX - dragOffset.value.x),
y: Math.max(0, e.clientY - dragOffset.value.y)
}
}
const stopDrag = () => {
isDragging.value = false
window.removeEventListener('mousemove', onDrag)
window.removeEventListener('mouseup', stopDrag)
}
const resetForm = () => {
if (activeWindowTab.value === 'basic' && basicRef.value) {
basicRef.value.reset?.()
}
}
const saveProductDetail = async () => {
if (activeWindowTab.value === 'basic' && basicRef.value) {
const updatedData = basicRef.value.getFormData?.()
if (updatedData) {
// 模拟本地修改 tableData
const index = tableData.value.findIndex(item => item.id === updatedData.id)
if (index !== -1) {
tableData.value[index] = { ...updatedData }
ElMessage.success('本地模拟修改成功')
windowVisible.value = false
}
}
}
}
onMounted(() => {
if (props.productData && props.productData.length > 0) {
tableData.value = [...props.productData]
pagination.total = props.productTotal || props.productData.length
} else if (!props.loading) {
// 如果父组件没有传入商品数据且提供了 id,则尝试通过接口加载
if (props.id) {
fetchReceivingDetail()
}
}
window.addEventListener('click', closeMenu)
})
onUnmounted(() => {
window.removeEventListener('click', closeMenu)
})
</script>
<style scoped>
.product-details {
width: 100%;
padding: 6px 10px 8px;
display: flex;
flex-direction: column;
height: 100%;
overflow: hidden;
background: #fff;
position: relative;
box-sizing: border-box;
}
.match-filter-group {
margin: 0 8px;
}
.required-mark {
color: #f56c6c;
margin-left: 4px;
}
.readonly-op {
color: #909399;
}
.clickable-date-cell.is-readonly {
color: #909399;
cursor: not-allowed;
}
.system-product-picker {
display: flex;
flex-direction: column;
gap: 10px;
}
.picker-toolbar {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
}
.batch-import-toolbar {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
margin-bottom: 10px;
}
.batch-import-summary {
margin-top: 10px;
color: #606266;
font-size: 12px;
}
.batch-cell-action {
display: flex;
align-items: center;
gap: 6px;
}
.picker-hint {
color: #606266;
font-size: 12px;
}
.picker-table-wrap {
height: 440px;
}
.product-window {
position: fixed;
z-index: 2000;
width: 1250px;
height: 700px;
background: #fff;
border: 1px solid #ebeef5;
box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.1);
/* border-radius: 4px; */
display: flex;
flex-direction: column;
}
.product-window.is-fullscreen {
top: 0 !important;
left: 0 !important;
width: 100vw !important;
height: 100vh !important;
border-radius: 0;
z-index: 3000;
}
.window-header {
padding: 8px 12px;
background: #f5f7fa;
border-bottom: 1px solid #ebeef5;
display: flex;
justify-content: space-between;
align-items: center;
cursor: move;
user-select: none;
}
.window-title {
font-size: 14px;
font-weight: bold;
color: #303133;
}
.window-actions {
display: flex;
gap: 4px;
}
.window-body {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
}
.window-tabs {
display: flex;
height: 40px;
background: #f5f7fa;
border-bottom: 1px solid #ebeef5;
padding: 0 10px;
}
.window-tabs .tab-item {
padding: 0 20px;
height: 100%;
display: flex;
align-items: center;
font-size: 13px;
color: #606266;
cursor: pointer;
transition: all 0.2s;
position: relative;
}
.window-tabs .tab-item:hover {
color: #409eff;
}
.window-tabs .tab-item.active {
color: #409eff;
font-weight: bold;
}
.window-tabs .tab-item.active::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 2px;
background: #409eff;
}
.window-content {
display: flex;
flex: 1;
overflow: auto;
padding: 20px;
}
.window-footer {
height: 52px;
display: flex;
align-items: center;
justify-content: flex-end;
padding: 0 20px;
background: #fff;
border-top: 1px solid #ebeef5;
gap: 12px;
}
.search-section {
margin-bottom: 20px;
}
.system-product-list {
flex: 1;
border: 1px solid #ebeef5;
border-radius: 4px;
background-color: #fafafa;
display: flex;
flex-direction: column;
}
.clickable-row {
cursor: pointer;
}
.context-menu {
position: fixed;
z-index: 3000;
background: #fff;
border: 1px solid #ebeef5;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
border-radius: 4px;
padding: 5px 0;
}
.menu-item {
padding: 8px 16px;
font-size: 13px;
color: #606266;
cursor: pointer;
white-space: nowrap;
}
.menu-item:hover {
background-color: #f5f7fa;
color: #409eff;
}
.header-actions {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 6px;
flex-shrink: 0;
gap: 4px;
flex-wrap: wrap;
}
.left-actions {
display: flex;
align-items: center;
gap: 8px;
}
.left-col {
flex: 1;
min-height: 0;
overflow: hidden;
display: flex;
flex-direction: column;
}
.left-col :deep(.upper-table-container) {
height: 100%;
display: flex;
flex-direction: column;
overflow: hidden;
}
.left-col :deep(.table-container) {
flex: 1;
min-height: 0;
height: auto !important;
}
.left-col :deep(.pagination-container) {
flex-shrink: 0;
padding: 4px 0 2px;
}
.product-detail-row-actions {
display: inline-flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
gap: 4px;
max-width: 100%;
}
.product-detail-table-wrap :deep(.product-detail-actions-col .cell) {
overflow: visible;
}
.product-detail-table-wrap :deep(.el-table__fixed-right) {
z-index: 3;
}
.bind-display-value {
color: #606266;
word-break: break-all;
}
.bind-product-picker {
width: 100%;
}
.edit-detail-form {
:deep(.el-input-group) {
width: 100%;
}
:deep(.el-form-item .el-input),
:deep(.el-form-item .el-date-editor) {
width: 100%;
}
}
.right-col {
grid-column: 2 / 3;
grid-row: 2 / 3;
height: 100%;
overflow-y: auto;
}
.right-panel {
position: sticky;
top: 20px;
background: #fff;
border-radius: 4px;
padding: 12px;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
}
.panel-actions {
text-align: right;
}
.image-slot {
display: flex;
align-items: center;
justify-content: center;
}
.clickable-date-cell {
color: #409eff;
cursor: pointer;
}
.clickable-date-cell:hover {
text-decoration: underline;
}
/* 商品入库状态样式 */
:deep(.el-table) {
.storage-status-tag {
font-weight: 500;
padding: 2px 8px;
border-radius: 3px;
display: inline-block;
}
/* 全部入库 - 绿色 */
.storage-status-all {
background-color: #f0f9ff;
color: #67C23A;
border: 1px solid #c6e2ff;
}
/* 部分入库 - 橙色 */
.storage-status-partial {
background-color: #fdf6ec;
color: #E6A23C;
border: 1px solid #f5dab1;
}
/* 待入库 - 蓝色 */
.storage-status-waiting {
background-color: #ecf5ff;
color: #409EFF;
border: 1px solid #b3d8ff;
}
/* 未入库 - 灰色 */
.storage-status-none {
background-color: #f5f7fa;
color: #909399;
border: 1px solid #ebeef5;
}
}
</style>