WEB/src/views/warehouse/PropertyForm.vue
2026-04-15 21:01:12 +08:00

519 lines
17 KiB
Vue

<template>
<div class="property-form">
<!-- 标题栏 -->
<div class="form-header">
<div class="space-info">
<el-tag type="success" size="small">
仓位编码: {{ formData.space_code }}
</el-tag>
<el-tag :type="getStatusTagType(formData.space_status)" size="small">
{{ getStatusText(formData.space_status) }}
</el-tag>
<el-tag v-if="formData.is_enabled === 0" type="danger" size="small">
已禁用
</el-tag>
</div>
<el-button-group>
<el-button type="primary" size="small" icon="el-icon-edit" @click="handleEdit" :disabled="!props.spaceId || loading">
{{ isEditing ? '保存修改' : '编辑属性' }}
</el-button>
<el-button v-if="isEditing" type="warning" size="small" icon="el-icon-refresh" @click="handleCancel">
取消编辑
</el-button>
</el-button-group>
</div>
<!-- 表单内容 -->
<el-form v-if="props.spaceId" ref="propertyFormRef" :model="formData" :rules="formRules" label-width="100px"
:disabled="!isEditing" size="small" class="property-form-content">
<el-row :gutter="20">
<el-col :span="12">
<el-form-item label="自定义名称" prop="custom_name">
<el-input v-model="formData.custom_name" placeholder="请输入自定义名称" :maxlength="100" show-word-limit />
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="自定义条码" prop="custom_barcode">
<el-input v-model="formData.custom_barcode" placeholder="请输入自定义条码" :maxlength="100" show-word-limit
@blur="handleBarcodeBlur" @input="handleBarcodeInput" clearable />
<div class="form-tip">
<span v-if="barcodeLoading">
<i class="el-icon-loading"></i> 正在检测条码...
</span>
<span v-else-if="barcodeError" class="error">
<i class="el-icon-error"></i> {{ barcodeError }}
</span>
<span v-else-if="barcodeValid" class="success">
<i class="el-icon-success"></i> 条码可用
</span>
<span v-else>可用于扫码识别</span>
</div>
</el-form-item>
</el-col>
</el-row>
<el-row :gutter="20">
<el-col :span="12">
<el-form-item label="仓位类型" prop="location_type_id">
<el-select v-model="formData.location_type_id" placeholder="请选择仓位类型" style="width: 100%;"
:loading="typeLoading">
<el-option v-for="type in locationTypes" :key="type.id" :label="type.type_name" :value="type.id" />
</el-select>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="拣货顺序" prop="pick_sequence">
<el-input-number v-model="formData.pick_sequence" placeholder="拣货顺序" :step="1" :min="0" :max="9999"
style="width: 100%;" controls-position="right" />
<div class="form-tip">数值越小越优先</div>
</el-form-item>
</el-col>
</el-row>
<el-row :gutter="20">
<el-col :span="12">
<el-form-item label="启用状态" prop="is_enabled">
<el-switch v-model="formData.is_enabled" :active-value="1" :inactive-value="0" active-text="启用"
inactive-text="禁用" :disabled="!isEditing || formData.space_status === 'OCCUPIED'" />
<div v-if="formData.space_status === 'OCCUPIED'" class="form-tip error">
仓位被占用时不可禁用
</div>
</el-form-item>
</el-col>
</el-row>
</el-form>
<!-- 空状态 -->
<div v-if="!loading && !props.spaceId" class="empty-state">
<el-empty description="请先选择仓位" :image-size="100" />
</div>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, watch, onMounted, onBeforeUnmount, getCurrentInstance, } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as warehouseApi from '@/api/warehouse/warehouse'
const props = defineProps({
title: { type: String, default: '仓位属性管理' },
spaceId: { type: [String, Number], default: null }
})
const emit = defineEmits(['spaceSave'])
// 表单相关
function getDefaultFormData() {
return {
id: null,
space_code: '',
custom_name: '',
custom_barcode: '',
location_type_id: null,
pick_sequence: 0,
is_enabled: 1,
space_status: 'AVAILABLE'
}
}
const formData = reactive<any>(getDefaultFormData())
let originalData: any = null
const isEditing = ref(false)
const loading = ref(false)
const saving = ref(false)
// 条码检测
const barcodeLoading = ref(false)
const barcodeValid = ref(false)
const barcodeError = ref('')
let barcodeCheckTimer: any = null
// 下拉
const locationTypes = ref<any[]>([])
const typeLoading = ref(false)
// 表单 ref & rules
const propertyFormRef = ref(null)
const formRules = {
custom_name: [{ max: 100, message: '长度不能超过100个字符', trigger: 'blur' }],
custom_barcode: [
{ max: 100, message: '长度不能超过100个字符', trigger: 'blur' },
{ validator: (rule:any, value:any, callback:any) => validateBarcode(rule, value, callback), trigger: 'blur' }
],
location_type_id: [{ required: true, message: '请选择仓位类型', trigger: 'change' }],
pick_sequence: [{ type: 'number', min: 0, max: 9999, message: '拣货顺序必须在0-9999之间', trigger: 'blur' }]
}
// 监听 props.spaceId
watch(() => props.spaceId, (newId) => {
if (newId) {
loadSpaceData(newId)
} else {
resetForm()
}
}, { immediate: true })
// 监听 is_enabled 和 space_status 的变化
watch(() => formData.is_enabled, (newValue) => {
if (isEditing.value) {
if (newValue === 1) {
formData.space_status = 'AVAILABLE'
} else if (newValue === 0) {
formData.space_status = 'DISABLED'
}
}
})
watch(() => formData.space_status, (newValue) => {
if (isEditing.value && newValue === 'OCCUPIED') {
formData.is_enabled = 1
}
})
onMounted(() => {
loadLocationTypes()
})
onBeforeUnmount(() => {
if (barcodeCheckTimer) clearTimeout(barcodeCheckTimer)
})
// 获取状态标签样式与文字
function getStatusTagType(status: string) {
const map: any = {
'AVAILABLE': 'success',
'OCCUPIED': 'info',
'RESERVED': 'warning',
'MAINTENANCE': 'warning',
'DISABLED': 'danger'
}
return map[status] || 'info'
}
function getStatusText(status: string) {
const map: any = {
'AVAILABLE': '可用',
'OCCUPIED': '占用',
'RESERVED': '预留',
'MAINTENANCE': '维护中',
'DISABLED': '禁用'
}
return map[status] || status
}
// 加载仓位数据
async function loadSpaceData(spaceId: any) {
loading.value = true
isEditing.value = false
resetBarcodeStatus()
try {
const response: any = await warehouseApi.getSpaceInfo(spaceId)
if (response.code == 200) {
const data = response.data
const fd = {
id: data.id,
space_code: data.space_code || '',
custom_name: data.custom_name || '',
custom_barcode: data.custom_barcode || '',
location_type_id: data.location_type_id || null,
pick_sequence: data.pick_sequence || 0,
is_enabled: data.is_enabled === undefined ? 1 : data.is_enabled,
space_status: data.space_status || 'AVAILABLE'
}
if (fd.is_enabled === 0) {
fd.space_status = 'DISABLED'
} else if (fd.space_status === 'DISABLED') {
fd.is_enabled = 0
}
originalData = { ...fd }
Object.assign(formData, fd)
} else {
ElMessage.error(response.message || '加载仓位数据失败')
}
} catch (error) {
console.error('加载仓位数据失败:', error)
ElMessage.error('加载仓位数据失败')
} finally {
loading.value = false
}
}
// 加载仓位类型
async function loadLocationTypes() {
typeLoading.value = true
try {
locationTypes.value = [
{ id: 1, type_name: '普通仓位' },
{ id: 2, type_name: '拣货仓位' },
{ id: 3, type_name: '存储仓位' }
]
} catch (error) {
console.error('加载仓位类型失败:', error)
} finally {
typeLoading.value = false
}
}
// 条码输入/失去焦点/检测
function handleBarcodeInput() {
barcodeValid.value = false
barcodeError.value = ''
if (barcodeCheckTimer) clearTimeout(barcodeCheckTimer)
const barcode = formData.custom_barcode
if (barcode && barcode.length > 0) {
barcodeCheckTimer = setTimeout(() => { checkBarcodeUnique(barcode) }, 500)
}
}
function handleBarcodeBlur() {
const barcode = formData.custom_barcode
if (barcode && barcode.length > 0) {
checkBarcodeUnique(barcode)
}
}
async function checkBarcodeUnique(barcode: string) {
if (originalData && originalData.custom_barcode === barcode) {
barcodeValid.value = true
barcodeError.value = ''
return
}
if (!barcode || barcode.trim() === '') {
resetBarcodeStatus()
return
}
barcodeLoading.value = true
barcodeValid.value = false
barcodeError.value = ''
try {
const response: any = await warehouseApi.checkBarcodeUnique({ id: props.spaceId, barcode: barcode.trim() })
if (response.code == 200) {
const data = response.data
if (data.isUnique) {
barcodeValid.value = true
barcodeError.value = ''
} else {
barcodeValid.value = false
barcodeError.value = data.message || '该条码已被其他仓位使用'
}
} else {
barcodeValid.value = false
barcodeError.value = response.message || '条码检测失败'
}
} catch (error) {
console.error('条码检测失败:', error)
barcodeValid.value = false
barcodeError.value = '条码检测失败,请稍后重试'
} finally {
barcodeLoading.value = false
}
}
function resetBarcodeStatus() {
barcodeLoading.value = false
barcodeValid.value = false
barcodeError.value = ''
}
function validateBarcode(rule: any, value: any, callback: any) {
if (!value || value.trim() === '') { callback(); return }
const pattern = /^[A-Za-z0-9_-]+$/
if (!pattern.test(value)) { callback(new Error('条码只能包含字母、数字、下划线和短横线')); return }
if (value.length > 100) { callback(new Error('条码长度不能超过100个字符')); return }
if (barcodeLoading.value) { callback(new Error('正在检测条码唯一性...')); return }
if (!barcodeValid.value && barcodeError.value) { callback(new Error(barcodeError.value)); return }
callback()
}
// 编辑/保存/取消
function handleEdit() {
if (!isEditing.value) {
isEditing.value = true
originalData = { ...formData }
resetBarcodeStatus()
} else {
handleSave()
}
}
async function handleSave() {
let valid = true
try {
await (propertyFormRef.value as any).validate()
} catch (e) { valid = false }
if (!valid) {
ElMessage.warning('请检查表单填写是否正确')
return
}
const barcode = formData.custom_barcode
if (barcode && barcode.trim() !== '') {
if (originalData && originalData.custom_barcode !== barcode && !barcodeValid.value) {
if (!barcodeError.value) {
await checkBarcodeUnique(barcode)
if (!barcodeValid.value) { ElMessage.warning('请先完成条码检测'); return }
} else { ElMessage.warning(barcodeError.value); return }
}
}
if (formData.space_status === 'OCCUPIED' && formData.is_enabled === 0) {
ElMessage.warning('占用状态的仓位不可禁用')
return
}
saving.value = true
try {
const instance = getCurrentInstance()
const globalStore: any = instance?.appContext.config.globalProperties.$store
const userId = (globalStore && globalStore.state && globalStore.state.user && globalStore.state.user.userId) || 1
const submitData: any = {
id: formData.id,
custom_name: formData.custom_name,
custom_barcode: formData.custom_barcode,
location_type_id: formData.location_type_id,
pick_sequence: formData.pick_sequence,
is_enabled: formData.is_enabled,
space_status: formData.space_status,
updated_by: userId
}
const response: any = await warehouseApi.updateSpaceInfo(submitData)
if (response.code == 200) {
ElMessage.success('仓位属性保存成功')
isEditing.value = false
originalData = { ...formData }
emit('spaceSave', { ...formData })
} else {
ElMessage.error(response.message || '保存失败')
}
} catch (error) {
console.error('保存失败:', error)
ElMessage.error('保存失败')
} finally {
saving.value = false
}
}
function handleCancel() {
if (originalData) {
Object.assign(formData, originalData)
}
isEditing.value = false
resetBarcodeStatus()
ElMessage.info('已取消编辑')
}
function resetForm() {
Object.assign(formData, getDefaultFormData())
originalData = null
isEditing.value = false
resetBarcodeStatus()
if (propertyFormRef.value) (propertyFormRef.value as any).clearValidate()
}
async function refreshData() {
if (props.spaceId) {
await loadSpaceData(props.spaceId)
ElMessage.success('数据已刷新')
}
}
function getFormData() { return { ...formData } }
function reload() { if (props.spaceId) loadSpaceData(props.spaceId) }
function toggleEnabled(enabled: boolean) {
if (formData.space_status === 'OCCUPIED' && !enabled) {
ElMessage.warning('占用状态的仓位不可禁用')
return false
}
formData.is_enabled = enabled ? 1 : 0
formData.space_status = enabled ? 'AVAILABLE' : 'DISABLED'
return true
}
defineExpose({ getFormData, reload, refreshData, toggleEnabled })
</script>
<style scoped lang="scss">
.property-form {
height: 100%;
display: flex;
flex-direction: column;
.form-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
padding: 15px 0;
border-bottom: 1px solid #ebeef5;
.space-info {
flex: 1;
display: flex;
align-items: center;
gap: 8px;
}
}
.property-form-content {
flex: 1;
.el-form-item {
margin-bottom: 20px;
}
}
.loading-container {
flex: 1;
display: flex;
flex-direction: column;
padding: 20px;
}
.empty-state {
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
color: #909399;
}
.form-tip {
font-size: 12px;
margin-top: 4px;
line-height: 1.4;
display: flex;
align-items: center;
gap: 4px;
&.error {
color: #f56c6c;
}
.error {
color: #f56c6c;
}
.success {
color: #67c23a;
}
.el-icon-loading,
.el-icon-error,
.el-icon-success {
font-size: 14px;
}
}
}
</style>