531 lines
20 KiB
Vue
531 lines
20 KiB
Vue
<template>
|
||
<el-dialog
|
||
v-model="visible"
|
||
title="导入批量修改"
|
||
width="1000px"
|
||
top="calc(50% - 250px)"
|
||
: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 style="flex:1;overflow:auto;padding:8px;">
|
||
<el-table :data="items" stripe size="small" border style="width:100%" :row-class-name="rowClassName">
|
||
<el-table-column prop="space_code" label="仓位编码" width="160">
|
||
<template #default="{ row }">
|
||
<div>{{ getRowValue(row, 'space_code') }}</div>
|
||
</template>
|
||
</el-table-column>
|
||
|
||
<el-table-column prop="custom_name" label="自定义名称" width="160">
|
||
<template #default="{ row, $index }">
|
||
<el-input :model-value="getRowValue(row, 'custom_name')" clearable @update:modelValue="(val: any) => (setRowValue(row, 'custom_name', val), onRowChange($index))"></el-input>
|
||
</template>
|
||
</el-table-column>
|
||
|
||
<el-table-column prop="custom_barcode" label="自定义条码" width="120">
|
||
<template #default="{ row, $index }">
|
||
<el-input :model-value="getRowValue(row, 'custom_barcode')" clearable @update:modelValue="(val: any) => (setRowValue(row, 'custom_barcode', val), onRowChange($index))"></el-input>
|
||
</template>
|
||
</el-table-column>
|
||
|
||
<el-table-column prop="pick_sequence" label="拣货顺序" width="120">
|
||
<template #default="{ row, $index }">
|
||
<el-input-number :model-value="getRowValue(row, 'pick_sequence')" :min="0" :controls="false" @change="(val: any) => (setRowValue(row, 'pick_sequence', val), onRowChange($index))"></el-input-number>
|
||
</template>
|
||
</el-table-column>
|
||
|
||
<el-table-column prop="location_type_name" label="库位类型" width="120">
|
||
<template #default="{ row, $index }">
|
||
<el-select :model-value="getRowValue(row, 'location_type_name')" placeholder="请选择" filterable clearable @change="(val: any) => (setRowValue(row, '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>
|
||
</template>
|
||
</el-table-column>
|
||
|
||
<el-table-column label="错误" width="160">
|
||
<template #default="{ row, $index }">
|
||
<div v-if="errors[$index]">
|
||
<el-tooltip :content="errors[$index]" placement="top">
|
||
<el-tag type="danger">{{ errors[$index] }}</el-tag>
|
||
</el-tooltip>
|
||
</div>
|
||
</template>
|
||
</el-table-column>
|
||
|
||
<el-table-column label="操作" width="120">
|
||
<template #default="{ row, $index }">
|
||
<el-button link type="primary" size="small" @click="removeRow($index)">移除</el-button>
|
||
<el-button link type="primary" size="small" @click="validateRow($index)">校验</el-button>
|
||
</template>
|
||
</el-table-column>
|
||
</el-table>
|
||
</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 * as warehouseApi from '@/api/warehouse/warehouse'
|
||
import * as indexApi from '@/api/index/index'
|
||
import { ElMessage } from 'element-plus'
|
||
|
||
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' })
|
||
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
|
||
})
|
||
// 打印调试信息,便于排查列映射问题(只打印前几行)
|
||
try {
|
||
console.log('RackBulkModifyDialog headerRow:', headerRow)
|
||
console.log('RackBulkModifyDialog matrix sample:', matrix.slice(0, Math.min(5, matrix.length)))
|
||
console.log('RackBulkModifyDialog dataRows sample:', dataRows.slice(0, Math.min(5, dataRows.length)))
|
||
console.log('RackBulkModifyDialog parsed rows sample:', rows.slice(0, Math.min(5, rows.length)))
|
||
console.log('RackBulkModifyDialog locationTypes:', locationTypes.value)
|
||
} catch (e) {
|
||
// ignore
|
||
}
|
||
// 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
|
||
}
|
||
}
|
||
|
||
try {
|
||
console.log('RackBulkModifyDialog headerMap:', headerMap, 'headerKeys:', headerKeys)
|
||
} catch (e) {}
|
||
|
||
// 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
|
||
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)
|
||
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 rowClassName({ row, rowIndex }: any) {
|
||
return errors[rowIndex] ? 'row-error' : ''
|
||
}
|
||
|
||
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 searchSpace
|
||
const uniques = Array.from(new Set(items.value.map(r => String(r.space_code || '').trim()).filter(Boolean)))
|
||
await Promise.all(uniques.map(async (code) => {
|
||
try {
|
||
const res: any = await indexApi.searchSpace({ keyword: code })
|
||
const data = res && (res.data || res.list || res)
|
||
const item = Array.isArray(data) ? (data[0] || null) : data
|
||
if (!item) {
|
||
// mark all rows with this code
|
||
items.value.forEach((r, i) => {
|
||
if (String(getRowValue(r, 'space_code') ?? '').trim() === code) {
|
||
errors[i] = (errors[i] ? errors[i] + ';' : '') + '仓位不存在'
|
||
}
|
||
})
|
||
} 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') {
|
||
items.value.forEach((r, i) => {
|
||
if (String(getRowValue(r, 'space_code') ?? '').trim() === code) {
|
||
errors[i] = (errors[i] ? errors[i] + ';' : '') + '仓位不属于货架类型'
|
||
}
|
||
})
|
||
}
|
||
}
|
||
} catch (e) {
|
||
items.value.forEach((r, i) => {
|
||
if (String(r.space_code || '').trim() === code) {
|
||
errors[i] = (errors[i] ? errors[i] + ';' : '') + '仓位校验失败'
|
||
}
|
||
})
|
||
}
|
||
}))
|
||
}
|
||
}
|
||
|
||
async function validateRow(index: number) {
|
||
// re-run validateAll for simplicity
|
||
await validateAll()
|
||
}
|
||
|
||
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;
|
||
}
|
||
.row-error td {
|
||
background: #fff6f6 !important;
|
||
}
|
||
</style>
|