WEB/src/views/warehouse/components/RackBulkModifyDialog.vue
2026-08-25 18:14:47 +08:00

632 lines
22 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>
<el-dialog
v-model="visible"
title="导入批量修改"
width="1000px"
top="calc(50% - 220px)"
align-center
:close-on-click-modal="false"
destroy-on-close
append-to-body
@close="close"
:show-close="true"
>
<div class="bulk-dialog" style="display:flex;flex-direction:column;">
<div v-if="!loaded" class="empty-container">
<input ref="fileInputRef" type="file" accept=".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" style="display:none" @change="onFileChange" />
<el-button type="primary" @click="triggerFileSelect">选择 Excel 文件</el-button>
</div>
<div v-else class="content-container" style="display:flex;flex-direction:column;flex:1;">
<div class="toolbar" style="display:flex;align-items:center;gap:8px;padding:8px;">
<el-button size="small" @click="triggerFileSelect">导入文件</el-button>
<el-button size="small" @click="clearData">清空</el-button>
<el-button size="small" type="primary" :loading="submitLoading" :disabled="hasErrors || items.length===0" @click="submit">提交</el-button>
<el-button size="small" @click="validateAll">校验</el-button>
<div style="flex:1"></div>
<el-tag type="info">总行: {{ items.length }}</el-tag>
<el-tag type="danger" v-if="errorCount>0">错误: {{ errorCount }}</el-tag>
</div>
<div class="virtual-table-wrap">
<div class="virtual-table">
<div class="virtual-table-header virtual-table-row">
<div class="cell cell-space-code">仓位编码</div>
<div class="cell cell-custom-name">自定义名称</div>
<div class="cell cell-custom-barcode">自定义条码</div>
<div class="cell cell-pick-sequence">拣货顺序</div>
<div class="cell cell-location-type">库位类型</div>
<div class="cell cell-error">错误</div>
<div class="cell cell-action">操作</div>
</div>
<RecycleScroller
class="virtual-table-body"
:items="items"
:item-size="56"
key-field="__virtualKey"
:buffer="300"
>
<template #default="{ item, index }">
<div class="virtual-table-row" :class="{ 'row-error': !!errors[index] }">
<div class="cell cell-space-code">
{{ getRowValue(item, 'space_code') }}
</div>
<div class="cell cell-custom-name">
<el-input :model-value="getRowValue(item, 'custom_name')" clearable @update:modelValue="(val: any) => (setRowValue(item, 'custom_name', val), onRowChange(index))"></el-input>
</div>
<div class="cell cell-custom-barcode">
<el-input :model-value="getRowValue(item, 'custom_barcode')" clearable @update:modelValue="(val: any) => (setRowValue(item, 'custom_barcode', val), onRowChange(index))"></el-input>
</div>
<div class="cell cell-pick-sequence">
<el-input-number :model-value="getRowValue(item, 'pick_sequence')" :min="0" :controls="false" @change="(val: any) => (setRowValue(item, 'pick_sequence', val), onRowChange(index))"></el-input-number>
</div>
<div class="cell cell-location-type">
<el-select :model-value="getRowValue(item, 'location_type_name')" placeholder="请选择" filterable clearable @change="(val: any) => (setRowValue(item, 'location_type_name', val), onRowChange(index))">
<el-option
v-for="(lt, idx) in locationTypes"
:key="lt.id ?? idx"
:label="lt.label"
:value="lt.value"
/>
</el-select>
</div>
<div class="cell cell-error">
<div v-if="errors[index]">
<el-tooltip :content="errors[index]" placement="top">
<el-tag type="danger">{{ errors[index] }}</el-tag>
</el-tooltip>
</div>
</div>
<div class="cell cell-action">
<el-button link type="primary" size="small" @click="removeRow(index)">移除</el-button>
<el-button link type="primary" size="small" @click="validateRow(index)">校验</el-button>
</div>
</div>
</template>
</RecycleScroller>
</div>
</div>
</div>
</div>
<template #footer>
<el-button @click="close">关闭</el-button>
<el-button type="primary" :loading="submitLoading" :disabled="hasErrors || items.length===0" @click="submit">提交</el-button>
</template>
</el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, computed, nextTick } from 'vue'
import * as XLSX from 'xlsx'
import { RecycleScroller } from 'vue-virtual-scroller'
import * as warehouseApi from '@/api/warehouse/warehouse'
import * as indexApi from '@/api/index/index'
import { ElMessage } from 'element-plus'
import 'vue-virtual-scroller/dist/vue-virtual-scroller.css'
const visible = ref(false)
const loaded = ref(false)
const fileInputRef = ref<HTMLInputElement | null>(null)
const items = ref<any[]>([])
const submitLoading = ref(false)
const rackId = ref<number | null>(null)
const locationTypes = ref<any[]>([])
const errors = reactive<Record<number, string>>({})
const parsedHeaderMap = ref<Record<string, string>>({})
const parsedHeaderKeys = ref<string[]>([])
const emit = defineEmits(['success'])
// 归一化用于匹配的字符串(去空格、去非中英数字、转小写)
const normalizeKey = (s: any) => String(s ?? '').toLowerCase().replace(/\s+/g, '').replace(/[^a-z0-9\u4e00-\u9fa5]/g, '')
function findHeaderKeyForField(field: string) {
for (const [hk, f] of Object.entries(parsedHeaderMap.value || {})) {
if (f === field) return hk
}
return undefined
}
function getRowValue(row: any, field: string) {
if (!row) return undefined
if (row[field] !== undefined) return row[field]
const hk = findHeaderKeyForField(field)
if (hk && row[hk] !== undefined) return row[hk]
return undefined
}
function setRowValue(row: any, field: string, value: any) {
if (!row) return
if (row[field] !== undefined) { row[field] = value; return }
const hk = findHeaderKeyForField(field)
if (hk) { row[hk] = value; return }
row[field] = value
}
function open(id?: number | null) {
rackId.value = id ?? null
visible.value = true
loadLocationTypes()
}
function close() {
visible.value = false
clearData()
}
defineExpose({ open })
function triggerFileSelect() {
fileInputRef.value?.click()
}
async function onFileChange(e: Event) {
const input = e.target as HTMLInputElement
const file = input.files?.[0]
if (!file) return
if (!file.name.toLowerCase().endsWith('.xlsx')) {
ElMessage.warning('仅支持 .xlsx 文件')
input.value = ''
return
}
try {
const arr = await file.arrayBuffer()
const wb = XLSX.read(arr, { type: 'array', dense: true })
const sheetName = Array.isArray(wb.SheetNames) && wb.SheetNames.length ? wb.SheetNames[0] : undefined
if (!sheetName) {
ElMessage.error('Excel 文件不包含工作表')
input.value = ''
return
}
const firstSheet = wb.Sheets[sheetName]
if (!firstSheet) {
ElMessage.error('选择的工作表为空')
input.value = ''
return
}
// read as array of arrays to preserve column order
const matrix: any[] = XLSX.utils.sheet_to_json(firstSheet, { header: 1, defval: '' })
if (!matrix || matrix.length === 0) {
ElMessage.error('空的表格')
input.value = ''
return
}
const headerRow: any[] = matrix[0]
const dataRows = matrix.slice(1)
// build objects preserving header order
const rows: any[] = dataRows.map(r => {
const obj: Record<string, any> = {}
for (let i = 0; i < headerRow.length; i++) {
const key = headerRow[i] ?? `col${i}`
obj[key] = r[i]
}
return obj
})
// pass both rows objects and original matrix rows so parser can force A 列为 space_code
parseRowsToItems(rows, headerRow as string[])
input.value = ''
} catch (err) {
console.error(err)
ElMessage.error('解析文件失败')
}
}
function parseRowsToItems(rows: any[], headerOrder?: string[]) {
const mapped: any[] = []
// build header -> field map using explicit headerOrder (preserves A列顺序) or fallback to object keys
const headerKeys = headerOrder && headerOrder.length ? headerOrder : (rows.length > 0 ? Object.keys(rows[0]) : [])
const normalize = normalizeKey
const candidates: Record<string, string[]> = {
space_code: ['spacecode', 'space_code', '仓位编码', '库位编码', '库位编号', '仓位编号', '库位', '仓位', '库位名称', '仓位名称', '编码', '编号', 'code'],
custom_name: ['customname', 'custom_name', '自定义名称', '自定义名', '名称', 'name'],
custom_barcode: ['custombarcode', 'custom_barcode', '自定义条码', '条码', 'barcode'],
pick_sequence: ['picksequence', 'pick_sequence', '拣货顺序', '拣货', 'pick'],
location_type_name: ['locationtypename', 'location_type_name', '库位类型名称', '库位类型', '仓位类型', '仓位类型名称']
}
// scoring match: exact -> 100, includes -> 80
const headerMap: Record<string, string> = {}
for (const hk of headerKeys) {
const nh = normalize(hk)
let bestField: string | null = null
let bestScore = -1
for (const [field, pats] of Object.entries(candidates)) {
for (const p of pats) {
const np = normalize(p)
let score = -1
if (nh === np) score = 100
else if (nh.includes(np) || np.includes(nh)) score = 80
if (score > bestScore) {
bestScore = score
bestField = field
}
}
}
if (bestField && bestScore > 0) {
headerMap[hk] = bestField
}
}
// fallback: if no space_code mapped, pick header with most non-empty values (excluding barcode-like headers)
if (!Object.values(headerMap).includes('space_code')) {
let bestHeader: string | null = null
let bestCount = -1
const sampleSize = Math.min(rows.length, 20)
for (const hk of headerKeys) {
const nh = normalize(hk)
if (/barcode|条码/.test(nh)) continue
let count = 0
for (let i = 0; i < sampleSize; i++) {
const v = String(rows[i][hk] ?? '').trim()
if (v !== '') count++
}
if (count > bestCount) { bestCount = count; bestHeader = hk }
}
if (bestHeader) {
headerMap[bestHeader] = 'space_code'
// notify user that a fallback was used
ElMessage.info(`未检测到明确的“仓位编码”表头,已使用 "${bestHeader}" 作为仓位编码列。`)
}
}
// 强制将第一列(A 列)映射为仓位编码,符合模板要求
if (headerKeys.length > 0) {
const firstKey = headerKeys[0]!
headerMap[firstKey] = 'space_code'
}
// 保存解析出的 headerMap 与 headerKeys,items 直接使用解析得到的 rows(不再转换字段)
parsedHeaderMap.value = headerMap
parsedHeaderKeys.value = headerKeys
items.value = rows
refreshVirtualKeys()
loaded.value = true
// 如果已有库位类型,把名称转换为 id 再校验;否则直接校验
if (locationTypes.value && locationTypes.value.length) {
remapItemsLocationTypes()
nextTick(() => validateAll())
} else {
nextTick(() => validateAll())
}
}
function remapItemsLocationTypes() {
if (!items.value || !items.value.length) return
// 找到源文件中对应的列名
const hk = findHeaderKeyForField('location_type_name')
items.value.forEach((r: any) => {
const rawStr = String(getRowValue(r, 'location_type_name') ?? '').trim()
// 用名称/id 进行归一化匹配,转换为数字 id;无匹配则设为 null
const rawNorm = normalizeKey(rawStr)
const found = rawStr ? locationTypes.value.find((lt: any) => {
try {
if (normalizeKey(lt.id) === rawNorm) return true
if (normalizeKey(lt.label) === rawNorm) return true
} catch (e) {}
return false
}) : undefined
const mapped = found != null ? found.id : null
if (hk !== undefined) r[hk] = mapped
else r.location_type_name = mapped
})
}
function removeRow(index: number) {
items.value.splice(index, 1)
refreshVirtualKeys()
nextTick(() => validateAll())
}
function clearData() {
items.value = []
loaded.value = false
Object.keys(errors).forEach(k => delete errors[Number(k)])
}
function onRowChange(index: number) {
validateRow(index)
}
function refreshVirtualKeys() {
items.value.forEach((row: any, index: number) => {
row.__virtualKey = `row-${index}`
})
}
const errorCount = computed(() => Object.keys(errors).length)
const hasErrors = computed(() => errorCount.value > 0)
async function loadLocationTypes() {
try {
const res: any = await indexApi.getLocationTypeList()
const data = res && (res.data || res.list || res)
const arr = Array.isArray(data) ? data : []
// normalize to { id, label, value } to avoid undefined in template
// prefer numeric id as value when available so imported numeric ids map to the dropdown
// Always normalize option `value` to string to avoid type mismatch in v-model comparisons
// value 直接用数字 id,便于提交时直接取到 id
locationTypes.value = arr.map((lt: any, idx: number) => {
const id = lt?.id ?? lt?.code ?? idx
const label = String(lt?.type_name ?? lt?.name ?? lt?.location_type_name ?? lt?.label ?? id ?? '').trim()
return { id, label, value: id }
})
// 如果已有解析后的 items,尝试把 items 中的库位类型名称映射为 id 并重新校验
if (items.value && items.value.length) {
remapItemsLocationTypes()
nextTick(() => validateAll())
}
} catch (e) {
locationTypes.value = []
}
}
async function validateAll() {
// clear
Object.keys(errors).forEach(k => delete errors[Number(k)])
// basic checks
const codeCounts: Record<string, number> = {}
items.value.forEach((r, i) => {
const code = String(getRowValue(r, 'space_code') ?? '').trim()
if (!code) {
errors[i] = '缺失仓位编码'
}
codeCounts[code] = (codeCounts[code] || 0) + 1
// pick_sequence check
const pickVal = getRowValue(r, 'pick_sequence')
if (pickVal !== null && pickVal !== undefined && pickVal !== '') {
const n = Number(pickVal)
if (isNaN(n) || n < 0 || !Number.isInteger(n)) {
errors[i] = (errors[i] ? errors[i] + ';' : '') + '拣货顺序必须为非负整数'
}
}
// location_type_name 校验:此时存储的应为数字 id 或 null
const locVal = getRowValue(r, 'location_type_name')
if (locVal !== null && locVal !== undefined && String(locVal).trim() !== '') {
const ok = locationTypes.value.some(lt => lt.id === locVal || String(lt.id) === String(locVal))
if (!ok) {
errors[i] = (errors[i] ? errors[i] + ';' : '') + '库位类型无效'
}
}
})
// duplicates within batch
for (const [code, cnt] of Object.entries(codeCounts)) {
if (!code) continue
if (cnt > 1) {
items.value.forEach((r, i) => {
if (String(getRowValue(r, 'space_code') ?? '').trim() === code) {
errors[i] = (errors[i] ? errors[i] + ';' : '') + '仓位编码在批次内重复'
}
})
}
}
// remote checks: rack membership or existence
if (rackId.value) {
try {
const resp: any = await warehouseApi.getSpacesByRack(rackId.value)
const allowed = Array.isArray(resp.spaces) ? resp.spaces.map((s:any) => String(s.space_code || '').trim()) : []
const allowSet = new Set(allowed)
items.value.forEach((r, i) => {
const code = String(getRowValue(r, 'space_code') ?? '').trim()
if (code && !allowSet.has(code)) {
errors[i] = (errors[i] ? errors[i] + ';' : '') + '仓位不属于当前货架'
}
})
} catch (e) {
// ignore
}
} else {
// validate existence by searchSpaces(一次批量查询,分组与关键词一一对应)
const uniques = Array.from(
new Set(items.value.map((r) => String(getRowValue(r, 'space_code') ?? '').trim()).filter(Boolean))
)
if (!uniques.length) return
const markRowsByCode = (code: string, message: string) => {
items.value.forEach((r, i) => {
if (String(getRowValue(r, 'space_code') ?? '').trim() === code) {
errors[i] = (errors[i] ? errors[i] + ';' : '') + message
}
})
}
try {
const res: any = await indexApi.searchSpaces({ keywords: uniques })
const data = res && (res.data || res.list || res)
const groups = Array.isArray(data?.list) ? data.list : Array.isArray(data) ? data : []
uniques.forEach((code, codeIndex) => {
const list = Array.isArray(groups[codeIndex]) ? groups[codeIndex] : []
const item = list[0] || null
if (!item) {
// mark all rows with this code
markRowsByCode(code, '仓位不存在')
} else {
// if item has zone/type info and not rack, try to detect
const zoneType = item.zone?.zone_type || item.zone_type || item.type || item.parent_type || ''
if (zoneType && String(zoneType) !== 'rack') {
markRowsByCode(code, '仓位不属于货架类型')
}
}
})
} catch (e) {
uniques.forEach((code) => markRowsByCode(code, '仓位校验失败'))
}
}
}
function validateRow(index: number) {
const r = items.value[index]
if (!r) return
delete errors[index]
const code = String(getRowValue(r, 'space_code') ?? '').trim()
if (!code) {
errors[index] = '缺失仓位编码'
}
const pickVal = getRowValue(r, 'pick_sequence')
if (pickVal !== null && pickVal !== undefined && pickVal !== '') {
const n = Number(pickVal)
if (isNaN(n) || n < 0 || !Number.isInteger(n)) {
errors[index] = (errors[index] ? errors[index] + ';' : '') + '拣货顺序必须为非负整数'
}
}
const locVal = getRowValue(r, 'location_type_name')
if (locVal !== null && locVal !== undefined && String(locVal).trim() !== '') {
const ok = locationTypes.value.some((lt) => lt.id === locVal || String(lt.id) === String(locVal))
if (!ok) {
errors[index] = (errors[index] ? errors[index] + ';' : '') + '库位类型无效'
}
}
}
async function submit() {
await validateAll()
if (hasErrors.value) {
ElMessage.warning('请先修正错误后再提交')
return
}
if (!items.value.length) {
ElMessage.warning('没有数据可提交')
return
}
submitLoading.value = true
try {
const payload: any = { items: items.value.map((r: any) => {
const spaceCode = String(getRowValue(r, 'space_code') ?? '').trim()
const customName = getRowValue(r, 'custom_name')
const customBarcode = getRowValue(r, 'custom_barcode')
const pickSeq = getRowValue(r, 'pick_sequence')
const locId = getRowValue(r, 'location_type_name') // 已经是数字 id 或 null
return {
space_code: spaceCode,
custom_name: customName != null ? String(customName) : undefined,
custom_barcode: customBarcode != null ? String(customBarcode) : undefined,
pick_sequence: pickSeq === null || pickSeq === undefined || pickSeq === '' ? undefined : Number(pickSeq),
location_type_id: locId != null && String(locId).trim() !== '' ? Number(locId) : undefined
}
}) }
if (rackId.value) payload.id = rackId.value
const res: any = await warehouseApi.batchUpdateSpaceInfo(payload)
const ok = res && (res.code === 1 || res.code === 200 || res.flag === 'success')
if (!ok) {
ElMessage.error(res?.message || '批量修改失败')
return
}
ElMessage.success(res?.message || '批量修改成功')
emit('success')
close()
} catch (e:any) {
console.error('批量修改失败', e)
ElMessage.error(e?.message || '批量修改失败')
} finally {
submitLoading.value = false
}
}
</script>
<style scoped>
.empty-container {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
}
.virtual-table-wrap {
flex: 1;
overflow: auto;
padding: 8px;
}
.virtual-table {
min-width: 960px;
border: 1px solid var(--el-border-color-lighter);
border-radius: 4px;
overflow: hidden;
}
.virtual-table-header {
background: var(--el-fill-color-light);
font-weight: 500;
border-bottom: 1px solid var(--el-border-color-lighter);
}
.virtual-table-body {
height: 420px;
}
.virtual-table-row {
display: flex;
align-items: center;
min-height: 56px;
border-bottom: 1px solid var(--el-border-color-lighter);
}
.virtual-table-row:last-child {
border-bottom: none;
}
.cell {
box-sizing: border-box;
padding: 8px;
border-right: 1px solid var(--el-border-color-lighter);
}
.cell:last-child {
border-right: none;
}
.cell-space-code {
width: 160px;
}
.cell-custom-name {
width: 160px;
}
.cell-custom-barcode {
width: 120px;
}
.cell-pick-sequence {
width: 120px;
}
.cell-location-type {
width: 120px;
}
.cell-error {
width: 160px;
}
.cell-action {
width: 120px;
}
.cell-pick-sequence :deep(.el-input-number),
.cell-location-type :deep(.el-select),
.cell-custom-name :deep(.el-input),
.cell-custom-barcode :deep(.el-input) {
width: 100%;
}
.row-error {
background: #fff6f6 !important;
}
</style>