<template>
    <el-dialog v-model="visible" title="开始盘点" width="800px" @open="onOpen" @opened="onOpened" @close="onClose">
      <div>
        <div class="form-row"><!-- @keyup.enter="handleAddToBatch，回车添加"@keydown.enter.prevent="handleDeviceEnter" -->
          <textarea
            ref="deviceCodeInputRef"
            v-model="device_code"
            class="device-code-input"
            placeholder="设备编号（支持扫码枪/RFID批量录入）"
            :disabled="loading"
            autocomplete="off"
            rows="3"
            @input="handleDeviceInput"
            @keydown="handleRFIDKeydown"
            @blur="handleDeviceBlur"
            @keydown.enter.prevent="handleDeviceEnter"
          ></textarea>
          <el-input v-model="check_no" placeholder="盘点编号" @keyup.enter="handleAddToBatch" :disabled="true" />
          <el-button type="success" @click="handleAddToBatch" :disabled="loading">添加到待提交列表</el-button>
          <el-button type="info" :icon="Setting" @click="showReadRuleDialog = true" :disabled="loading">读取规则</el-button>
        </div>
       <!--  <div class="input-hint">
          <span>提示：系统会自动识别扫码和RFID输入</span>
          <span class="input-status" :style="{ color: inputStatusColor }">{{ inputStatus }}</span>
        </div> -->
        <!-- <div class="action-buttons">
          <el-button class="action-button" type="primary" plain @click="handleManualAdd" :disabled="loading">手动添加</el-button>
          <el-button class="action-button" plain @click="handleClearRecords" :disabled="loading || records.length === 0">清除记录</el-button>
          <el-button class="action-button" plain @click="handleExportRecords" :disabled="loading || records.length === 0">导出数据</el-button>
        </div> -->

        <!-- 待提交设备编号列表 -->
        <div v-if="pendingDeviceCodes.length > 0" class="pending-list" style="margin-top: 15px; margin-bottom: 15px;">
          <div class="pending-header">
            <div class="pending-title">待提交设备编号 ({{ pendingDeviceCodes.length }}个)：</div>
            <div class="pending-actions">
              <el-button type="primary" @click="handleBatchSubmit" :loading="loading" size="small">批量提交({{ pendingDeviceCodes.length }})</el-button>
              <el-button type="text" size="small" @click="clearPendingCodes">清空</el-button>
            </div>
          </div>
          <div class="pending-tags">
            <el-tag 
              v-for="(code, index) in pendingDeviceCodes" 
              :key="index" 
              closable 
              @close="removePendingCode(index)"
              style="margin-right: 8px; margin-bottom: 8px;"
            >
              {{ code }}
            </el-tag>
          </div>
        </div>

       <!--  <div class="results-section">
          <div class="section-title">
            <span>录入结果</span>
            <span class="section-count">共 {{ records.length }} 条</span>
          </div>
          <div v-if="records.length === 0" class="empty-state">
            <i>📋</i>
            <p>暂无录入数据</p>
            <p>请使用扫码枪或RFID设备进行录入</p>
          </div>
          <div v-else class="results-container">
            <div class="result-item" v-for="(item, idx) in records" :key="idx">
              <div class="result-content">
                <div class="result-code">{{ item.code }}</div>
                <div class="result-time">{{ item.time }}</div>
              </div>
              <div class="result-type">{{ item.type }}</div>
            </div>
          </div>
        </div> -->
    
        <el-table :data="deviceList"  v-loading="loading" style="margin-top: 20px">
          <el-table-column type="index" label="序号" width="60" />
          <!-- <el-table-column prop="id" label="盘点id" width="60" /> -->
          <el-table-column prop="device_code" label="设备编号" />
          <el-table-column prop="device_name" label="设备名称" />
          <el-table-column prop="device_category" label="设备分类" />
          <el-table-column prop="check_no" label="盘点编号" />
          <el-table-column prop="scanned_quantity" label="盘点数量" />
          <el-table-column prop="status_display" label="状态" />
          <!-- <el-table-column prop="productName" label="商品名称" /> -->
        </el-table>
      </div>
      <template #footer v-if="deviceList.length > 0">
        <div class="dialog-footer">
          <el-button @click="onCancelAll" :disabled="!currentRecordId">取消盘点</el-button>
          <el-button type="primary" @click="onCompleteAll" :disabled="!check_no">完成盘点</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 读取规则设置对话框 -->
    <el-dialog 
      v-model="showReadRuleDialog" 
      title="设置读取规则" 
      width="600px" 
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form :model="readRuleConfig" label-width="140px">
        <el-form-item label="RFID标签长度">
          <el-input-number v-model="readRuleConfig.rfidLength" :min="1" :max="100" style="width: 100%" />
          <div class="form-tip">RFID标签的固定长度（字符数）</div>
        </el-form-item>
        <el-form-item label="RFID标签前缀">
          <el-input v-model="readRuleConfig.rfidPrefix" placeholder="例如：E280" style="width: 100%" />
          <div class="form-tip">RFID标签的前缀（可选，留空则不限制前缀）</div>
        </el-form-item>
        <el-form-item label="分隔符">
          <el-select 
            v-model="readRuleConfig.separator" 
            placeholder="选择分隔符" 
            style="width: 100%"
            popper-class="separator-select-popper"
            teleported
          >
            <el-option label="空格" value=" " />
            <el-option label="逗号" value="," />
            <el-option label="分号" value=";" />
            <el-option label="制表符" value="\t" />
            <el-option label="回车换行" value="\n" />
            <el-option label="自定义" value="custom" />
          </el-select>
          <el-input 
            v-if="readRuleConfig.separator === 'custom'" 
            v-model="readRuleConfig.customSeparator" 
            placeholder="请输入自定义分隔符" 
            style="width: 100%; margin-top: 10px;" 
          />
          <div class="form-tip">用于分割多个设备编号的分隔符</div>
        </el-form-item>
        <el-form-item label="自动分割粘连">
          <el-switch v-model="readRuleConfig.autoSplitSticky" />
          <div class="form-tip">是否自动分割粘连在一起的RFID标签</div>
        </el-form-item>
        <el-form-item label="允许重复添加">
          <el-switch v-model="readRuleConfig.allowDuplicate" />
          <div class="form-tip">是否允许添加重复的设备编号</div>
        </el-form-item>
        <el-form-item label="启用高速缓冲">
          <el-switch v-model="readRuleConfig.enableRFIDBuffer" />
          <div class="form-tip">开启后使用缓冲区整包处理RFID高速输入</div>
        </el-form-item>
        <el-form-item label="缓冲判定时间(ms)">
          <el-input-number
            v-model="readRuleConfig.rfidInputTimeout"
            :min="30"
            :max="1000"
            :step="10"
            style="width: 100%"
          />
          <div class="form-tip">超出该间隔判定一次扫码完成</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetReadRule">重置默认</el-button>
        <el-button type="primary" @click="saveReadRule">保存</el-button>
      </template>
    </el-dialog>
  </template>
  
  <script setup lang="ts" >
  import { ref, nextTick, onBeforeUnmount } from 'vue';
  import * as api from '../api';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Setting } from '@element-plus/icons-vue';
  const emit = defineEmits(['completed']);

  type ScanRecord = {
    code: string;
    type: string;
    time: string;
  };

  const visible = ref(false);
  const device_code = ref('');
  const check_no = ref('');
  const deviceList = ref<any[]>([]);
  const currentRecordId = ref<number | null>(null);
  const loading = ref(false);
  const deviceCodeInputRef = ref<HTMLTextAreaElement | null>(null);
  // 待提交的设备编号数组
  const pendingDeviceCodes = ref<string[]>([]);
  // 标记是否是正常完成/取消盘点关闭（避免重复调用取消接口）
  const isNormalClose = ref(false);
  // 读取规则设置对话框显示状态
  const showReadRuleDialog = ref(false);
  // 读取规则配置
  const readRuleConfig = ref({
    rfidLength: 24, // RFID标签长度
    rfidPrefix: 'E280', // RFID标签前缀
    separator: ' ', // 分隔符
    customSeparator: '', // 自定义分隔符
    autoSplitSticky: true, // 自动分割粘连
    allowDuplicate: true, // 允许重复添加
  enableRFIDBuffer: true, // 是否启用RFID缓冲
  rfidInputTimeout: 120, // RFID缓冲判定时间
  });
//   const btflag=ref(true);

  const inputStatus = ref('等待输入...');
  const inputStatusColor = ref('');
  const records = ref<ScanRecord[]>([]);
  const MAX_RECORDS = 500;
  let statusResetTimer: ReturnType<typeof setTimeout> | null = null;
const rfidInputBuffer = ref('');
let rfidInputTimer: ReturnType<typeof setTimeout> | null = null;
  
  const setCheckNo = async (checkNo: string, id?: number | null) => {
    console.log("checkNo::::::", checkNo, "id::::::", id)
    check_no.value = checkNo;
    
    // 如果传递了 id，直接使用
    if (id !== undefined && id !== null) {
      currentRecordId.value = id;
    } else {
      // 如果没有传递 id，通过 check_no 查询记录获取 id
      try {
        const reslist = await api.GetPermission();
        if (reslist?.code === 2000) {
          const record = findCheckRecord(checkNo, reslist.data);
          currentRecordId.value = record?.id ?? null;
          console.log("通过 check_no 查询到的 id::", currentRecordId.value);
        }
      } catch (error) {
        console.error('查询盘点记录失败:', error);
        currentRecordId.value = null;
      }
    }
};
  
  // 聚焦设备编号输入框
  const focusDeviceCodeInput = async () => {
    // 如果"设置读取规则"对话框打开，不自动聚焦，避免影响对话框内的输入框
    if (showReadRuleDialog.value) {
      return;
    }
    await nextTick();
    setTimeout(() => {
      const inputEl = deviceCodeInputRef.value;
      if (!inputEl || loading.value) return;
      inputEl.focus();
      setTimeout(() => {
        inputEl?.select();
      }, 10);
    }, 100);
  };

const clearRFIDInputTimer = () => {
  if (rfidInputTimer) {
    clearTimeout(rfidInputTimer);
    rfidInputTimer = null;
  }
};

const commitRFIDBufferToTextarea = () => {
  if (!readRuleConfig.value.enableRFIDBuffer) return;
  if (!rfidInputBuffer.value) return;
  device_code.value = rfidInputBuffer.value;
  rfidInputBuffer.value = '';
  clearRFIDInputTimer();
};

const submitRFIDBuffer = () => {
  if (!readRuleConfig.value.enableRFIDBuffer) return;
  if (!rfidInputBuffer.value) return;
  const bufferedValue = rfidInputBuffer.value;
  rfidInputBuffer.value = '';
  clearRFIDInputTimer();
  device_code.value = bufferedValue;
  handleAddToBatch(true);
};

const scheduleRFIDBufferSubmit = () => {
  if (!readRuleConfig.value.enableRFIDBuffer) return;
  clearRFIDInputTimer();
  const delay = Math.max(readRuleConfig.value.rfidInputTimeout || 120, 30);
  rfidInputTimer = setTimeout(() => {
    /* submitRFIDBuffer(); */
  }, delay);
};

  const setInputStatus = (text: string, color = '', resetDelay = 0) => {
    inputStatus.value = text;
    inputStatusColor.value = color;
    if (statusResetTimer) {
      clearTimeout(statusResetTimer);
    }
    if (resetDelay > 0) {
      statusResetTimer = setTimeout(() => {
        inputStatus.value = '等待输入...';
        inputStatusColor.value = '';
        statusResetTimer = null;
      }, resetDelay);
    }
  };

  const handleDeviceInput = () => {
    setInputStatus('输入中...', '#4b6cb7');
  };

const handleRFIDKeydown = (event: KeyboardEvent) => {
  if (!readRuleConfig.value.enableRFIDBuffer) return;
  if (event.ctrlKey || event.metaKey || event.altKey) return;
  if (event.key === 'Enter') {
    event.preventDefault();
    submitRFIDBuffer();
    return;
  }
  if (event.key === 'Backspace') {
    event.preventDefault();
    rfidInputBuffer.value = rfidInputBuffer.value.slice(0, -1);
    device_code.value = rfidInputBuffer.value;
    return;
  }
  if (event.key.length === 1) {
    event.preventDefault();
    rfidInputBuffer.value += event.key;
    device_code.value = rfidInputBuffer.value;
    scheduleRFIDBufferSubmit();
  }
};

  const handleDeviceBlur = () => {
    // 如果"设置读取规则"对话框打开，不自动聚焦，避免影响对话框内的输入框
    if (showReadRuleDialog.value) {
      return;
    }
    setTimeout(() => {
      focusDeviceCodeInput();
    }, 10);
  };

  const handleDeviceEnter = (event: KeyboardEvent) => {
  if (event.shiftKey) return;
  if (readRuleConfig.value.enableRFIDBuffer) {
    event.preventDefault();
    submitRFIDBuffer();
    return;
  }
  event.preventDefault();
  handleAddToBatch();
  };

  const detectInputType = (code: string) => {
    const numeric = /^\d+$/.test(code);
    const minLength = Math.max(readRuleConfig.value.rfidLength, 8);
    if (numeric && code.length >= minLength) {
      return 'RFID';
    }
    return '二维码';
  };

  const appendRecords = (codes: string[]) => {
    const now = new Date().toLocaleString();
    const newRecords = codes.map((code) => ({
      code,
      type: detectInputType(code),
      time: now,
    }));
    records.value.unshift(...newRecords);
    if (records.value.length > MAX_RECORDS) {
      records.value.splice(MAX_RECORDS);
    }
  };

  const handleManualAdd = async () => {
    try {
      const { value } = await ElMessageBox.prompt('请输入要添加的条码或RFID：', '手动添加', {
        confirmButtonText: '添加',
        cancelButtonText: '取消',
        inputPattern: /\S+/,
        inputErrorMessage: '输入不能为空',
      });
      const manualCode = value?.trim();
      if (!manualCode) return;
      device_code.value = manualCode;
      handleAddToBatch();
    } catch {
      // 用户取消输入
    }
  };

  const handleClearRecords = async () => {
    if (records.value.length === 0) return;
    try {
      await ElMessageBox.confirm('确定要清除所有录入记录吗？该操作不可恢复。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      });
      records.value = [];
      ElMessage.success('已清除录入记录');
      setInputStatus('等待输入...');
    } catch {
      // 用户取消操作
    }
  };

  const handleExportRecords = () => {
    if (records.value.length === 0) {
      ElMessage.warning('暂无数据可导出');
      return;
    }
    const header = '数据,类型,时间\n';
    const csvContent =
      header +
      records.value
        .map((record) => `"${record.code}","${record.type}","${record.time}"`)
        .join('\n');
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `扫码记录_${new Date().toLocaleDateString().replace(/\//g, '-')}.csv`;
    link.click();
    URL.revokeObjectURL(url);
  };

  // 重置读取规则为默认值
  const resetReadRule = () => {
    readRuleConfig.value = {
      rfidLength: 24,
      rfidPrefix: 'E280',
      separator: ' ',
      customSeparator: '',
      autoSplitSticky: true,
      allowDuplicate: true,
    enableRFIDBuffer: true,
    rfidInputTimeout: 120,
    };
    ElMessage.success('已重置为默认规则');
  };

  // 保存读取规则
  const saveReadRule = () => {
    // 验证配置
    if (readRuleConfig.value.rfidLength < 1) {
      ElMessage.warning('RFID标签长度必须大于0');
      return;
    }
    if (readRuleConfig.value.separator === 'custom' && !readRuleConfig.value.customSeparator) {
      ElMessage.warning('请设置自定义分隔符');
      return;
    }
  if (readRuleConfig.value.rfidInputTimeout < 30) {
    ElMessage.warning('缓冲判定时间需大于等于30ms');
    return;
  }
    showReadRuleDialog.value = false;
    ElMessage.success('读取规则已保存');
  };

  const onOpen = () => {
    device_code.value = '';
    // check_no.value = '';
    deviceList.value = [];
    currentRecordId.value = null;
    pendingDeviceCodes.value = [];
    isNormalClose.value = false; // 重置标志
    records.value = [];
    setInputStatus('等待输入...');
  rfidInputBuffer.value = '';
  clearRFIDInputTimer();
  };

  // 对话框完全打开后聚焦输入框
  const onOpened = () => {
    focusDeviceCodeInput();
  };
  
  const findCheckRecord = (checkNo: string, list: any[]) => {
        console.log("lists::::",list)
        if (!Array.isArray(list)) return null;
        return list.find(item => item.check_no === checkNo);
    };

  /**
   * 添加或更新设备记录，如果存在相同设备编号则替换为最新数据
   * @param newItems 新添加的设备记录数组
   */
  const addOrUpdateDeviceList = (newItems: any[]) => {
    newItems.forEach((newItem) => {
      // 查找是否已存在相同的设备编号
      const existingIndex = deviceList.value.findIndex(
        (item) => item.device_code === newItem.device_code && item.check_no === newItem.check_no
      );

      if (existingIndex !== -1) {
        // 如果已存在，替换为最新数据（保留最新的那条）
        deviceList.value[existingIndex] = {
          ...newItem,
          scanned_quantity: newItem.scanned_quantity || 1,
        };
      } else {
        // 如果不存在，添加新记录
        deviceList.value.push({
          ...newItem,
          scanned_quantity: newItem.scanned_quantity || 1,
        });
      }
    });
  };

  /**
   * 分割单个字符串中的RFID粘连标签（不包含空格）
   * @param input 输入的设备编号字符串（已去除空格）
   * @param isFromSeparator 是否来自分隔符分割（如果是，则更保守地处理，避免错误分割）
   * @returns 分割后的设备编号数组
   */
  const splitRFIDStickyCodes = (input: string, isFromSeparator: boolean = false): string[] => {
    if (!input) return [];

    const { rfidLength, rfidPrefix, autoSplitSticky } = readRuleConfig.value;
    
    // 如果未启用自动分割粘连，直接返回
    if (!autoSplitSticky) {
      return [input];
    }

    // 如果来自分隔符分割，采用更保守的策略：只有当明确检测到粘连时才分割
    if (isFromSeparator) {
      // 如果输入长度小于等于配置长度，肯定是单个编码，不分割
      if (input.length <= rfidLength) {
        return [input];
      }
      
      // 只有当长度是配置长度的倍数且明显大于配置长度（至少2倍）时，才认为是粘连
      if (input.length > rfidLength * 2 && input.length % rfidLength === 0) {
        // 方法1: 如果配置了前缀，使用正则表达式匹配RFID标签
        if (rfidPrefix && rfidPrefix.trim()) {
          const prefixLength = rfidPrefix.length;
          const remainingLength = rfidLength - prefixLength;
          if (remainingLength > 0) {
            try {
              const escapedPrefix = rfidPrefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
              const rfidPattern = new RegExp(`${escapedPrefix}[0-9A-F]{${remainingLength}}`, 'gi');
              const matches = input.match(rfidPattern);
              
              // 如果匹配到多个RFID标签，说明是粘连的，返回分割后的数组
              if (matches && matches.length > 1) {
                return matches;
              }
            } catch (error) {
              console.warn('RFID前缀正则表达式构建失败:', error);
            }
          }
        }
        
        // 方法2: 按固定长度分割
        const codes: string[] = [];
        for (let i = 0; i < input.length; i += rfidLength) {
          const code = input.substring(i, i + rfidLength);
          if (code.trim()) {
            codes.push(code);
          }
        }
        if (codes.length > 1) {
          return codes;
        }
      }
      
      // 如果不符合粘连条件，返回原样
      return [input];
    }

    // 如果不是来自分隔符分割，使用原有逻辑（用于处理直接粘贴的粘连数据）
    // 方法1: 如果配置了前缀，使用正则表达式匹配RFID标签
    if (rfidPrefix && rfidPrefix.trim()) {
      const prefixLength = rfidPrefix.length;
      const remainingLength = rfidLength - prefixLength;
      if (remainingLength > 0) {
        try {
          // 转义前缀中的特殊字符，避免正则表达式错误
          const escapedPrefix = rfidPrefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
          // 构建正则表达式：前缀 + 剩余长度的十六进制字符
          const rfidPattern = new RegExp(`${escapedPrefix}[0-9A-F]{${remainingLength}}`, 'gi');
          const matches = input.match(rfidPattern);
          
          // 如果匹配到多个RFID标签，说明是粘连的，返回分割后的数组
          if (matches && matches.length > 1) {
            return matches;
          }
        } catch (error) {
          console.warn('RFID前缀正则表达式构建失败:', error);
          // 如果正则构建失败，继续使用固定长度分割方法
        }
      }
    }

    // 方法2: 如果长度是配置长度的倍数且大于配置长度，按固定长度分割
    // 这种情况适用于粘连的RFID标签（无论是否有前缀）
    if (input.length > rfidLength && input.length % rfidLength === 0) {
      const codes: string[] = [];
      for (let i = 0; i < input.length; i += rfidLength) {
        const code = input.substring(i, i + rfidLength);
        if (code.trim()) {
          codes.push(code);
        }
      }
      // 如果分割出多个，返回分割结果
      if (codes.length > 1) {
        return codes;
      }
    }

    // 如果都不匹配，返回原始输入作为单个设备编号
    return [input];
  };

  /**
   * 分割RFID粘连的设备编号
   * 支持分隔符分隔和粘连两种情况
   * RFID标签通常以特定前缀开头（如E280），且有固定长度（24字符）
   * @param input 输入的设备编号字符串
   * @returns 分割后的设备编号数组
   */
  const splitRFIDCodes = (input: string): string[] => {
    const trimmed = input.trim();
    if (!trimmed) return [];

    const { separator, customSeparator } = readRuleConfig.value;
    const actualSeparator = separator === 'custom' ? customSeparator : separator;

    console.log('splitRFIDCodes - 输入:', trimmed, '分隔符配置:', separator, '实际分隔符:', actualSeparator, '分隔符类型:', typeof actualSeparator, '长度:', actualSeparator?.length);

    // 方法0: 优先处理换行符分隔的情况（换行符是最明确的分隔符）
    // 检测各种换行符组合：\r\n (Windows), \n (Unix/Linux), \r (Mac)
    const hasNewline = /[\r\n]/.test(trimmed);
    
    if (hasNewline) {
      // 如果输入包含换行符，优先按换行符分割（无论配置如何）
      const parts = trimmed.split(/[\r\n]+/).filter(part => part.trim());
      console.log('检测到换行符，分割结果:', parts);
      
      if (parts.length > 1) {
        const result: string[] = [];
        // 对每个部分处理可能的粘连情况（传入 isFromSeparator=true，采用保守策略）
        for (const part of parts) {
          const trimmedPart = part.trim();
          if (trimmedPart) {
            const splitCodes = splitRFIDStickyCodes(trimmedPart, true);
            result.push(...splitCodes);
          }
        }
        console.log('换行符分割最终结果:', result);
        return result.length > 0 ? result : [trimmed];
      }
    }

    // 方法1: 处理配置的分隔符（如果配置了且不是换行符）
    if (actualSeparator && actualSeparator.trim() !== '' && actualSeparator !== '\n' && actualSeparator !== '\r\n' && actualSeparator !== '\r') {
      let parts: string[] = [];
      let hasSeparator = false;

      // 根据分隔符类型进行分割
      if (actualSeparator === '\t') {
        // 制表符分隔符
        hasSeparator = trimmed.includes('\t');
        if (hasSeparator) {
          parts = trimmed.split(/\t+/).filter(part => part.trim());
        }
      } else {
        // 其他分隔符（包括空格和自定义分隔符）
        hasSeparator = trimmed.includes(actualSeparator);
        if (hasSeparator) {
          try {
            // 转义特殊字符，匹配一个或多个连续的分隔符
            const escapedSeparator = actualSeparator.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
            const separatorPattern = new RegExp(escapedSeparator + '+', 'g');
            parts = trimmed.split(separatorPattern).filter(part => part.trim());
          } catch (error) {
            console.warn('分隔符正则表达式构建失败，使用字符串分割:', error);
            // 回退到简单的字符串分割
            parts = trimmed.split(actualSeparator).filter(part => part.trim());
          }
        }
      }

      // 如果检测到分隔符并成功分割，处理每个部分
      if (hasSeparator && parts.length > 0) {
        const result: string[] = [];
        // 对每个部分处理可能的粘连情况（传入 isFromSeparator=true，采用保守策略）
        for (const part of parts) {
          const trimmedPart = part.trim();
          if (trimmedPart) {
            const splitCodes = splitRFIDStickyCodes(trimmedPart, true);
            result.push(...splitCodes);
          }
        }
        console.log('配置分隔符分割最终结果:', result);
        return result.length > 0 ? result : [trimmed];
      }
    }

    // 方法2: 如果没有明确的分隔符，检查是否有空格（作为备选）
    const hasSpace = /\s/.test(trimmed);
    
    if (hasSpace) {
      // 如果输入包含空格，按空格分割
      const parts = trimmed.split(/\s+/).filter(part => part.trim());
      console.log('检测到空格，分割结果:', parts);
      
      if (parts.length > 1) {
        const result: string[] = [];
        // 对每个部分处理可能的粘连情况（传入 isFromSeparator=true，采用保守策略）
        for (const part of parts) {
          const trimmedPart = part.trim();
          if (trimmedPart) {
            const splitCodes = splitRFIDStickyCodes(trimmedPart, true);
            result.push(...splitCodes);
          }
        }
        console.log('空格分割最终结果:', result);
        return result.length > 0 ? result : [trimmed];
      }
    }

    // 方法3: 如果没有分隔符或分割失败，直接处理粘连情况
    const stickyResult = splitRFIDStickyCodes(trimmed);
    console.log('粘连处理结果:', stickyResult);
    return stickyResult;
  };

// 添加到待提交列表（不立即提交）
const handleAddToBatch = (triggeredByBuffer = false) => {
  if (!triggeredByBuffer) {
    commitRFIDBufferToTextarea();
  }
    if (!device_code.value || !check_no.value) {
      ElMessage.warning('请输入设备编号');
      setInputStatus('输入为空，请重新输入', '#e74c3c', 2000);
      return;
    }

    const input = device_code.value.trim();
    if (!input) {
      ElMessage.warning('设备编号不能为空');
      setInputStatus('输入为空，请重新输入', '#e74c3c', 2000);
      return;
    }

    // 自动分割RFID粘连的设备编号（分割函数内部已经去重）
    const codes = splitRFIDCodes(input);
    console.log('分割结果:', codes, '输入:', input, '配置:', readRuleConfig.value);
    
    if (codes.length === 0) {
      ElMessage.warning('未识别到有效的设备编号');
      setInputStatus('未识别到有效设备', '#e74c3c', 2000);
      return;
    }

    // 根据配置决定是否允许添加到待提交列表（与已存在的编码比较）
    let codesToAdd = codes;
    if (!readRuleConfig.value.allowDuplicate) {
      // 过滤掉已存在于待提交列表中的设备编号
      codesToAdd = codes.filter(code => !pendingDeviceCodes.value.includes(code));
      if (codesToAdd.length < codes.length) {
        const duplicateCount = codes.length - codesToAdd.length;
        ElMessage.warning(`已过滤 ${duplicateCount} 个重复的设备编号（与待提交列表中的编码重复）`);
      }
    }

    if (codesToAdd.length === 0) {
      ElMessage.warning('没有可添加的设备编号（可能全部重复）');
      setInputStatus('全部重复，未添加', '#e67e22', 2000);
      return;
    }

    // 批量添加到待提交列表
    pendingDeviceCodes.value.push(...codesToAdd);
    appendRecords(codesToAdd);
    
    // 显示提示信息
    if (codes.length > 1) {
      /* ElMessage.success(`已自动分割并添加 ${codesToAdd.length} 个设备编号`); */
      setInputStatus(`已录入 ${codesToAdd.length} 个编码`, '#27ae60', 1500);
    } else {
      /* ElMessage.success('已添加到待提交列表'); */
      setInputStatus(`成功录入${detectInputType(codesToAdd[0])}`, '#27ae60', 1500);
    }
    
    device_code.value = '';
  rfidInputBuffer.value = '';
    
    // 自动聚焦输入框，方便继续扫码
    focusDeviceCodeInput();
  };

  // 移除待提交的设备编号
  const removePendingCode = (index: number) => {
    pendingDeviceCodes.value.splice(index, 1);
  };

  // 清空待提交列表
  const clearPendingCodes = () => {
    pendingDeviceCodes.value = [];
  };

  // 批量提交设备编号
  const handleBatchSubmit = async () => {
    if (pendingDeviceCodes.value.length === 0 || !check_no.value) {
      ElMessage.warning('没有待提交的设备编号');
      return;
    }

    loading.value = true;
    const successList: any[] = [];
    const failList: string[] = [];

    try {
      // 优先使用批量提交接口
      const batchPayload = {
        check_no: check_no.value,
        device_codes: [...pendingDeviceCodes.value], // 复制数组，避免修改原数组
      };

      try {
        const batchRes = await api.ScanDeviceBatch(batchPayload);
        
        if (batchRes?.code === 2000) {
          // 批量提交成功，处理返回数据
          const reslist = await api.GetPermission();
          if (reslist?.code === 2000) {
            const record = findCheckRecord(check_no.value, reslist.data);
            currentRecordId.value = record?.id ?? null;

            // 处理批量返回的数据
            // 如果后端返回了详细的设备信息列表，使用返回的数据
            if (batchRes.data && Array.isArray(batchRes.data)) {
              // 后端返回了设备详情数组
              batchRes.data.forEach((item: any) => {
                successList.push({
                  device_code: item.device_code || item.deviceCode,
                  check_no: check_no.value,
                  productName: item.productName || '未知商品',
                  id: record?.id || 0,
                  status_display: record?.status_display || '',
                  device_name: item.device_name || item.deviceName || '未知设备',
                  device_category: item.device_category || item.deviceCategory || '未知分类',
                  scanned_quantity: item.scanned_quantity || 0,
                });
              });
            } else if (batchRes.data?.success_codes && Array.isArray(batchRes.data.success_codes)) {
              // 后端只返回了成功的设备编号列表
              batchRes.data.success_codes.forEach((code: string) => {
                successList.push({
                  device_code: code,
                  check_no: check_no.value,
                  productName: '未知商品',
                  id: record?.id || 0,
                  status_display: record?.status_display || '',
                  device_name: '未知设备',
                  device_category: '未知分类',
                  scanned_quantity: 1,
                });
              });
              
              // 处理失败的设备编号
              if (batchRes.data?.fail_codes && Array.isArray(batchRes.data.fail_codes)) {
                failList.push(...batchRes.data.fail_codes);
              }
            } else {
              // 如果后端没有返回详细数据，假设全部成功
              pendingDeviceCodes.value.forEach((code: string) => {
                successList.push({
                  device_code: code,
                  check_no: check_no.value,
                  productName: '未知商品',
                  id: record?.id || 0,
                  status_display: record?.status_display || '',
                  device_name: '未知设备',
                  device_category: '未知分类',
                  scanned_quantity: 1,
                });
              });
            }

            // 将成功的数据添加到列表（如果存在相同设备编号，保留最新的）
            addOrUpdateDeviceList(successList);

            // 显示提交结果并处理待提交列表
            if (successList.length > 0 && failList.length === 0) {
              // 全部成功，清空待提交列表
              pendingDeviceCodes.value = [];
              ElMessage.success(`提交成功`);
            } else if (successList.length > 0 && failList.length > 0) {
              // 部分成功，保留失败的设备编号
              pendingDeviceCodes.value = failList;
              ElMessage.warning(`成功提交 ${successList.length} 个，失败 ${failList.length} 个`);
            } else {
              // 全部失败，保留失败的设备编号
              pendingDeviceCodes.value = failList;
              ElMessage.error(`提交失败，共 ${failList.length} 个设备编号`);
            }
            return; // 批量提交成功，直接返回
          }
        } else {
          // 批量提交失败，记录错误但继续尝试逐个提交
          console.warn('批量提交失败，尝试逐个提交:', batchRes);
        }
      } catch (batchError) {
        // 批量接口不存在或出错，回退到逐个提交
        console.warn('批量提交接口不可用，使用逐个提交方式:', batchError);
      }

      // 回退方案：如果批量提交失败或接口不存在，使用逐个提交
      for (const code of pendingDeviceCodes.value) {
        try {
          const payload = {
            device_code: code,
            check_no: check_no.value,
          };
          
          const res = await api.ScanDevice(payload);
          if (res?.code === 2000) {
            const reslist = await api.GetPermission();
            if (reslist?.code === 2000) {
              const record = findCheckRecord(check_no.value, reslist.data);
              successList.push({
                ...payload,
                productName: res.data?.productName || '未知商品',
                id: record?.id || 0,
                status_display: record?.status_display || '',
                device_name: res.data?.device_name || '未知设备',
                device_category: res.data?.device_category || '未知分类',
                scanned_quantity: res.data?.scanned_quantity || 1,
              });
              currentRecordId.value = record?.id ?? null;
            }
          } else {
            failList.push(code);
          }
        } catch (error) {
          console.error(`提交设备编号 ${code} 失败:`, error);
          failList.push(code);
        }
      }

      // 将成功的数据添加到列表（如果存在相同设备编号，保留最新的）
      addOrUpdateDeviceList(successList);

      // 显示提交结果并处理待提交列表
      if (successList.length > 0 && failList.length === 0) {
        // 全部成功，清空待提交列表
        pendingDeviceCodes.value = [];
        ElMessage.success(`成功提交 ${successList.length} 个设备编号`);
      } else if (successList.length > 0 && failList.length > 0) {
        // 部分成功，保留失败的设备编号
        pendingDeviceCodes.value = failList;
        ElMessage.warning(`成功提交 ${successList.length} 个，失败 ${failList.length} 个`);
      } else {
        // 全部失败，保留失败的设备编号
        pendingDeviceCodes.value = failList;
        ElMessage.error(`提交失败，共 ${failList.length} 个设备编号`);
      }
    } finally {
      loading.value = false;
      focusDeviceCodeInput();
    }
  };

  // 保留原有的单个添加方法（兼容性）
  const handleAdd = async () => {
    if (!device_code.value || !check_no.value) return;

    const payload = {
        device_code: device_code.value,
        check_no: check_no.value,
    };
    
    loading.value = true;
    try {
      const res = await api.ScanDevice(payload);
      if (res?.code===2000) {
          const reslist=await api.GetPermission();
          if (reslist?.code===2000) {
              const record = findCheckRecord(check_no.value, reslist.data);
              // 添加或更新设备记录（如果存在相同设备编号，保留最新的）
              addOrUpdateDeviceList([{
                  ...payload,
                  productName: res.data?.productName || '未知商品',
                  id: record?.id||0,
                  status_display:record?.status_display||'',
                  device_name: res.data?.device_name || '未知设备',
                  device_category: res.data?.device_category || '未知分类',
                  scanned_quantity: res.data?.scanned_quantity || 1,
              }]);
              device_code.value = '';
              currentRecordId.value = record?.id ?? null;
          }
      }
    } finally {
      loading.value = false;
      // 在 loading 状态更新后聚焦
      await focusDeviceCodeInput();
    }
  };

  const onCompleteAll = async () => {
    if (!check_no.value) return;
    const res=await api.CompleteScan({ check_no: check_no.value });
    if (res?.code===2000) {
        ElMessage.success('完成盘点！');
        // 标记为正常关闭，避免 onClose 中再次调用取消接口
        isNormalClose.value = true;
        visible.value = false;
        emit('completed');
    }
  };

  const onCancelAll = async () => {
    if (!currentRecordId.value) return;
    const res=await api.CancelScan(currentRecordId.value);
    if (res?.code===2000) {
        ElMessage.success('取消盘点成功！');
        // 标记为正常关闭，避免 onClose 中再次调用取消接口
        isNormalClose.value = true;
        visible.value = false;
        emit('completed');
    }
  };
  
  const completeScan = async (row: any) => {
    const res=await api.CompleteScan({ check_no: row.check_no });
    if (res?.code===2000) {
        // const payload = {
        //     device_code: device_code.value,
        //     check_no: check_no.value,
        // };
        // const reslist=await api.GetPermission();
        // const record = findCheckRecord(check_no.value, reslist.data.results);
        // deviceList.value.push({
        //     ...payload,
        //     productName: res.data?.productName || '未知商品',
        //     id: record?.id||0,
        //     status_display:record?.status_display||'',
        //     // record,
        // });
        // btflag.value=false;
        ElMessage.success('完成盘点！');
       /*  visible.value = false */
    }
  };
  
  const cancelScan = async (row: any) => {
    const res=await api.CancelScan(row.id);
    if (res?.code===2000) {
        console.log("deviceList.value::",deviceList.value)
        deviceList.value = deviceList.value.filter(item => item.id !== row.id);
        console.log("deviceList.value22222::",deviceList.value)
        ElMessage.success('取消盘点成功！');
        visible.value = false
    }
  };
  
  defineExpose({ visible,setCheckNo});

  const onClose = async () => {
    // 如果是正常完成/取消盘点关闭，不调用取消接口，直接清理状态
    if (isNormalClose.value) {
      isNormalClose.value = false;
      // 清理状态
      check_no.value = '';
      pendingDeviceCodes.value = [];
      deviceList.value = [];
      currentRecordId.value = null;
      records.value = [];
      setInputStatus('等待输入...');
      return;
    }
    
    // 用户直接关闭对话框时，调用取消盘点接口
    console.log("currentRecordId.value::",currentRecordId.value, "check_no.value::", check_no.value)
    
    let recordId = currentRecordId.value;
    
    // 如果 currentRecordId 为 null，但 check_no 存在，尝试通过 check_no 查询获取 id
    if (!recordId && check_no.value) {
      try {
        const reslist = await api.GetPermission();
        if (reslist?.code === 2000) {
          const record = findCheckRecord(check_no.value, reslist.data);
          recordId = record?.id ?? null;
          console.log("通过 check_no 查询到的 id::", recordId);
        }
      } catch (error) {
        console.error('查询盘点记录失败:', error);
      }
    }
    
    // 如果存在盘点记录ID，调用取消盘点接口
    if (recordId) {
      try {
        const res = await api.CancelScan(recordId);
        if (res?.code === 2000) {
          ElMessage.success('取消盘点成功！');
        } else {
          ElMessage.warning(res?.msg || '取消盘点失败');
        }
      } catch (error) {
        console.error('取消盘点失败:', error);
        ElMessage.error('取消盘点失败');
      }
    }
    
    // 清理状态
    check_no.value = '';
    pendingDeviceCodes.value = [];
    deviceList.value = [];
    currentRecordId.value = null;
    records.value = [];
    setInputStatus('等待输入...');
  };


  onBeforeUnmount(() => {
    if (statusResetTimer) {
      clearTimeout(statusResetTimer);
    }
  if (rfidInputTimer) {
    clearTimeout(rfidInputTimer);
  }
  });


  </script>
  
<style scoped>
.form-row {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
  flex-wrap: wrap;
}

.pending-list {
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.pending-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.pending-title {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
}

.pending-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.pending-tags {
  margin-top: 8px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

.device-code-input {
  flex: 1 1 100%;
  min-height: 90px;
  padding: 12px 16px;
  font-size: 14px;
  border: 2px solid #e1e5ee;
  border-radius: 8px;
  outline: none;
  resize: vertical;
  transition: all 0.3s;
  font-family: 'Microsoft YaHei', sans-serif;
}

.device-code-input:focus {
  border-color: #4b6cb7;
  box-shadow: 0 0 0 3px rgba(75, 108, 183, 0.2);
}

.input-hint {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.input-status {
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.action-button {
  flex: 1;
}

.results-section {
  border: 1px solid #e1e5ee;
  border-radius: 8px;
  padding: 16px;
  background: #f9fafc;
  margin-bottom: 20px;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #182848;
  margin-bottom: 12px;
}

.section-count {
  font-size: 14px;
  color: #666;
}

.results-container {
  max-height: 240px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.result-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
  border-left: 4px solid #4b6cb7;
}

.result-content {
  display: flex;
  flex-direction: column;
}

.result-code {
  font-weight: 600;
  font-size: 15px;
  margin-bottom: 4px;
}

.result-time {
  font-size: 12px;
  color: #888;
}

.result-type {
  background: #eef2ff;
  color: #4b6cb7;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
}

.empty-state {
  text-align: center;
  color: #888;
  padding: 24px 0;
}

.empty-state i {
  display: block;
  font-size: 32px;
  margin-bottom: 8px;
  color: #c3cfe2;
}
</style>

<style>
/* 分隔符选择器下拉框样式，确保在对话框内正确显示 */
.separator-select-popper {
  z-index: 9999 !important;
}

/* 确保下拉框在对话框上方显示 */
.separator-select-popper.el-select-dropdown {
  z-index: 9999 !important;
}

/* 防止对话框遮罩层拦截下拉框点击 */
.el-overlay {
  z-index: 2000 !important;
}

.el-overlay .el-dialog {
  z-index: 2001 !important;
}
</style>
  