WEB/src/views/material/packageMaterial/component/BatchImportDialog.vue
liufumingren a680b9e9b2 1
2026-06-15 09:10:53 +08:00

441 lines
13 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="批量导入包材"
align-center
width="1020px"
append-to-body
destroy-on-close
:close-on-click-modal="false"
>
<div class="batch-import-toolbar">
<input
ref="importInputRef"
type="file"
accept=".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
style="display: none"
@change="handleFileChange"
/>
<el-button @click="triggerFileSelect">选择Excel</el-button>
<el-button @click="downloadTemplate">下载模板</el-button>
<el-button @click="clearData">清除数据</el-button>
<el-button :loading="retryLoading" @click="retryFailedRows">只重试失败</el-button>
<el-button type="primary" :loading="importLoading" @click="submitBatchImport">导入</el-button>
<span class="picker-hint">已选文件:{{ fileName || '未选择' }}</span>
</div>
<div class="picker-table-wrap">
<UpperTable
:data="previewRows"
:show-selection="false"
:pagination="{ currentPage: 1, pageSize: 200, total: previewRows.length }"
:columns="previewColumns"
>
<template #column-row_no="{ row }">
{{ row.row_no }}
</template>
<template #column-material_code="{ row }">
<span :class="{ 'cell-required-empty': !row.material_code && row.import_status !== '成功' }">
{{ row.material_code || '--' }}
</span>
</template>
<template #column-material_name="{ row }">
<span :class="{ 'cell-required-empty': !row.material_name && row.import_status !== '成功' }">
{{ row.material_name || '--' }}
</span>
</template>
<template #column-length="{ row }">
{{ formatCellNumber(row.length) }}
</template>
<template #column-width="{ row }">
{{ formatCellNumber(row.width) }}
</template>
<template #column-height="{ row }">
{{ formatCellNumber(row.height) }}
</template>
<template #column-weight="{ row }">
{{ formatCellNumber(row.weight) }}
</template>
<template #column-cost_price="{ row }">
{{ formatCellNumber(row.cost_price) }}
</template>
<template #column-status="{ row }">
{{ formatStatusLabel(row.status) }}
</template>
<template #column-import_status="{ row }">
<el-tag v-if="row.import_status === '成功'" type="success" size="small">成功</el-tag>
<el-tag v-else-if="row.import_status === '失败'" type="danger" size="small">失败</el-tag>
<el-tag v-else type="info" size="small">待导入</el-tag>
</template>
<template #column-import_message="{ row }">
{{ row.import_message || '--' }}
</template>
<template #column-retry_action="{ row }">
<el-button
v-if="row.import_status === '失败'"
type="primary"
link
size="small"
:loading="row._retrying"
@click="retrySingleRow(row)"
>
重试
</el-button>
<span v-else>--</span>
</template>
</UpperTable>
</div>
<template #footer>
<el-button @click="visible = false">关闭</el-button>
</template>
</el-dialog>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import * as XLSX from 'xlsx'
import UpperTable from '@/components/UpperTable/index.vue'
import { packageMaterialCreate } from '@/api/setting.packagematerial/packagematerial'
import type { PackageMaterialRecord } from '../package-material-config'
const visible = defineModel<boolean>({ default: false })
const emit = defineEmits<{
success: []
}>()
const importInputRef = ref<HTMLInputElement | null>(null)
const importLoading = ref(false)
const retryLoading = ref(false)
const fileName = ref('')
interface ImportPreviewRow extends PackageMaterialRecord {
row_no: number
import_status: string
import_message: string
_retrying?: boolean
}
const previewRows = ref<ImportPreviewRow[]>([])
const previewColumns = [
{ prop: 'row_no', label: '行号', width: '70' },
{ prop: 'material_code', label: '包材编码', minWidth: '120' },
{ prop: 'material_name', label: '包材名称', minWidth: '140' },
{ prop: 'material_type', label: '包材类型', minWidth: '110' },
{ prop: 'spec', label: '规格', minWidth: '110' },
{ prop: 'length', label: '长度', width: '80' },
{ prop: 'width', label: '宽度', width: '80' },
{ prop: 'height', label: '高度', width: '80' },
{ prop: 'weight', label: '重量', width: '80' },
{ prop: 'cost_price', label: '成本价', width: '90' },
{ prop: 'status', label: '状态', width: '70' },
{ prop: 'import_status', label: '导入状态', width: '100' },
{ prop: 'import_message', label: '结果说明', minWidth: '180' },
{ prop: 'retry_action', label: '操作', width: '80' }
]
watch(visible, (opened) => {
if (!opened) {
fileName.value = ''
previewRows.value = []
}
})
function triggerFileSelect() {
importInputRef.value?.click()
}
function downloadTemplate() {
const headers = [
'包材编码',
'包材名称',
'包材类型',
'规格',
'长度',
'宽度',
'高度',
'重量',
'成本价',
'状态'
]
const sample = ['PM001', '示例纸箱', '纸箱', '60×40×30cm', 60, 40, 30, 0.5, 2.5, '启用']
const ws = XLSX.utils.aoa_to_sheet([headers, sample])
ws['!cols'] = headers.map(() => ({ wch: 16 }))
const wb = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(wb, ws, '批量导入包材')
XLSX.writeFile(wb, `包材导入模板_${Date.now()}.xlsx`)
}
function clearData() {
previewRows.value = []
fileName.value = ''
if (importInputRef.value) {
importInputRef.value.value = ''
}
}
function pickImportValue(row: Record<string, any>, keys: string[]): 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 String(v).trim()
}
}
}
return ''
}
function toImportNumber(val: any): number | undefined {
const text = String(val ?? '').trim()
if (!text) return undefined
const num = Number(text)
return Number.isFinite(num) ? num : undefined
}
function parseStatus(val: string): number {
const text = val.trim()
if (['1', '启用', 'enable', 'enabled', 'active', '是', 'yes', 'true'].some(
(s) => s.toLowerCase() === text.toLowerCase()
)) {
return 1
}
if (['0', '停用', 'disable', 'disabled', 'inactive', '否', 'no', 'false'].some(
(s) => s.toLowerCase() === text.toLowerCase()
)) {
return 0
}
return 1
}
function formatCellNumber(val: any): string {
if (val === null || val === undefined || val === '') return '--'
const num = Number(val)
return Number.isFinite(num) ? String(num) : '--'
}
function formatStatusLabel(status: any): string {
return status === 0 ? '停用' : '启用'
}
async function parseExcelFile(file: File) {
const buffer = await file.arrayBuffer()
const workbook = XLSX.read(buffer, { type: 'array' })
const sheetName = workbook.SheetNames[0]
if (!sheetName) {
ElMessage.warning('Excel 中没有可读取的工作表')
return []
}
const sheet = workbook.Sheets[sheetName]
if (!sheet) {
ElMessage.warning('工作表读取失败')
return []
}
const rawRows = XLSX.utils.sheet_to_json<Record<string, any>>(sheet, { defval: '' })
const result: ImportPreviewRow[] = []
for (let index = 0; index < rawRows.length; index += 1) {
const row = rawRows[index] || {}
const materialCode = pickImportValue(row, ['包材编码', 'material_code', 'materialCode'])
const materialName = pickImportValue(row, ['包材名称', 'material_name', 'materialName'])
// 跳过空行
if (!materialCode && !materialName) continue
const materialType = pickImportValue(row, ['包材类型', 'material_type', 'materialType'])
const spec = pickImportValue(row, ['规格', 'spec'])
const length = toImportNumber(pickImportValue(row, ['长度', 'length']))
const width = toImportNumber(pickImportValue(row, ['宽度', 'width']))
const height = toImportNumber(pickImportValue(row, ['高度', 'height']))
const weight = toImportNumber(pickImportValue(row, ['重量', 'weight']))
const costPrice = toImportNumber(pickImportValue(row, ['成本价', 'cost_price', 'costPrice']))
const status = parseStatus(pickImportValue(row, ['状态', 'status']))
result.push({
row_no: index + 2,
material_code: materialCode,
material_name: materialName,
material_type: materialType || undefined,
spec: spec || undefined,
length,
width,
height,
weight,
cost_price: costPrice,
status,
import_status: '待导入',
import_message: ''
})
}
return result
}
async function handleFileChange(event: Event) {
const input = event.target as HTMLInputElement
const file = input?.files?.[0]
input.value = ''
if (!file) return
const lowerName = file.name.toLowerCase()
if (!lowerName.endsWith('.xlsx')) {
ElMessage.warning('仅支持上传 .xlsx 文件')
return
}
fileName.value = file.name
try {
const rows = await parseExcelFile(file)
if (!rows.length) {
ElMessage.warning('未解析到有效数据行,请检查 Excel 内容')
return
}
previewRows.value = rows
ElMessage.success(`已解析 ${rows.length} 条包材数据`)
} catch (error) {
console.error('解析 Excel 失败', error)
ElMessage.error('解析 Excel 失败')
previewRows.value = []
}
}
function buildCreatePayload(row: ImportPreviewRow) {
const payload: Record<string, unknown> = {
material_code: row.material_code,
material_name: row.material_name,
status: row.status
}
if (row.material_type) payload.material_type = row.material_type
if (row.spec) payload.spec = row.spec
if (row.length !== undefined && row.length !== null) payload.length = row.length
if (row.width !== undefined && row.width !== null) payload.width = row.width
if (row.height !== undefined && row.height !== null) payload.height = row.height
if (row.weight !== undefined && row.weight !== null) payload.weight = row.weight
if (row.cost_price !== undefined && row.cost_price !== null) payload.cost_price = row.cost_price
return payload
}
async function importSingleRow(row: ImportPreviewRow): Promise<boolean> {
try {
const payload = buildCreatePayload(row)
const res: any = await packageMaterialCreate(payload as any)
const ok = res && [0, 1, 200].includes(res.code)
if (ok) {
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
}
}
async function submitBatchImport() {
if (!previewRows.value.length) {
ElMessage.warning('请先选择 Excel 文件')
return
}
// 基础校验
const pendingRows = previewRows.value.filter((r) => r.import_status !== '成功')
for (const row of pendingRows) {
if (!row.material_code) {
ElMessage.warning(`第 ${row.row_no} 行缺少包材编码,请修正后重试`)
return
}
if (!row.material_name) {
ElMessage.warning(`第 ${row.row_no} 行缺少包材名称,请修正后重试`)
return
}
}
importLoading.value = true
let successCount = 0
try {
for (const row of pendingRows) {
const ok = await importSingleRow(row)
if (ok) successCount += 1
}
ElMessage.success(`导入完成:成功 ${successCount} 条,共 ${pendingRows.length} 条`)
if (successCount > 0) {
emit('success')
}
} finally {
importLoading.value = false
}
}
async function retryFailedRows() {
const failedRows = previewRows.value.filter((r) => r.import_status === '失败')
if (!failedRows.length) {
ElMessage.warning('当前没有失败行可重试')
return
}
retryLoading.value = true
let successCount = 0
try {
for (const row of failedRows) {
const ok = await importSingleRow(row)
if (ok) successCount += 1
}
ElMessage.success(`重试完成:成功 ${successCount} 条,共 ${failedRows.length} 条`)
if (successCount > 0) {
emit('success')
}
} finally {
retryLoading.value = false
}
}
async function retrySingleRow(row: ImportPreviewRow) {
row._retrying = true
try {
const ok = await importSingleRow(row)
if (ok) {
ElMessage.success(`第 ${row.row_no} 行重试成功`)
emit('success')
}
} finally {
row._retrying = false
}
}
</script>
<style lang="scss" scoped>
.batch-import-toolbar {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 12px;
flex-wrap: wrap;
.picker-hint {
color: #909399;
font-size: 13px;
margin-left: auto;
}
}
.picker-table-wrap {
max-height: 480px;
overflow: auto;
}
.cell-required-empty {
color: #f56c6c;
font-weight: 500;
}
</style>