647556386
2026-01-27 1378fc4cd7abc24ed3a982e09437c2c8a74e9f2f
ÏîÄ¿´úÂë/WIDESEA_WMSClient/src/extension/inbound/extend/Pallet.vue
@@ -1,12 +1,11 @@
<template>
  <vol-box v-model="groupPalletVisible" :title="'组盘操作 - å•据号:' + currentDocNo" :height="1000" :width="1100" :padding="20"
    :modal="true" @open="handleDialogOpen" @close="handleDialogClose">
  <vol-box v-model="show" :title="'组盘操作 - å•据号:' + orderNo" :height="1000" :width="1100" :padding="20" :modal="true">
    <div class="barcode-scanner-container">
      <!-- ä»“库选择 - ç´§å‡‘布局 -->
      <div class="location-section compact">
        <el-form :model="form" :rules="rules" ref="locationForm" class="compact-form">
          <el-form-item label="仓库" prop="warehouseType" class="location-select compact-item">
          <el-form-item label="入库仓库" prop="warehouseType" class="location-select compact-item">
            <el-select v-model="form.warehouseType" placeholder="请选择仓库" clearable filterable
              @change="handleWarehouseChange" style="width: 100%" :loading="warehouseLoading" size="medium">
              <el-option v-for="item in warehouseTypes" :key="item.warehouseType" :label="item.warehouseTypeDesc"
@@ -53,7 +52,7 @@
          <!-- æ‰˜ç›˜æ¡ç è¾“å…¥ -->
          <div class="input-wrapper custom-input-group compact-input">
            <div class="input-label">料箱码</div>
            <div class="input-label">托盘条码</div>
            <el-input ref="trayInput" v-model="trayBarcode" placeholder="请扫描或输入料箱码后按回车键" clearable
              :disabled="!form.locationType || !form.warehouseType" @keyup.enter.native="handleTraySubmit"
              @clear="handleTrayClear" @input="handleTrayInput" class="custom-input" size="medium">
@@ -71,11 +70,11 @@
            <div class="input-label">物料条码</div>
            <el-input ref="barcodeInput" v-model="barcode" placeholder="请扫描或输入物料条码后按回车键" clearable
              :disabled="!form.locationType || !trayBarcode || !form.warehouseType"
              @keyup.enter.native="handleBarcodeSubmit" @clear="handleClear" @input="handleBarcodeInput"
              @keyup.enter.native="debounceHandleBarcodeSubmit" @clear="handleClear" @input="handleBarcodeInput"
              class="custom-input" size="medium">
              <template slot="append">
                <el-button :loading="loading" @click="handleBarcodeSubmit" type="primary" icon="el-icon-search"
                  :disabled="!form.locationType || !trayBarcode || !barcode || !from.warehouseType" size="medium">
                <el-button :loading="loading" @click="debounceHandleBarcodeSubmit" type="primary" icon="el-icon-search"
                  :disabled="!form.locationType || !trayBarcode || !barcode || !form.warehouseType" size="medium">
                  {{ loading ? '查询中...' : '查询' }}
                </el-button>
              </template>
@@ -85,7 +84,7 @@
          <div class="input-tips compact-tips">
            <p>提示:请先选择仓库 â†’ é€‰æ‹©ä»“库区域 â†’ è¾“入料箱码 â†’ è¾“入物料条码</p>
            <p v-if="!form.warehouseType" class="warning-text">⚠️ è¯·å…ˆé€‰æ‹©ä»“库</p>
            <p v-if="!form.locationType && !form.warehouseType" class="warning-text">⚠️ è¯·å…ˆé€‰æ‹©ä»“库区域</p>
            <p v-if="form.warehouseType && !form.locationType" class="warning-text">⚠️ è¯·å…ˆé€‰æ‹©ä»“库区域</p>
            <p v-if="form.warehouseType && form.locationType && !trayBarcode" class="warning-text">⚠️ è¯·å…ˆè¾“入料箱码</p>
          </div>
@@ -103,6 +102,32 @@
        <el-alert :title="error" type="error" show-icon closable @close="error = ''" />
      </div>
      <!-- æœªç»„盘列表 -->
      <div class="unpallet-section compact">
        <el-card shadow="hover" class="compact-card unpallet-card">
          <div slot="header" class="compact-header">
            <span><i class="el-icon-tickets"></i> æœªç»„盘条码</span>
            <span class="list-actions">
              <el-tag type="primary" size="small">未组盘 {{ totalStockCount }}</el-tag>
            </span>
          </div>
          <div class="table-container">
            <el-table :data="unpalletMaterials" stripe style="width: 100%" height="100%" size="small"
              v-loading="unpalletBarcodesLoading">
              <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
              <el-table-column prop="barcode" label="条码" min-width="140" show-overflow-tooltip></el-table-column>
              <el-table-column prop="materielCode" label="物料编码" min-width="150" show-overflow-tooltip></el-table-column>
              <el-table-column prop="batchNo" label="批次" min-width="150" show-overflow-tooltip></el-table-column>
              <el-table-column prop="orderQuantity" label="数量" min-width="130" align="right"></el-table-column>
              <el-table-column prop="unit" label="单位" width="80" align="center"></el-table-column>
              <el-table-column prop="supplyCode" label="供应商" min-width="130" show-overflow-tooltip></el-table-column>
            </el-table>
          </div>
        </el-card>
      </div>
      <!-- ç‰©æ–™åˆ—表 - å›ºå®šé«˜åº¦å¸¦æ»šåŠ¨æ¡ -->
      <div class="material-list compact">
        <el-card shadow="hover" class="compact-card">
@@ -110,7 +135,6 @@
            <span><i class="el-icon-tickets"></i> ç»„盘数据</span>
            <span class="list-actions">
              <el-tag type="primary" size="small">共 {{ materials.length }} æ¡</el-tag>
              <el-tag type="primary" size="small">未组盘 {{ totalStockCount }}</el-tag>
              <el-tag type="primary" size="small">未入库数量 {{ totalStockSum }}{{ uniqueUnit }}</el-tag>
              <el-tag v-if="trayBarcode" type="success" size="small">托盘: {{ trayBarcode }}</el-tag>
              <el-tag v-if="form.warehouseType" type="info" size="small">仓库: {{ currentWarehouseName }}</el-tag>
@@ -121,7 +145,7 @@
          <div v-if="materials.length === 0" class="empty-state compact">
            <i class="el-icon-document"></i>
            <p v-if="!form.warehouseType">请先选择仓库</p>
            <p v-if="!form.locationType">请先选择仓库区域</p>
            <p v-if="form.warehouseType && !form.locationType">请先选择仓库区域</p>
            <p v-else-if="!trayBarcode">请先输入料箱条码</p>
            <p v-else>暂无物料数据,请扫描或输入物料条码</p>
          </div>
@@ -141,34 +165,37 @@
        </el-card>
      </div>
    </div>
    <!--      <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确认</el-button>
    </div> -->
    <template #footer>
      <el-button type="danger" size="small" @click="handleDialogClose()">关闭</el-button>
    </template>
  </vol-box>
</template>
<script>
import http from '@/api/http.js';
import VolBox from '@/components/basic/VolBox.vue';
import VolForm from '@/components/basic/VolForm.vue';
import VolTable from '@/components/basic/VolTable.vue';
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus';
import { ref, onMounted, onUnmounted } from 'vue'
import InboundOrder from '../../../views/inbound/inboundOrder.vue';
import { th } from 'element-plus/es/locales.mjs';
// é˜²æŠ–函数
function debounce(func, wait) {
  let timeout;
  return function () {
    const context = this;
    const args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      func.apply(context, args);
    }, wait);
  };
}
export default {
  name: 'BarcodeScanner',
  components: { VolBox, VolForm, VolTable },
  props: {
    docNo: { type: String, required: true, default: '' },
    visible: { type: Boolean, required: true, default: false }
  },
  components: { VolBox },
  data() {
    return {
      show: false,
      orderNo: "",
      palletVisible: this.visible,
      trayBarcodeReg: /^[A-Z]\d{9}$/,
      trayBarcode: '',
      barcode: '',
      materials: [],
@@ -177,25 +204,27 @@
      debugMode: false,
      currentFocus: 'warehouse',
      // æ‰«ç æžªç›¸å…³å˜é‡
      unpalletBarcodes: [],
      unpalletBarcodesLoading: false,
      unpalletMaterials: [],
      scanCode: '',
      lastKeyTime: null,
      isManualInput: false,
      isScanning: false,
      scanTimer: null,
      manualInputTimer: null,
      scanTarget: 'tray', // å½“前扫码目标: tray æˆ– material
      scanTarget: 'tray',
      isSubmitting: false,
      palletGroupedBarcodes: {},
      // åº“存统计相关变量
      totalStockSum: 0,
      totalStockCount: 0,
      uniqueUnit: '',
      sumLoading: false,
      sumError: '',
      // ä»“库相关变量
      warehouseTypes: [],
      warehouseLoading: false,
      // ä»“库区域相关变量
      locationTypes: [],
      locationLoading: false,
      form: {
@@ -209,99 +238,143 @@
            trigger: 'change'
          }
        ],
        trayBarcode: [
          {
            pattern: this.trayBarcodeReg,
            message: '托盘号格式错误(需为1个大写字母+9个数字,如A000008024)',
            trigger: 'blur'
          }
        ],
        warehouseType: [
          {
            massage: '请选择仓库',
            message: '请选择仓库',
            trigger: 'change'
          }
        ]
      }
      },
      // æ–°å¢žï¼šé”®ç›˜äº‹ä»¶ç›‘听标记
      keyPressListenerAdded: false,
      isDialogClosing: false
    }
  },
  computed: {
    groupPalletVisible: {
      get() { return this.visible; },
      set(newVal) { this.$emit('update:visible', newVal); }
    },
    currentDocNo() { return this.docNo; },
    // å½“前选择的仓库名称
    currentWarehouseName() {
      const warehouse = this.warehouseTypes.find(item => item.warehouseType === this.form.warehouseType);
      return warehouse ? warehouse.warehouseTypeDesc : '';
    },
    // å½“前选择的仓库区域描述
    currentLocationDesc() {
      const location = this.locationTypes.find(item => item.locationType === this.form.locationType)
      return location ? location.locationTypeDesc : ''
    },
    debounceHandleBarcodeSubmit() {
      return debounce(this.handleBarcodeSubmit, 500);
    }
  },
  watch: {
    // ç›‘听show变量变化
    show(newVal) {
      if (newVal === true) {
        console.log('弹框打开,重置数据');
        this.isDialogClosing = false;
        this.resetData();
        this.$nextTick(() => {
          setTimeout(() => {
            this.fetchUnpalletMaterialDetails();
            this.addKeyPressListener(); // æ·»åŠ é”®ç›˜äº‹ä»¶ç›‘å¬
          }, 300);
        });
      } else if (newVal === false && !this.isDialogClosing) {
        console.log('弹框关闭,移除事件监听');
        this.isDialogClosing = true;
        this.removeKeyPressListener(); // ç§»é™¤é”®ç›˜äº‹ä»¶ç›‘听
        this.resetData();
      }
    },
    visible(newVal, oldVal) {
      this.palletVisible = newVal;
      // å½“从 false å˜ä¸º true æ—¶ï¼Œè¡¨ç¤ºå¼¹æ¡†æ‰“å¼€
      if (newVal === true && oldVal === false) {
        console.log('弹框打开,重置数据');
        this.resetData();
        this.$nextTick(() => {
          setTimeout(() => {
            // this.focusTrayInput();
            this.initwarehouseTypes(); // åˆå§‹åŒ–仓库
            this.initLocationTypes(); // åˆå§‹åŒ–仓库区域
            this.fetchStockStatistics(); // åŠ è½½ç»Ÿè®¡æ•°æ®
            this.fetchUnpalletMaterialDetails();
          }, 300);
        });
      }
      // å½“从 true å˜ä¸º false æ—¶ï¼Œè¡¨ç¤ºå¼¹æ¡†å…³é—­
      if (newVal === false && oldVal === true) {
        console.log('弹框关闭,重置数据');
        this.resetData();
      }
    },
    palletVisible(newVal) {
      this.$emit('update:visible', newVal);
    },
    docNo(newVal) {
      if (newVal) {
        this.palletForm = { palletCode: '', barcode: '' };
        this.backData = [];
        this.$refs.palletForm?.reset();
        this.fetchStockStatistics(); // å•据号变了,刷新统计
        this.fetchUnpalletMaterialDetails();
      }
    }
  },
  'form.warehouseType'(newVal) {
    if (newVal) {
      this.form.locationType = null;
    } else {
      this.locationTypes = [];
    }
  },
  mounted() {
    // æ·»åŠ å…¨å±€é”®ç›˜ç›‘å¬
    document.addEventListener('keypress', this.handleKeyPress);
    // ä½¿ç”¨setTimeout确保DOM完全渲染后再聚焦
    setTimeout(() => {
      // this.focusTrayInput();
      this.focusLocationSelect();
    }, 300);
    // ä¸åœ¨mounted时添加监听,在弹窗打开时添加
  },
  beforeDestroy() {
    // æ¸…理事件监听
    document.removeEventListener('keypress', this.handleKeyPress);
    // ç¡®ä¿ç»„件销毁时移除监听
    this.removeKeyPressListener();
    this.clearAllTimers();
  },
  methods: {
    /**
* è‡ªå®šä¹‰ä»“库区域验证
* å…è®¸å€¼ä¸º0,因为0是合法的locationType
*/
    // æ·»åŠ é”®ç›˜äº‹ä»¶ç›‘å¬
    addKeyPressListener() {
      if (!this.keyPressListenerAdded) {
        document.addEventListener('keypress', this.handleKeyPress);
        this.keyPressListenerAdded = true;
        console.log('键盘事件监听已添加');
      }
    },
    // ç§»é™¤é”®ç›˜äº‹ä»¶ç›‘听
    removeKeyPressListener() {
      if (this.keyPressListenerAdded) {
        document.removeEventListener('keypress', this.handleKeyPress);
        this.keyPressListenerAdded = false;
        console.log('键盘事件监听已移除');
      }
    },
    open() {
      this.show = true;
      this.orderNo = "";
      this.resetData();
      this.initLocationTypes();
      this.initwarehouseTypes();
      this.fetchUnpalletMaterialDetails();
      // å¼¹çª—打开时添加键盘事件监听
      this.$nextTick(() => {
        setTimeout(() => {
          this.addKeyPressListener();
        }, 100);
      });
    },
    validateLocationType(rule, value, callback) {
      // æ£€æŸ¥å€¼æ˜¯å¦ä¸ºnull、undefined或空字符串,但允许数字0
      if (!this.form.warehouseType) {
        callback(new Error('请先选择仓库'));
      } else if (value === null || value === undefined || value === '') {
@@ -310,156 +383,105 @@
        callback();
      }
    },
    /**
    * åˆå§‹åŒ–仓库区域数据
    */
    async initLocationTypes() {
    // èŽ·å–æœªç»„ç›˜ç‰©æ–™è¯¦æƒ…
    fetchUnpalletMaterialDetails() {
      this.unpalletBarcodesLoading = true;
      http.post('/api/InboundOrder/UnPalletGroupBarcode?orderNo=' + this.orderNo, {})
        .then(response => {
          if (response.status && Array.isArray(response.data)) {
            this.unpalletMaterials = response.data;
            this.unpalletBarcodes = response.data.map(item => item.barcode || '');
            this.totalStockCount = response.data.length;
          } else {
            this.unpalletMaterials = [];
          }
        })
        .catch(err => {
          console.error('获取未组盘物料失败:', err);
          this.unpalletMaterials = this.unpalletBarcodes.map(barcode => ({
            barcode: barcode,
            materielCode: '-',
            batchNo: '-',
            stockQuantity: '-',
            unit: '-',
            supplyCode: '-',
            warehouseType: '-'
          }));
        })
        .finally(() => {
          this.unpalletBarcodesLoading = false;
        });
    },
    // åˆå§‹åŒ–仓库区域类型
    initLocationTypes() {
      this.locationLoading = true;
      this.error = '';
      try {
        const response = await http.post('/api/LocationInfo/GetLocationTypes');
        if (response.status && Array.isArray(response.data)) {
          this.locationTypes = response.data;
          if (this.locationTypes.length === 0) {
            this.error = '未获取到仓库区域数据';
          } else {
            // å¦‚果有默认区域,可以在这里设置
            // this.form.locationType = this.locationTypes[0].locationType;
          }
        } else {
          this.error = '获取仓库区域数据失败';
        }
      } catch (error) {
        console.error('获取仓库区域失败:', error);
        this.error = `获取仓库区域失败: ${error.message || '网络错误'}`;
      } finally {
        this.locationLoading = false;
      }
      this.http.post("api/LocationInfo/GetLocationTypes")
        .then(({ data }) => {
          this.locationTypes = data;
        })
        .catch(e => {
          console.error('获取区域类型失败:', e);
          this.$message.error('获取区域类型失败');
        })
        .finally(() => {
          this.locationLoading = false;
        });
    },
    /**
     * åˆå§‹åŒ–仓库数据
     */
    async initwarehouseTypes() {
    // åˆå§‹åŒ–仓库类型
    initwarehouseTypes() {
      this.warehouseLoading = true;
      this.error = '';
      try {
        const response = await http.post('/api/Warehouse/GetwarehouseTypes');
        if (response.status && Array.isArray(response.data)) {
          this.warehouseTypes = response.data;
          if (this.warehouseTypes.length === 0) {
            this.error = '未获取到仓库数据';
          } else {
            // å¦‚果有默认区域,可以在这里设置
            // this.form.locationType = this.locationTypes[0].locationType;
          }
        } else {
          this.error = '获取仓库数据失败';
        }
      } catch (error) {
        console.error('获取仓库失败:', error);
        this.error = `获取仓库失败: ${error.message || '网络错误'}`;
      } finally {
        this.warehouseLoading = false;
      }
      this.http.post("api/Warehouse/GetwarehouseTypes")
        .then(({ data }) => {
          this.warehouseTypes = data;
        })
        .catch(e => {
          console.error('获取仓库类型失败:', e);
          this.$message.error('获取仓库类型失败');
        })
        .finally(() => {
          this.warehouseLoading = false;
        });
    },
    /**
    * ä»“库区域变更处理
    */
    handleLocationChange(value) {
      console.log('选择仓库区域:', value, '类型:', typeof value, this.currentLocationDesc);
      // ç«‹å³æ¸…除错误信息
      this.error = '';
      // æ‰‹åŠ¨è§¦å‘è¡¨å•éªŒè¯æ›´æ–°
      this.$nextTick(() => {
        if (this.$refs.locationForm) {
          // æ¸…除该字段的验证状态,然后重新验证
          this.$refs.locationForm.clearValidate('locationType');
          // çŸ­æš‚延迟后重新验证,确保DOM已更新
          setTimeout(() => {
            this.$refs.locationForm.validateField('locationType', (errorMsg) => {
              if (!errorMsg && (value === 0 || value)) {
                console.log('仓库区域验证通过:', value);
                // åŒºåŸŸé€‰æ‹©åŽï¼Œè‡ªåŠ¨èšç„¦åˆ°æ‰˜ç›˜è¾“å…¥æ¡†
                this.focusLocationSelect();
              }
            });
          }, 100);
        }
      });
    },
    /**
     * ä»“库变更处理
     */
    handleWarehouseChange(value) {
      console.log('选择仓库:', value, '类型:', typeof value, this.currentWarehouseName);
      // ç«‹å³æ¸…除错误信息
      this.error = '';
      // æ‰‹åŠ¨è§¦å‘è¡¨å•éªŒè¯æ›´æ–°
      this.$nextTick(() => {
        if (this.$refs.locationForm) {
          // æ¸…除该字段的验证状态,然后重新验证
          this.$refs.locationForm.clearValidate('warehouseType');
          // çŸ­æš‚延迟后重新验证,确保DOM已更新
          setTimeout(() => {
            this.$refs.locationForm.validateField('warehouseType', (errorMsg) => {
              if (!errorMsg && (value === 0 || value)) {
                console.log('仓库验证通过:', value);
                this.focusLocationSelect();
              }
            });
          }, 100);
        }
      });
    },
    async fetchStockStatistics() {
      // å•据号为空时不查询
      if (!this.docNo) {
    // èŽ·å–åº“å­˜ç»Ÿè®¡
    fetchStockStatistics(orderNo) {
      if (!orderNo) {
        this.sumError = '单据号为空,无法统计';
        return;
        return Promise.resolve(null);
      }
      this.sumLoading = true;
      this.sumError = '';
      try {
        // è°ƒç”¨åŽç«¯ç»Ÿè®¡æŽ¥å£ï¼ˆæ›¿æ¢ä¸ºä½ çš„实际接口路径)
        const response = await http.post('/api/InboundOrder/UnPalletQuantity?orderNo=' + this.docNo, {
      return http.post('/api/InboundOrder/UnPalletQuantity?orderNo=' + orderNo, {})
        .then(response => {
          if (response.data) {
            this.totalStockSum = response.data.stockSumQuantity || 0;
            this.totalStockCount = response.data.stockCount || 0;
            this.uniqueUnit = response.data.uniqueUnit || '';
          }
          return response.data;
        })
        .catch(err => {
          console.error('统计加载失败:', err);
          this.sumError = '统计加载失败';
          this.totalStockSum = 0;
          this.totalStockCount = 0;
          throw err;
        })
        .finally(() => {
          this.sumLoading = false;
        });
        // ç»‘定数据(匹配 PalletSumQuantityDTO ç»“构)
        if (response.data) {
          this.totalStockSum = response.data.stockSumQuantity || 0; // æ€»åº“存数量
          this.totalStockCount = response.data.stockCount || 0;     // æ€»åº“存记录数
          this.uniqueUnit = response.data.uniqueUnit || '';               // è®¡é‡å•位
        }
      } catch (err) {
        this.sumError = '统计加载失败';
        this.totalStockSum = 0;
        this.totalStockCount = 0;
        console.error('库存统计查询异常:', err);
      } finally {
        this.sumLoading = false;
      }
    },
    /**
     * è¡¨å•验证
     */
    async validateForm() {
    // è¡¨å•验证
    validateForm() {
      return new Promise((resolve) => {
        if (!this.$refs.locationForm) {
          this.error = '表单未初始化';
@@ -473,15 +495,11 @@
            this.error = '';
            resolve(true);
          } else {
            // æ‰‹åŠ¨æ£€æŸ¥locationType,正确处理值为0的情况
            if (!this.from.warehouseType) {
            if (!this.form.warehouseType) {
              this.error = '请先选择仓库';
            }
            else if (this.form.locationType === null || this.form.locationType === undefined || this.form.locationType === '') {
            } else if (!this.form.locationType) {
              this.error = '请先选择仓库区域';
              //this.$message.warning('请先选择仓库区域');
            } else {
              // å¦‚果值存在(包括0),但验证不通过,可能是其他验证错误
              this.error = '请检查表单填写是否正确';
            }
            resolve(false);
@@ -489,26 +507,7 @@
        });
      });
    },
    focusWarehouseSelect() {
      if (this.$refs.locationForm) {
        const selectEl = this.$el.querySelector('.location-select:first-child .el-input__inner');
        if (selectEl) {
          selectEl.focus();
          this.currentFocus = 'warehouse';
        }
      }
    },
    // èšç„¦åˆ°ä»“库区域选择
    focusLocationSelect() {
      if (this.$refs.locationForm) {
        const selectEl = this.$el.querySelector('.location-select:nth-child(2) .el-input__inner');
        if (selectEl) {
          selectEl.focus();
          this.currentFocus = 'location';
        }
      }
    },
    // èšç„¦åˆ°æ‰˜ç›˜è¾“入框
    focusTrayInput() {
      if (this.$refs.trayInput && this.$refs.trayInput.$el) {
        const inputEl = this.$refs.trayInput.$el.querySelector('input');
@@ -516,11 +515,11 @@
          inputEl.focus();
          this.currentFocus = 'tray';
          this.scanTarget = 'tray';
          inputEl.select();
        }
      }
    },
    // èšç„¦åˆ°ç‰©æ–™è¾“入框
    focusBarcodeInput() {
      if (this.$refs.barcodeInput && this.$refs.barcodeInput.$el) {
        const inputEl = this.$refs.barcodeInput.$el.querySelector('input');
@@ -528,24 +527,19 @@
          inputEl.focus();
          this.currentFocus = 'material';
          this.scanTarget = 'material';
            inputEl.select();
            console.log('物料输入框内容已选中');
          inputEl.select();
        }
      }
    },
    
    // é‡ç½®æ‰€æœ‰æ•°æ®
    resetData() {
      console.log('重置弹框数据');
      this.palletGroupedBarcodes = {};
      this.isSubmitting = false;
      this.trayBarcode = '';
      this.barcode = '';
      this.materials = [];
      this.unpalletBarcodes = [];
      this.unpalletMaterials = [];
      this.loading = false;
      this.error = '';
      this.scanCode = '';
@@ -562,10 +556,10 @@
      this.form = {
        warehouseType: null,
        locationType: null
      }
      };
      this.warehouseTypes = [];
      this.locationTypes = [];
      // æ¸…除表单验证状态
      this.$nextTick(() => {
        if (this.$refs.locationForm) {
          this.$refs.locationForm.clearValidate();
@@ -573,7 +567,6 @@
      });
    },
    // æ¸…除所有计时器
    clearAllTimers() {
      if (this.manualInputTimer) {
        clearTimeout(this.manualInputTimer);
@@ -584,138 +577,110 @@
        this.scanTimer = null;
      }
    },
    // å¼¹æ¡†æ‰“开时重置数据
    handleDialogOpen() {
      console.log('弹框打开,重置数据');
      this.resetData();
      // ä½¿ç”¨setTimeout确保DOM完全渲染后再聚焦
      this.$nextTick(() => {
        setTimeout(() => {
          this.initwarehouseTypes();
          this.initLocationTypes(); // åˆå§‹åŒ–仓库区域
          // ç¡®ä¿è¡¨å•引用存在后再聚焦
          if (this.$refs.locationForm) {
            this.focusWarehouseSelect();
          } else {
            // å¦‚果表单引用还不存在,稍后重试
            setTimeout(() => {
              this.focusWarehouseSelect();
            }, 500);
          }
        }, 300);
      });
    },
    // å¼¹æ¡†å…³é—­æ—¶é‡ç½®æ•°æ®
    handleDialogClose() {
      console.log('弹框关闭,重置数据');
      // å…ˆç§»é™¤é”®ç›˜äº‹ä»¶ç›‘听
      this.removeKeyPressListener();
      this.show = false;
      this.resetData();
    },
    // å–消按钮
    handleCancel() {
      this.palletVisible = false;
    },
    // ç¡®è®¤æŒ‰é’®
    async handleConfirm() {
      if (!await this.validateForm()) return;
    handleConfirm() {
      this.validateForm()
        .then(valid => {
          if (!valid) return;
          if (this.materials.length === 0) {
            this.$message.warning('请至少添加一个物料');
            return;
          }
      if (this.materials.length === 0) {
        this.$message.warning('请至少添加一个物料');
        return;
      }
          if (!this.trayBarcode) {
            this.$message.warning('请输入托盘条码');
            return;
          }
      if (!this.trayBarcode) {
        this.$message.warning('请输入托盘条码');
        return;
      }
          const result = {
            warehouseType: this.form.warehouseType,
            warehouseName: this.currentWarehouseName,
            locationType: this.form.locationType,
            locationDesc: this.currentLocationDesc,
            trayBarcode: this.trayBarcode,
            materials: this.materials,
            docNo: this.docNo
          };
      const result = {
        warehouseType: this.form.warehouseType,
        warehouseName: this.currentWarehouseName,
        locationType: this.form.locationType,
        locationDesc: this.currentLocationDesc,
        trayBarcode: this.trayBarcode,
        materials: this.materials,
        docNo: this.docNo
      };
      // è§¦å‘父组件的 back-success äº‹ä»¶
      this.$emit('back-success', result);
      this.palletVisible = false;
          this.$emit('back-success', result);
          this.palletVisible = false;
        });
    },
    // å¤„理托盘输入
    handleTrayInput() {
      // æ ‡è®°ä¸ºæ‰‹åŠ¨è¾“å…¥æ¨¡å¼
      this.isManualInput = true;
      this.isScanning = false;
      // æ¸…除之前的计时器
      if (this.manualInputTimer) {
        clearTimeout(this.manualInputTimer);
      }
      // è®¾ç½®è®¡æ—¶å™¨ï¼Œå¦‚果一段时间内没有输入,则重置为扫码模式
      this.manualInputTimer = setTimeout(() => {
        this.isManualInput = false;
      }, 1000);
    },
    // å¤„理物料输入
    handleBarcodeInput() {
      // æ ‡è®°ä¸ºæ‰‹åŠ¨è¾“å…¥æ¨¡å¼
      this.isManualInput = true;
      this.isScanning = false;
      // æ¸…除之前的计时器
      if (this.manualInputTimer) {
        clearTimeout(this.manualInputTimer);
      }
      // è®¾ç½®è®¡æ—¶å™¨ï¼Œå¦‚果一段时间内没有输入,则重置为扫码模式
      this.manualInputTimer = setTimeout(() => {
        this.isManualInput = false;
      }, 1000);
    },
    // å¤„理托盘条码提交
    async handleTraySubmit() {
      // å…ˆç›´æŽ¥æ£€æŸ¥locationType,避免表单验证的异步问题
    handleTraySubmit() {
      this.barcode = '';
      this.materials = [];
      this.error = '';
      if (!this.form.warehouseType) {
        this.error = '请先选择仓库';
        return;
      }
      if (!this.form.locationType) {
        this.error = '请先选择仓库区域';
        //this.$message.warning('请先选择仓库区域');
        return;
      }
      // ç„¶åŽå†è¿›è¡Œå®Œæ•´çš„表单验证
      if (!await this.validateForm()) return;
      this.validateForm()
        .then(valid => {
          if (!valid) return;
          const currentTrayBarcode = this.trayBarcode.trim();
      const currentTrayBarcode = this.trayBarcode.trim();
          if (!currentTrayBarcode) {
            this.error = '请输入或扫描托盘条码';
            return;
          }
      if (!currentTrayBarcode) {
        this.error = '请输入或扫描托盘条码';
        return;
      }
          this.error = '';
      this.error = '';
          if (!this.trayBarcodeReg.test(currentTrayBarcode)) {
            this.$message("托盘号格式错误");
            this.focusTrayInput();
            return;
          }
      // è®¾ç½®æ‰˜ç›˜æ¡ç åŽï¼Œè‡ªåŠ¨èšç„¦åˆ°ç‰©æ–™è¾“å…¥æ¡†
      this.focusBarcodeInput();
      this.$message({
        message: `托盘条码已设置: ${currentTrayBarcode}`,
        type: 'success',
        duration: 2000
      });
          this.focusBarcodeInput();
          this.$message.success(`托盘条码已设置: ${currentTrayBarcode}`);
        });
    },
    // æ¸…除托盘
    clearTray() {
      this.trayBarcode = '';
      this.materials = [];
@@ -727,65 +692,79 @@
      });
    },
    // æ¸…空托盘输入
    handleTrayClear() {
      this.error = '';
    },
    // æ¸…空输入
    handleClear() {
      this.error = '';
      this.scanCode = '';
      this.isManualInput = false;
      this.isScanning = false;
    },
    // å¤„理物料条码提交
    async handleBarcodeSubmit() {
      if (!await this.validateForm()) return;
    handleBarcodeSubmit() {
      if (this.isSubmitting) {
        this.$message.warning('正在处理中,请稍候');
        return;
      }
      const currentBarcode = this.barcode.trim();
      if (!this.trayBarcode) {
        this.error = '请先输入托盘条码';
        this.focusTrayInput();
      const currentTrayGrouped = this.palletGroupedBarcodes[this.trayBarcode] || [];
      if (currentTrayGrouped.includes(currentBarcode)) {
        this.error = `条码 ${currentBarcode} å·²è¢«å½“前托盘组盘,请勿重复操作`;
        this.barcode = '';
        this.focusBarcodeInput();
        return;
      }
      if (!currentBarcode) {
        this.error = '请输入或扫描物料条码';
        return;
      }
      this.focusBarcodeInput();
      this.error = '';
      this.loading = true;
      try {
        // è°ƒç”¨API查询物料信息
        const materialData = await this.fetchMaterialData(currentBarcode);
        if (!materialData || materialData.length === 0) {
          return;
        }
        // æ£€æŸ¥æ˜¯å¦å·²å­˜åœ¨ç›¸åŒç‰©æ–™ç¼–码的记录
        const exists = this.materials.some(item =>
          item.barcode === this.trayBarcode
        );
        console.log('API:', materialData)
        if (exists) {
          this.$message({
            message: '该条码已存在当前托盘的列表中',
            type: 'warning',
            duration: 2000
          });
      this.isSubmitting = true;
      this.validateForm()
        .then(valid => {
          if (!valid) {
            this.isSubmitting = false;
            return;
          }
          
        } else {
          if (!this.trayBarcode) {
            this.error = '请先输入托盘条码';
            this.focusTrayInput();
            this.isSubmitting = false;
            return;
          }
          if (!currentBarcode) {
            this.error = '请输入或扫描物料条码';
            this.isSubmitting = false;
            return;
          }
          this.focusBarcodeInput();
          this.error = '';
          this.loading = true;
          console.log('组盘请求参数:', {
            palletCode: this.trayBarcode,
            barcode: currentBarcode,
            locationTypeDesc: this.currentLocationDesc,
            locationType: this.form.locationType,
            warehouseType: this.form.warehouseType
          });
          return this.fetchMaterialData(currentBarcode);
        })
        .then(materialData => {
          if (!materialData || materialData.length === 0) {
            return;
          }
          this.materials = [];
          const newBarcodes = [];
          materialData.forEach(item => {
            // å¦‚果不存在,添加新物料
            this.materials.push({
              ...item,
              trayCode: this.trayBarcode,
@@ -793,98 +772,107 @@
              locationDesc: this.currentLocationDesc,
              scanTime: this.formatTime(new Date())
            });
          });
          this.$message({
            message: `成功添加条码: ${currentBarcode}`,
            type: 'success',
            duration: 2000
            newBarcodes.push(item.barcode);
          });
          this.fetchStockStatistics();
          // æ¸…空物料输入框并保持聚焦
          if (!this.palletGroupedBarcodes[this.trayBarcode]) {
            this.palletGroupedBarcodes[this.trayBarcode] = [];
          }
          this.palletGroupedBarcodes[this.trayBarcode] = [...new Set([...this.palletGroupedBarcodes[this.trayBarcode], ...newBarcodes])];
          this.orderNo = materialData[0].orderNo;
          return Promise.all([
            this.fetchStockStatistics(materialData[0].orderNo),
            this.fetchUnpalletMaterialDetails()
          ]);
        })
        .then(() => {
          this.barcode = '';
          this.scanCode = ''; // æ¸…空扫码缓存
          this.scanCode = '';
          this.isScanning = false;
          setTimeout(() => {
            this.focusBarcodeInput();
          }, 100);
        }
      } catch (err) {
        this.error = err.message || '查询条码信息失败,请重试';
        this.focusBarcodeInput();
        setTimeout(() => {
      // é€‰ä¸­è¾“入框内的错误内容(确保focus完成后执行)
      const inputEl = this.$refs.barcodeInput?.$el?.querySelector('input');
      if (inputEl) inputEl.select();
    }, 100);
      } finally {
        this.loading = false;
      }
        })
        .catch(err => {
          console.error('处理物料条码失败:', err);
          this.error = err.message || '查询条码信息失败,请重试';
          this.focusBarcodeInput();
          setTimeout(() => {
            const inputEl = this.$refs.barcodeInput?.$el?.querySelector('input');
            if (inputEl) inputEl.select();
          }, 100);
        })
        .finally(() => {
          this.loading = false;
          this.isSubmitting = false;
        });
    },
    // API请求 - æ›¿æ¢ä¸ºå®žé™…çš„API调用
    async fetchMaterialData(barcode) {
      try {
        const response = await http.post('/api/InboundOrder/BarcodeMaterielGroup',
          {
            palletCode: this.trayBarcode,
            orderNo: this.docNo,
            barcodes: barcode,
            locationTypeDesc: this.currentLocationDesc,
            locationType: this.form.locationType, // æ·»åŠ ä»“åº“åŒºåŸŸä¿¡æ¯
            warehouseType: this.form.warehouseType
    // API请求
    fetchMaterialData(barcode) {
      return http.post('/api/Inbound/GroupPallet', {
        palletCode: this.trayBarcode,
        barcode: barcode,
        locationTypeDesc: this.currentLocationDesc,
        locationType: this.form.locationType,
        warehouseType: this.form.warehouseType
      })
        .then(response => {
          let materialData;
          if (typeof response.data === 'string') {
            try {
              materialData = JSON.parse(response.data);
            } catch (e) {
              console.error('解析响应数据失败:', e);
            }
          } else {
            materialData = response.data;
          }
        );
        let materialData;
        if (typeof response.data === 'string') {
          try {
            materialData = JSON.parse(response.data);
          } catch (e) {
          if (!response.status) {
            this.error = response.message || '查询条码信息失败,请重试';
            return [];
          }
        } else {
          // å¦‚果返回的是JSON对象,直接使用
          materialData = response.data;
        }
        if (!response.status) {
          this.error = response.message || '查询条码信息失败,请重试';
        }
        return materialData;
      } catch (error) {
        console.error('API调用失败:', error);
      }
          return materialData || [];
        })
        .catch(error => {
          console.error('API调用失败:', error);
          this.$message.error('接口请求失败,请联系管理员');
          throw error;
        });
    },
    // å¤„理扫码枪输入
    handleKeyPress(event) {
      // å¦‚果是手动输入模式,不处理扫码枪逻辑
      if (this.isManualInput) {
      // æ£€æŸ¥å¼¹çª—是否显示
      if (!this.show || this.isDialogClosing) {
        return;
      }
      if (this.isManualInput || this.isSubmitting) {
        return;
      }
      const key = event.key;
      const currentTime = new Date().getTime();
      // å¿½ç•¥ç›´æŽ¥æŒ‰ä¸‹çš„回车键(由handleBarcodeSubmit处理)
      if (key === 'Enter') {
        event.preventDefault();
        if (this.scanCode.length > 0) {
          // é˜»æ­¢é»˜è®¤å›žè½¦è¡Œä¸ºï¼Œé¿å…è¡¨å•提交
          event.preventDefault();
          if (this.scanTarget === 'material' && !this.trayBarcode) {
            this.$message.warning('请先设置托盘条码');
            this.scanCode = '';
            this.lastKeyTime = null;
            return;
          }
          // æ‰«ç å®Œæˆï¼Œè‡ªåŠ¨è§¦å‘æŸ¥è¯¢
          this.isScanning = false;
          // æ ¹æ®å½“前扫码目标设置相应的输入框值
          if (this.scanTarget === 'tray') {
            this.trayBarcode = this.scanCode;
            this.handleTraySubmit();
@@ -898,7 +886,6 @@
        return;
      }
      // æž„建扫码内容(快速连续输入视为扫码)
      if (this.lastKeyTime && currentTime - this.lastKeyTime < 50) {
        this.scanCode += key;
        this.isScanning = true;
@@ -907,7 +894,6 @@
        this.isScanning = true;
      }
      // è®¾ç½®è®¡æ—¶å™¨ï¼Œå¦‚果一段时间内没有输入,则重置扫描状态
      if (this.scanTimer) {
        clearTimeout(this.scanTimer);
      }
@@ -916,44 +902,6 @@
      }, 100);
      this.lastKeyTime = currentTime;
    },
    // åˆ é™¤ç‰©æ–™
    removeMaterial(index) {
      this.$confirm('确定要删除这条物料记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.materials.splice(index, 1);
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.fetchStockStatistics();
      }).catch(() => {
        // å–消删除
      });
    },
    // æ¸…空所有物料
    clearAllMaterials() {
      if (this.materials.length === 0) return;
      this.$confirm('确定要清空所有物料记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.materials = [];
        this.$message({
          type: 'success',
          message: '已清空所有记录!'
        });
      }).catch(() => {
        // å–消清空
      });
    },
    // æ ¼å¼åŒ–æ—¶é—´
@@ -966,6 +914,23 @@
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // ä»“库切换事件
    handleWarehouseChange() {
      this.form.locationType = null;
      this.trayBarcode = '';
      this.barcode = '';
      this.materials = [];
      this.error = '';
    },
    // åŒºåŸŸåˆ‡æ¢äº‹ä»¶
    handleLocationChange() {
      this.trayBarcode = '';
      this.barcode = '';
      this.materials = [];
      this.error = '';
    }
  }
}
@@ -1278,5 +1243,37 @@
    border: 1px solid #DCDFE6;
    border-radius: 4px;
  }
  .unpallet-section.compact {
    margin-bottom: 8px;
    flex-shrink: 0;
  }
  .unpallet-card {
    flex-shrink: 0;
  }
  .unpallet-barcode-list {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    padding: 8px 0;
    max-height: 180px;
    overflow-y: auto;
  }
  .unpallet-barcode-list>>>.el-tag {
    cursor: pointer;
    max-width: calc(33.333% - 4px);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  @media (max-width: 768px) {
    .unpallet-barcode-list>>>.el-tag {
      max-width: calc(50% - 4px);
    }
  }
}
</style>