<template>
	<el-dialog v-model="visible" :title="isView ? '查看' : isCollect ? '领取' : '归还'" width="75%" :close-on-click-modal="false" @close="onCancel">
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="借用单信息" name="first">       
                <el-form :model="form" label-width="110px" label-position="top" :rules="rules" ref="formRef">
                    <el-row :gutter="16">
                        <el-col :span="8">
                            <el-form-item label="借用单编号" prop="application_no">
                                <el-input v-model="form.application_no" placeholder="自动生成" disabled />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                          <el-form-item label="借用人类型" prop="borrower_type">
                            <el-select v-model="form.borrower_type" :placeholder="isView?'':'请选择借用人角色'"  :disabled="true">
                              <el-option label="管理员用户" :value=0 />
                              <el-option label="应用用户" :value=1 />
                              <el-option label="外部用户" :value=2 />
                            </el-select>
                          </el-form-item>
                        </el-col>
                        <el-col :span="8" >
                          <!-- <el-form-item label="借用人" prop="external_borrower_name"  v-if="form.borrower_type !== 2">
                            <el-input v-model="form.borrower_info.name" placeholder="请输入借用人" :disabled="true" />
                          </el-form-item> -->
                          <el-form-item label="借用人" prop="admin_borrower" v-if="form.borrower_type == 0">
                        
                            <el-select v-model="form.admin_borrower" :placeholder="isView?'':'请选择借用人'" :disabled="true" >
                              <el-option  :label="adminList.name" :value="adminList.id" />
                            </el-select>
                          </el-form-item>
                          <el-form-item label="借用人" prop="app_user_borrower" v-if="form.borrower_type == 1">
                            <el-select v-model="form.app_user_borrower.id" :placeholder="isView?'':'请选择借用人'" :disabled="true" >
                              <el-option v-for="item in allUserList"  :key="item.id" :label="item.name" :value="item.id" />
                            </el-select>
                          </el-form-item> 
                          <el-form-item label="借用人" prop="external_borrower_name" v-if="form.borrower_type == 2">
                            <el-input v-model="form.external_borrower_name" :placeholder="isView?'':'请输入借用人'" :disabled="true" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="8" v-if="form.borrower_type !== 2">
                            <el-form-item label="学号/工号" prop="user_code" >
                       <!--      {{ form.borrower_info.user_code }} -->
                                <el-input v-model="form.app_user_borrower.user_code" :placeholder="isView?'':'请输入学号/工号'"  :disabled="true"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="联系电话" v-if="form.borrower_type !== 2">
                                <el-input v-model="form.app_user_borrower.mobile" :placeholder="isView?'':'请输入联系电话'" :disabled="true" />
                            </el-form-item>
                            <el-form-item label="联系电话" v-if="form.borrower_type == 2">
                                <el-input v-model="form.external_borrower_phone" :placeholder="isView?'':'请输入联系电话'" :disabled="true" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="借用部门" prop="borrower_dept">
                                <el-input v-model="form.borrower_dept" placeholder="请输入借用部门" :disabled="true" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="预计归还时间" prop="expected_end_time">
                                <el-date-picker v-model="form.expected_end_time" type="date" 
                                format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD"
                                :disabledDate="disabledDate" placeholder="请选择预计归还时间" style="width: 100%"  :disabled="true"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item label="个人/团队" prop="team_type" >
                                <el-select v-model="form.team_type" placeholder="请选择" :disabled="true">
                                    <el-option label="个人" :value="0" />
                                    <el-option label="团队" :value="1" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4" v-show="form.team_type===1">
                            <el-form-item label="团队人数" prop="team_members_count">
                                <el-input v-model="form.team_members_count" :placeholder="isView?'':'请输入'"  :disabled="true"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="16" v-show="form.team_type===1">
                            <el-form-item label="团队其他人员名单" prop="team_members">
                                <el-input v-model="form.team_members" :placeholder="isView?'':'请输入团队其他人员名单'"  :disabled="true"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="借用原因" prop="purpose">
                                <el-input v-model="form.purpose" type="textarea" :placeholder="isView?'':'请输入借用原因'" :disabled="true" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                          <!-- ||form.approver_info.name -->
                            <el-form-item label="审批人" prop="applicant_remark_type">
                                <el-input :model-value="displayApproverName" placeholder="-" :disabled="true" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="20">
                            <el-form-item label="备注" prop="applicant_remark">
                                <el-input v-model="form.applicant_remark" :placeholder="isView?'':'请输入备注'"  :disabled="true"/>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <div style="margin: 16px 0 8px 0; font-weight: bold"> {{ isView ? '借用列表' : (isCollect ? '借用列表' : '归还列表') }}</div>
                    <el-table :data="form.items.filter(item => item.device === null)" border style="width: 50%; margin-bottom: 12px">
                        <el-table-column type="index" label="序号" width="60" />
                        <el-table-column prop="device_category_name" label="设备分类" />
                        <el-table-column :label="isView ? '数量' : (isCollect ? '借用数量' : '归还数量')">
                        <template #default="{ row }">
                        <el-input v-model="row.quantity" type="number" :min="1" prop="quantity" size="small" :disabled="true" />
                        </template>
                        </el-table-column>
                        <el-table-column label="操作" width="80">
                            <template #default="{ $index }">
                                <el-button type="text" style="color: red" @click="removeItem($index)" :disabled="true">移除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-button type="primary" @click="addItem" v-if="!isView" :disabled="true">选择设备分类</el-button>
                    <div style="margin: 16px 0 8px 0; font-weight: bold">预借配件信息</div>
                    <el-input v-model="form.accessories" :placeholder="isView?'':'请输入预借配件信息'"  :disabled="true"/>

                    <div style="margin: 16px 0 8px 0; font-weight: bold" >附件</div>
                    <!-- <el-upload
                      action="#"
                      drag
                      :list-type="'picture'"
                      accept=".bmp,.gif,.jpeg,.jpg,.png,‌.webp,.svg"
                      multiple
                      :show-file-list="true"
                      :file-list="attachmentFileList"
                      :on-success="handleUploadSuccess"
                      :on-error="handleUploadError"
                      :disabled="true"
                    >
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或 <em>点击上传</em></div>
                    </el-upload> -->
                     <el-upload
                      :disabled="true"
                      action="#"
                      list-type="picture-card"
                      :on-preview="handlePictureCardPreview"
                      :on-remove="handleRemoves"
                      :file-list="attachmentFileList"
                    >
                    <el-icon><Plus /></el-icon>
                    </el-upload>
                    <div v-if="isView && form.latest_renewal" style="margin-top: 8px;">
                    <div style="font-weight: bold; margin-bottom: 8px">续借信息</div>
                    <el-row :gutter="16">
                      <el-col :span="4">
                        <el-form-item label="续借天数">
                          <el-input :model-value="form.latest_renewal?.renewal_days" :disabled="true">
                            <template #append>天</template>
                          </el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="21">
                        <el-form-item label="续借理由">
                          <el-input :model-value="form.latest_renewal?.renewal_reason" type="textarea" :disabled="true" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </div>
                </el-form>
                
                <!-- 审批信息流程展示 -->
                <!-- <div v-if="isView"  style="margin-top: 24px; padding: 0 12px">
                <div style="font-weight: bold; margin-bottom: 12px">审批流程进度</div>
                    <el-steps :active="activeStep" align-center>
                        <el-step
                        title="创建申请"
                        :description="`创建时间：${ timeline.create }`"
                        icon="CircleCheck"
                        :status="activeStep >= 1 ? 'finish' : 'wait'"
                        />
                        <el-step
                        title="待审批"
                        description="待审批人审批"
                        icon="CircleCheck"
                        :status="activeStep >= 2 ? 'finish' : 'wait'"
                        />
                        <el-step
                        title="审批通过"
                        :description="`审批人：${timeline.approver}，时间：${timeline.approve}`"
                        icon="CircleCheck"
                        :status="activeStep >= 3 ? 'finish' : 'wait'"
                        />
                        <el-step
                        title="流程完成"
                        description="流程已结束"
                        icon="CircleCheck"
                        :status="activeStep >= 4 ? 'finish' : 'wait'"
                        />
                    </el-steps>
                </div> -->
                <div v-if="isView"  style="margin-top: 24px; padding: 0 12px">
                <div style="font-weight: bold; margin-bottom: 12px">审批流程进度</div>
                <el-steps :active="steps.length" align-center>
                  <el-step
                    v-for="(step, index) in steps"
                    :key="index"
                    :title="step.title"
                    :description="step.description"
                    icon="CircleCheck"
                    :status="step.status"
                  />
                  </el-steps>

                </div>
            </el-tab-pane>
        <el-tab-pane v-if="isCollect && !shouldHideDeviceList" label="设备清单" name="second">
            <el-form :model="form" label-width="110px">
                <el-row :gutter="16">
                    <el-col :span="24">
                        <div style="margin: 8px 0">
                            <textarea
                                ref="searchInputRef"
                                v-model="searchText"
                                class="device-code-input"
                                placeholder="设备编号（支持扫码枪/RFID批量录入）"
                                :disabled="loading"
                                autocomplete="off"
                                rows="1"
                                style="width: 300px; vertical-align: top;"
                                @input="handleDeviceInput"
                                @keydown="handleRFIDKeydown"
                                @blur="handleDeviceBlur"
                                @keydown.enter.prevent="handleDeviceEnter"
                            ></textarea>
                            <el-button type="primary" style="margin-left: 16px" @click="handleAdd">手动借用</el-button>
                        </div>
                        <el-table :data="deviceList" border style="width: 100%">
                            <el-table-column type="index" label="序号" width="60" align="center" />
                            <el-table-column prop="device_code" label="设备编号" align="center" />
                            <el-table-column prop="device_type" label="设备分类" align="center" />
                            <el-table-column prop="device_name" label="设备名称" align="center" />
                            <el-table-column prop="borrow_count" label="借用数量" align="center" width="150">
                                <template #default="{ row }">
                                    <el-input-number v-model="row.borrow_count" :disabled="isView" :min="1" :max="row.available_quantity" size="small" />
                                </template>
                            </el-table-column>
                            <el-table-column prop="brand" label="品牌" align="center" />
                            <el-table-column prop="device_specification" label="规格型号" align="center" />
                            <!-- <el-table-column prop="warehouse" label="存放仓库" align="center" /> -->
                            <el-table-column label="操作" width="80" align="center">
                                <template #default="{ $index }">
                                    <el-button type="text" style="color: red" :disabled="isView" @click="handleRemove($index)">移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
                <el-row :gutter="16" style="margin-top: 16px">
                    <el-col :span="24">
                        <div style="font-weight: bold; margin-bottom: 8px">实借配件信息</div>
                        <el-input v-if="isCollect" v-model="collectAccessories" :disabled="isView" type="textarea" :placeholder="isView?'':'请输入实借配件信息'" />
                        <el-input v-else v-model="form.pre_borrow_accessories" :disabled="isView" type="textarea" :placeholder="isView?'':'请输入实借配件信息'" />
                    </el-col>
                    <el-col :span="24" style="margin-top: 16px">
                        <div style="font-weight: bold; margin-bottom: 8px">备注</div>
                        <el-input v-model="remark" type="textarea" :disabled="isView" :placeholder="isView?'':'请输入备注'" />
                    </el-col>
                </el-row>
                <el-row :gutter="16" style="margin-top: 16px">
                    <el-col :span="24">
                      <div style="font-weight: bold; margin-bottom: 8px">异常记录 <span>{{ 
                          abnormalList?.length ? 
                          abnormalList.reduce((sum, item) => sum + (Number(item?.condition) || 0), 0)
                          : 0 
                        }}</span> 次</div>
                        <el-table v-if="abnormalList.length > 0" :data="abnormalList" border style="width: 100%">
                          <!-- <el-table-column type="index" label="序号" width="60" align="center" />
                            <el-table-column prop="application_no" label="借用单编号" align="center" /> -->
                            <el-table-column prop="operator_name" label="借用人" align="center" />
                            <el-table-column prop="user_code" label="学号" align="center" />
                            <el-table-column prop="emergency_phone" label="借用人电话" align="center" />
                           <!--  <el-table-column prop="time" label="发生时间" align="center" /> -->
                            <el-table-column prop="type" label="异常" align="center">
                                <template #default="{ row }">
                                    {{ row.type }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="condition" label="数量" align="center">
                              <template #default="{ row }">
                                {{ row.condition }}
                              </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
            </el-form>
        </el-tab-pane>
        <el-tab-pane v-else-if="!shouldHideDeviceList" label="设备清单" name="third">
            <el-form :model="form" label-width="110px">
                <el-row :gutter="16">
                    <el-col :span="24">
                        <div style="margin: 8px 0" v-if="!isView" >
                            <textarea
                                ref="returnSearchInputRef"
                                v-model="returnSearchText"
                                class="device-code-input"
                                placeholder="设备编号（支持扫码枪/RFID批量录入）"
                                :disabled="loading"
                                autocomplete="off"
                                rows="1"
                                style="width: 300px; vertical-align: top;"
                                @input="handleReturnDeviceInput"
                                @keydown="handleReturnRFIDKeydown"
                                @blur="handleReturnDeviceBlur"
                                @keydown.enter.prevent="handleReturnDeviceEnter"
                            ></textarea>
                            <el-button type="primary" style="margin-left: 16px" @click="handleAdd" :disabled="isView">手动归还</el-button>
                        </div>
                        <el-table :data="sortedReturnDeviceList" border style="width: 100%" >
                            <!-- <el-table-column type="selection" width="55" align="center" />@selection-change="handleSelectionChange" -->
                            <el-table-column type="index" label="序号" width="60" align="center" />
                            <el-table-column prop="device_code" label="设备编号" align="center" />
                            <!-- <el-table-column prop="device_type" label="设备分类" align="center" /> -->
                            <el-table-column prop="device_name" label="设备名称" align="center" />
                            <el-table-column label="已归还数量" width="110" align="center">
                                <template #default="{ row }">
                                    {{ row.returned_quantity ?? 0 }}
                                </template>
                            </el-table-column>
                            <el-table-column
                                v-if="showUnreturnedReturnTableColumns"
                                label="未归还可还"
                                width="110"
                                align="center"
                            >
                                <template #default="{ row }">
                                    {{ row.available_quantity ?? 0 }}
                                </template>
                            </el-table-column>
                            <el-table-column
                                v-if="showUnreturnedReturnTableColumns"
                                prop="borrow_count"
                                label="归还数量"
                                align="center"
                                width="150"
                            >
                                <template #default="{ row }">
                                    <el-input-number
                                        v-if="!isView && isReturnLinePendingReturn(row)"
                                        v-model="row.borrow_count"
                                        :min="0"
                                        :max="(row.available_quantity ?? 0) > 0 ? (row.available_quantity ?? 0) : 0"
                                        :disabled="(row.available_quantity ?? 0) <= 0"
                                        size="small"
                                        @change="() => clampReturnBorrowCount(row)"
                                    />
                                    <span
                                        v-else-if="isView && isReturnLinePendingReturn(row)"
                                        class="return-cell-text"
                                    >{{ row.borrow_count ?? 0 }}</span>
                                    <span v-else class="return-cell-placeholder">—</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="brand" label="品牌" align="center" />
                            <el-table-column prop="model" label="规格型号" align="center" />
                            <!-- <el-table-column prop="warehouse" label="存放仓库" align="center" /> -->
                            <el-table-column prop="status" label="状态" align="center">
                                <template #default="{ row }">
                                  {{ row.return_status.label }}
                                   <!--  <el-tag v-if="!isView" :type="row.status === '已归还' ? 'success' : 'warning'">{{ row.status }}</el-tag>
                                    <el-tag v-else-if="['已领取', '已归还'].includes(form.status_label)">{{ form.status_label }}</el-tag> -->
                                    <!-- <span v-else>{{ form.status_label }}</span> -->
                                </template>
                            </el-table-column>
                            <el-table-column prop="status" label="归还时间" align="center">
                              <template #default="{ row }">
                                {{ row.return_time ? dayjs(row.return_time).format('YYYY-MM-DD HH:mm:ss') : (row.return_status?.label === '已归还' ? dayjs().format('YYYY-MM-DD HH:mm:ss') : '') }}
                              </template>
                            </el-table-column>
                            <el-table-column label="操作" width="120" align="center">
                                <template #default="{ row }">
                                 <!--  && (!returnDeviceList[$index]?.condition || returnDeviceList[$index]?.photos?.length==0)&& row.problem_records?.length ==0 -->
                                  <el-button :disabled="isView" type="text" style="color: red;"  
                                   v-if="!isView"
                                  @click="handleAbnormal(row)">异常操作</el-button>
                                  <el-button 
                                    
                                    type="text" 
                                    style="color: #409EFF;margin-left:0" 
                                    @click="handleViewAbnormal(row)"
                                    v-if="row.problem_records?.length || row.condition || row.photos?.length"
                                  >查看异常</el-button>
                                    <!-- <el-button type="text" v-if="!isView" :disabled="isView" style="color: red" @click="handleReturnRemove($index)">移除</el-button> -->
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
                <el-row :gutter="16" style="margin-top: 16px">
                    <el-col :span="16">
                        <div style="font-weight: bold; margin-bottom: 8px">实借配件信息</div>
                        <el-input v-model="form.pre_borrow_accessories" :disabled="true" :placeholder="isView?'':'请输入实借配件信息'" />
                    </el-col>
                    <el-col :span="8">
                        <div style="font-weight: bold; margin-bottom: 8px">当前状态</div>
                        <el-input v-model="returnStatus" v-if="!isView"  :disabled="true" placeholder="" style="width: 150px" />
                         <el-input  :value="form.status==7?'已归还':returnStatus" v-else  :disabled="true" placeholder="" style="width: 150px" />
                      <el-button type="primary" v-if="!isView"  style="margin-left: 16px" @click="clickReturn"
                       :disabled="returnStatus=='已归还'||isView">归还</el-button>
                    </el-col>
                    <el-col :span="24" style="margin-top: 16px">
                        <div style="font-weight: bold; margin-bottom: 8px">备注</div>
                        <el-input 
                            v-model="displayReturnRemark"
                            type="textarea" 
                            :disabled="isView" 
                            :placeholder="isView?'':'请输入备注'" 
                        />
                    </el-col>
                </el-row>
                <el-row :gutter="16" style="margin-top: 16px">
                    <el-col :span="24">
                        <div style="font-weight: bold; margin-bottom: 8px">异常记录 <span>{{ 
                          returnAbnormalList?.length ? 
                          returnAbnormalList.reduce((sum, item) => sum + (Number(item?.condition) || 0), 0)
                          : 0 
                        }}</span> 次</div>
                        <el-table v-if="returnAbnormalList?.length > 0" :data="returnAbnormalList" border style="width: 100%">
                           <!--  <el-table-column type="index" label="序号" width="60" align="center" />
                            <el-table-column prop="application_no" label="借用单编号" align="center" /> -->
                            <el-table-column prop="operator_name" label="借用人" align="center" />
                            <el-table-column prop="user_code" label="学号" align="center" />
                            <el-table-column prop="emergency_phone" label="借用人电话" align="center" />
                           <!--  <el-table-column prop="time" label="发生时间" align="center" /> -->
                            <el-table-column prop="type" label="异常" align="center">
                                <template #default="{ row }">
                                    {{ row.type }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="condition" label="数量" align="center">
                              <template #default="{ row }">
                                {{ row.condition }}
                              </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
            </el-form>
        </el-tab-pane>
        </el-tabs>
		<template #footer>
			<el-button @click="onCancel">关闭</el-button>
			<el-button type="primary" @click="onSubmit" v-if="!isView"> {{ isCollect ? '提交' : '确认' }}</el-button>
		</template>
	</el-dialog>
	<SelectDeviceDialog 
    v-model:visible="showSelectDeviceDialog"  
    @confirm="onDeviceSelected" 
    :device-ids="unreturnedDeviceIds"
    :return-mode="activeName === 'third'"
    :device-status-map="deviceStatusMap"
    :selected-device-codes="selectedDeviceCodes"
    :disabled-device-ids="disabledDeviceIds"
/>
	<SettlementDialog v-model:visible="showSettlementDialog" :settlement-data="settlementData" :modelValue="borrowForm" />
    <AbnormalDialog v-model:visible="showAbnormalDialog" @confirm="onAbnormalConfirm" />
    <ViewAbnormalDialog 
      v-model:visible="showViewAbnormalDialog" 
      :abnormal-data="currentAbnormalData" 
    />
    <!-- 图片预览对话框 -->
    <el-dialog v-model="dialogVisible" title="图片预览" width="auto" center>
      <img width="100%" :src="dialogImageUrl" alt="Preview Image" style="max-width: 100%; max-height: 80vh;" />
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineEmits, onMounted, onBeforeUnmount, computed, nextTick } from 'vue';
import SelectDeviceDialog from './SelectDeviceDialog/index.vue';
import SettlementDialog from './SettlementDialog.vue';
import AbnormalDialog from './AbnormalDialog/index.vue';
import ViewAbnormalDialog from './ViewAbnormalDialog/index.vue';
import dayjs from 'dayjs';
import { ElMessage } from 'element-plus';
import * as api from '../../api';
import * as deviceApi from '../../../device/api';
import { CollectEquipment, ReturnEquipment } from '../../api';
import type { TabsPaneContext } from 'element-plus';
import { getUserInfo } from '../../../login/api';
import { request } from '/@/utils/service';

// 禁止选择今天之前的日期
const disabledDate = (time: Date) => {
  // 获取今天的开始时间（准确到日）
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  // 返回true表示禁用，禁用今天之前的所有日期
  return time.getTime() < today.getTime()
}
/* 获取管理员列表 */
const adminList = ref([]);

async function getAdminList() {
	const res = await getUserInfo();
	adminList.value = res.data;
	console.log("adminList.value:::",adminList.value)	
}
/*  */
/* 获取所有用户 */
const allUserList = ref([]);
let allUserLoaded = false;
const allUserLoading = ref(false);
async function getAllUserList() {
	if (allUserLoaded || allUserLoading.value) return;
	allUserLoading.value = true;
	try {
		// 分页拉取，避免一次性超大 limit 硬编码
		const pageSize = 100;
		let page = 1;
		const users: any[] = [];
		while (true) {
			const res = await api.GetAllUser({ page, limit: pageSize });
			const list = Array.isArray(res?.data) ? res.data : [];
			users.push(...list);
			if (list.length < pageSize) break;
			page += 1;
		}
		allUserList.value = users;
		// 设置默认选择（仅在当前未有选中时）
		if ((!form.value.app_user_borrower || !form.value.app_user_borrower.id) && allUserList.value.length > 0) {
			const first: any = allUserList.value[0];
			form.value.app_user_borrower = {
				id: first.id,
				name: first.name,
				user_code: first.user_code,
				mobile: first.mobile
			};
		}
		allUserLoaded = true;
	} catch (e) {
		/* empty */
	} finally {
		allUserLoading.value = false;
	}
}

interface ApiResponse {
  code: number;
  data?: any;
  message?: string;
}

// 用户最小结构用于表单回显
interface AppUserBorrower {
  id: number | string;
  name?: string;
  user_code?: string;
  mobile?: string;
}

// 定义接口
interface Device {
  id: string | number;
  category_name: string;
  name?: string;
  brand?: string;
  model?: string;
  warehouse: string;
  device_specification?: string;
  device_name?: string;
}

interface DeviceListItem {
  device_no: string | number;
  device_code?: string;
  device_type: string;
  device_name?: string;  // 改为可选
  borrow_count: number;
  brand: string;
  model?: string;  // 改为可选
  warehouse: string;
  status?: string;
  return_status?: {
    value?: number;
    label?: string;
  };
  return_time?: string;
  is_return?: boolean;
  condition?: string;
  photos?: Array<{
    filename: string;
    data: string;
  }>;
  device_specification?: string;
  /** 归还页签：可归还上限，来自 items.pending_quantity */
  available_quantity?: number;
  /** 截止当前已在库登记归还的数量，来自 items.returned_quantity */
  returned_quantity?: number;
  problem_records?: any[];
  damage_type?: number;
  /** 借用单明细行接口返回的更新时间，用于列表排序 */
  line_update_at?: string;
  /** 本页对行做了归还/数量等操作时的排序时间戳，与 line_update_at 取较大者参与排序 */
  sort_touched_at?: number;
}

interface FormItem {
  device: string | number;
  remark: string;
  quantity: number;
  location: string;
  device_name?: string;
  device_specification?: string;
  condition?: string;
  photos?: Array<{
    filename: string;
    data: string;
  }>;
}

interface FormData {
  application_no: string;
  emergency_contact: string;
  emergency_phone: string;
  app_user_borrower: AppUserBorrower | any;
  team_type: number;
  team_members_count: number;
  team_members: string;
  expected_start_time: string;
  expected_end_time: string;
  borrower_dept: string;
  purpose: string;
  applicant_remark_type: string;
  applicant_remark: string;
  items: FormItem[];
  accessory_info: string;
  borrow_type: number;
  return_location: string;
  status_label?: string;
  id?: number;
  records?: any[];
  borrower_info?: {
    user_code: string;
  };
  borrower_damage_count?: number;
  borrower_overdue_count?:number;
  accessories?: string;
  pre_borrow_accessories?:string;
  latest_renewal?: {
    renewal_days?: number | string;
    renewal_reason?: string;
  };
  problem_remarks?: string[];
}

interface AbnormalData {
  damage_type:number;
  condition: string;
  photos: Array<{
    filename: string;
    data: string;
  }>;
}

interface AbnormalRecord {
  application_no: string;
  operator_name: string;
  user_code: string;
  emergency_phone: string;
  type: '损坏' | '逾期';
  condition: number;
  create_time: string;
}

const now = dayjs().format('YYYY-MM-DD HH:mm:ss');

const props = defineProps<{ visible: boolean; modelValue?: any }>();

const isEdit = computed(() => props.modelValue?.mode === 'edit');
const isView = computed(() => props.modelValue?.mode === 'view');
const isAdd = computed(() => props.modelValue?.mode === 'add');
const isCollect = computed(() => props.modelValue?.mode === 'collect');
const isReturn = computed(() => props.modelValue?.mode === 'return');

// 获取待审批人显示名称（与 buildSteps 中逻辑一致）
// 待审批时显示当前环节审批人；审批完成后显示全部环节（老师、学院领导、管理员）的审批人
function getPendingApproverDisplay(data: any): string {
  if (!data) return '';
  const adminInfo = data.admin_approver_info;
  const status = data.status;

  // 审批完成后：按实际审批顺序（老师→学院领导→管理员）显示
  // 优先用 approval_records 的审批顺序；否则用 all_steps_status 按 step_order
  if (status >= 2 && status !== 3) {
    const approvedRecords = data.approval_records?.filter((r: any) => r.status === 1) || [];
    if (approvedRecords.length) {
      const sorted = [...approvedRecords].sort(
        (a: any, b: any) => (a.step_order ?? 0) - (b.step_order ?? 0)
      );
      const names = sorted
        .map((r: any) => (r.approver_name || r.app_user_approver_name || r.name || '').trim())
        .filter(Boolean);
      if (names.length) return names.join('、');
    }
    if (adminInfo?.all_steps_status?.length) {
      const allNames: string[] = [];
      const seen = new Set<string>();
      const sortedSteps = [...adminInfo.all_steps_status].sort(
        (a: any, b: any) => (a.step_order ?? 0) - (b.step_order ?? 0)
      );
      for (const step of sortedSteps) {
        if (step.approvers?.length) {
          for (const a of step.approvers) {
            const name = (a.name || '').trim();
            if (name && !seen.has(name)) {
              seen.add(name);
              allNames.push(name);
            }
          }
        }
      }
      if (allNames.length) return allNames.join('、');
    }
  }

  // 待审批时：取当前待审批环节，排除已通过的步骤（API 可能将已通过步骤仍标为 is_current）
  const isApproved = (s: any) => s.status === 'approved' || s.status_label === '已通过';
  const isPendingOrCurrent = (s: any) =>
    !isApproved(s) && (
      s.status === 'pending' || s.status_label === '待审核' ||
      s.status === 'current' || s.status_label === '当前步骤' || s.is_current === true
    );
  const candidateSteps = adminInfo?.all_steps_status?.filter(isPendingOrCurrent) || [];
  const sortedCandidates = [...candidateSteps].sort((a: any, b: any) => (a.step_order ?? 0) - (b.step_order ?? 0));
  const pendingStep = sortedCandidates[0];
  if (pendingStep?.approvers?.length) {
    const stepName = pendingStep.step_name || '';
    let approvers = pendingStep.approvers;
    if (stepName.includes('老师')) {
      // 老师环节：仅显示 type 为 app_user 的审批人（老师姓名）
      approvers = approvers.filter((a: any) => a.type === 'app_user');
    } else if (stepName.includes('管理员')) {
      // 二级管理员/管理员环节：仅显示 type 为 admin 的审批人（超级管理员）
      approvers = approvers.filter((a: any) => a.type === 'admin');
    }
    const names = approvers.map((a: any) => a.name).filter((n: string) => n && n.trim());
    if (names.length) return names.join('、');
  }
  const currentApprovers = adminInfo?.current_step?.approvers;
  if (Array.isArray(currentApprovers) && currentApprovers.length) {
    const names = currentApprovers.map((a: any) => a.name).filter((n: string) => n && n.trim());
    if (names.length) return names.join('、');
  }
  const currentStep = adminInfo?.all_steps_status?.find((s: any) => s.is_current);
  if (currentStep?.approvers?.length) {
    const names = currentStep.approvers.map((a: any) => a.name).filter((n: string) => n && n.trim());
    if (names.length) return names.join('、');
  }
  if (data.approval_records?.length) {
    const pendingRecords = data.approval_records.filter(
      (item: any) => (status === 1 ? item.status !== 1 : item.status !== 0)
    );
    const names = pendingRecords
      .map((item: any) => item.approver_name || item.app_user_approver_name || item.name)
      .filter((name: string) => name && name.trim());
    if (names.length) return names.join('、');
  }
  return data.approver_info?.name || '未知';
}

// 表单审批人显示：待审批时与流程步骤一致，审批完成后显示管理员
const displayApproverName = computed(() => {
  const data = form.value as any;
  if (!data?.id) return '';
  const status = data.status;
  if (status >= 2 && status !== 3) return '管理员'; // 审批通过
  if (status >= 4) return '管理员'; // 流程完成
  if (status === 1) return getPendingApproverDisplay(data); // 待审批
  if (status === 3) {
    const rejectNames = data.approval_records
      ?.filter((item: any) => item.status === 2)
      ?.map((item: any) => item.approver_name || item.app_user_approver_name || item.name)
      ?.filter((name: string) => name && name.trim()) || [];
    return rejectNames.join('、') || data.approver_info?.name || '未知';
  }
  return data.approver_info?.name || data.admin_approver_info?.name || '';
});

// 计算是否应该隐藏设备清单标签页
const shouldHideDeviceList = computed(() => {
  if (!isView.value) return false;
  // 检查状态
  const status = (form.value as any).status;
  const statusLabel = (form.value as any).status_label;

  // 审批拒绝：隐藏设备清单
  const isRejected = status === 3 || (typeof statusLabel === 'string' && statusLabel.includes('拒绝'));
  if (isRejected) {
    return true;
  }

  // 强制显示：状态大于 5 或状态标签为"已借出"
  if ((typeof status === 'number' && status > 5) || statusLabel === '已借出') {
    return false;
  }

  // 审批通过：隐藏设备清单（不影响已借出/更高级状态的强制显示）
  const isApproved = typeof statusLabel === 'string' && statusLabel.includes('已批准');
  if (isApproved) {
    return true;
  }

  // 待审批状态：隐藏设备清单
  const isPendingApproval = status < 2 || statusLabel === '待审批';

  // 其他情况默认显示
  return isPendingApproval;
});

// 计算设备状态映射
const deviceStatusMap = computed(() => {
  const statusMap: Record<string | number, any> = {};
  returnDeviceList.value.forEach(device => {
    if (device.device_no && device.return_status) {
      statusMap[device.device_no] = device.return_status;
    }
  });
  return statusMap;
});

const emit = defineEmits(['update:visible', 'update:modelValue', 'submit']);
const visible = ref(props.visible);
const formRef = ref();

// 图片预览相关
const dialogImageUrl = ref('');
const dialogVisible = ref(false);

const timeline = ref({
  create: '',
  approve: '',
  approver: ''
});
// const activeStep = ref(1);

const activeName = ref('first');
const returnStatus = ref('未归还'); // 添加独立的状态变量

// 输入框引用
const searchInputRef = ref<any>(null);
const returnSearchInputRef = ref<any>(null);

// 借用列表相关数据
const searchText = ref('');
const deviceList = ref<DeviceListItem[]>([]);
const accessoryInfo = ref('');
const remark = ref('');
// 领取模式下的"实借配件信息"本地输入，不回显历史
const collectAccessories = ref('');
// RFID高速扫码缓冲相关
const rfidInputBuffer = ref('');
// RFID标签数组，用于收集批量识别的标签
const rfidTagArray = ref<string[]>([]);
// 当前正在输入的标签
const currentRfidTag = ref('');
// 正在处理的标签集合，用于去重
const processingTags = ref<Set<string>>(new Set());
// 是否正在处理标签数组
const isProcessingTagArray = ref(false);
// 待提交的设备编号数组（参考 InventoryDialog 实现）
const pendingDeviceCodes = ref<string[]>([]);
// 是否正在自动循环提交
const isAutoSubmitting = ref(false);
let rfidInputTimer: ReturnType<typeof setTimeout> | null = null;
// 统一的标签数组处理延迟定时器，避免多次触发
let processTagArrayTimer: ReturnType<typeof setTimeout> | null = null;
const loading = ref(false);
// 记录最后一次输入时间，用于检测是否是高速扫码输入
let lastInputTime = 0;
// 记录连续输入次数，用于判断是否是扫码输入
let consecutiveInputCount = 0;
// RFID读取规则配置（简化版，可根据需要扩展）
const readRuleConfig = ref({
  enableRFIDBuffer: true, // 是否启用RFID缓冲
  rfidInputTimeout: 120, // RFID缓冲判定时间(ms)
  separator: ' ', // 分隔符
  minInputSpeed: 30, // 最小输入速度(ms)，低于此值认为是扫码输入
  tagSeparatorTimeout: 100, // 标签分隔判定时间(ms)，超过此时间认为是一个新标签
});

// 归还设备相关数据
const returnSearchText = ref('');
const returnDeviceList = ref<DeviceListItem[]>([]);
const returnAccessoryInfo = ref('');
const returnRemark = ref('');
const selectedDevices = ref<DeviceListItem[]>([]); // 添加选中设备列表
// 归还流程 RFID高速扫码缓冲相关
const returnRfidInputBuffer = ref('');
// 归还流程 RFID标签数组，用于收集批量识别的标签
const returnRfidTagArray = ref<string[]>([]);
// 归还流程当前正在输入的标签
const returnCurrentRfidTag = ref('');
// 归还流程正在处理的标签集合，用于去重
const returnProcessingTags = ref<Set<string>>(new Set());
// 归还流程是否正在处理标签数组
const isProcessingReturnTagArray = ref(false);
let returnRfidInputTimer: ReturnType<typeof setTimeout> | null = null;
// 统一的归还标签数组处理延迟定时器，避免多次触发
let returnProcessTagArrayTimer: ReturnType<typeof setTimeout> | null = null;
// 记录归还流程最后一次输入时间，用于检测是否是高速扫码输入
let returnLastInputTime = 0;
// 记录归还流程连续输入次数，用于判断是否是扫码输入
let returnConsecutiveInputCount = 0;

// 备注显示值计算属性：查看模式下显示 problem_remarks[0]，否则显示 returnRemark
const displayReturnRemark = computed({
  get: () => {
    if (isView.value && form.value.problem_remarks?.[0]) {
      return form.value.problem_remarks[0];
    }
    return returnRemark.value;
  },
  set: (val: string) => {
    if (!isView.value) {
      returnRemark.value = val;
    }
  }
});

/** 从借用单明细行解析待归还数量：优先用 pending_quantity，缺省时用借出-已还推算（与后端 items 一致，避免硬编码） */
function getPendingUnreturnedFromItem(item: any): number {
  if (item == null) return 0;
  const raw = item.pending_quantity;
  if (raw !== undefined && raw !== null && String(raw) !== '') {
    const n = Math.floor(Number(raw));
    if (!Number.isNaN(n)) return Math.max(0, n);
  }
  const borrowed = Number(item.borrowed_quantity) || 0;
  const returned = Number(item.returned_quantity) || 0;
  return Math.max(0, borrowed - returned);
}

/** 从借用单 items 行解析「明细更新时间」（兼容常见后端字段名，避免写死单一路径） */
function getItemLineUpdateTimeForSort(item: any): string | undefined {
  if (item == null || typeof item !== 'object') return undefined;
  const v =
    item.update_datetime ?? item.update_time ?? item.modified_time ?? item.update_at;
  if (v == null || v === '') return undefined;
  return String(v);
}

function getReturnRowSortMs(row: DeviceListItem): number {
  const serverRaw = row.line_update_at;
  const serverMs =
    serverRaw && dayjs(serverRaw).isValid() ? dayjs(serverRaw).valueOf() : 0;
  const localMs = row.sort_touched_at ?? 0;
  return Math.max(serverMs, localMs);
}

function touchReturnRowSort(row: DeviceListItem) {
  row.sort_touched_at = Date.now();
}

/** 将 form.items 单行映射为归还列表行：上限为待归还；归还数量由扫码/手工录入，从 0 起算 */
function mapFormItemToReturnDeviceListRow(item: any): DeviceListItem {
  const pending = getPendingUnreturnedFromItem(item);
  const lineUpdate = getItemLineUpdateTimeForSort(item);
  return {
    device_no: item.device,
    device_code: item.device_code,
    device_type: item.remark,
    device_name: item.device_name,
    borrow_count: 0,
    brand: item.brand || item.device_brand || '',
    model: item.device_specification,
    warehouse: item.location || item.device_storage_location || '',
    problem_records: item.problem_records,
    return_status: item.return_status,
    return_time: item.return_times,
    available_quantity: pending,
    returned_quantity: Math.max(0, Number(item.returned_quantity) || 0),
    line_update_at: lineUpdate,
    sort_touched_at: 0
  };
}

function clampReturnBorrowCount(row: DeviceListItem) {
  const max = row.available_quantity ?? 0;
  if (max <= 0) {
    row.borrow_count = 0;
    return;
  }
  let n = Number(row.borrow_count) || 0;
  if (n < 0) n = 0;
  if (n > max) n = max;
  row.borrow_count = n;
  touchReturnRowSort(row);
}

/** 是否仍有待归还（有未归还可还）：用于表格列在「只展示已归还」与「展示待还+本次归还」间切换 */
function isReturnLinePendingReturn(row: DeviceListItem) {
  return (Number(row.available_quantity) || 0) > 0;
}

/**
 * 扫码命中列表中的设备时：归还数量 +1，不超过待归还数。
 * 成功返回 null；失败返回提示文案。不在此调用 ElMessage，由扫码/RFID 批处理处统一只弹一次。
 */
function tryApplyReturnScanIncrement(row: DeviceListItem): string | null {
  const cap = row.available_quantity ?? 0;
  if (cap <= 0) {
    return '该设备无待归还数量';
  }
  const current = Number(row.borrow_count) || 0;
  if (current >= cap) {
    return '该设备归还数量已达待归还上限';
  }
  row.borrow_count = current + 1;
  if (row.borrow_count >= cap) {
    row.is_return = true;
    row.return_time = dayjs().format('YYYY-MM-DD HH:mm:ss');
  }
  touchReturnRowSort(row);
  return null;
}

// 统一判定「该明细是否已把本次可归还数记满」：用于选设备白名单/全部完成判断（不依赖硬编码业务状态值）
const isDeviceReturned = (device: any) => {
  const cap = Number(device?.available_quantity) || 0;
  if (cap <= 0) return true;
  return (Number(device?.borrow_count) || 0) >= cap;
};

// 过滤未归还设备的 device_no 列表，用于设备选择弹窗的排除
const unreturnedDeviceIds = computed(() =>
  returnDeviceList.value
    .filter((d) => !isDeviceReturned(d))
    .map((d) => d.device_no)
);

// 是否全部已归还（仅在归还页签生效）
const allReturned = computed(() => unreturnedDeviceIds.value.length === 0);

/** 列表中是否仍有「待归还」行：为 false 时整表隐藏「未归还可还」「归还数量」两列（仅保留已归还数量等） */
const showUnreturnedReturnTableColumns = computed(() =>
  returnDeviceList.value.some((d) => (Number(d.available_quantity) || 0) > 0)
);

/** 归还设备表按「明细/本页最近修改时间」降序，最近在前 */
const sortedReturnDeviceList = computed(() =>
  [...returnDeviceList.value].sort(
    (a, b) => getReturnRowSortMs(b) - getReturnRowSortMs(a)
  )
);

//审批步骤
const steps = ref<any[]>([]);
// 仓库映射（id -> name）
const warehouseMap = ref<Record<string, string>>({});

async function loadWarehouses() {
	try {
		const res = await request({
			url: '/api/system/warehouse/',
			method: 'get',
			params: { page: 1, limit: 999 }
		});
		if (res?.code === 2000 && Array.isArray(res.data)) {
			warehouseMap.value = Object.fromEntries(
				res.data.map((w: any) => [String(w.id), w.name])
			);
		}
	} catch (e) {
		/* empty */
	}
}

function getWarehouseName(id: any) {
	const key = id != null ? String(id) : '';
	return warehouseMap.value[key] ?? id;
}

/** 从 Promise.allSettled 单条结果安全取出 success/message，避免解构 undefined 导致整批 try 抛错、误报「处理批次时发生错误」 */
function readSettledListStepResult(
  result: PromiseSettledResult<unknown>,
  codeLabel: string
): { success: boolean; message?: string } {
  if (result.status === 'rejected') {
    const err = result.reason instanceof Error ? result.reason.message : String(result.reason);
    return { success: false, message: `处理设备编号 ${codeLabel} 时发生错误: ${err}` };
  }
  const v = result.value as { success?: boolean; message?: string } | null | undefined;
  if (v == null || typeof v !== 'object' || typeof v.success !== 'boolean') {
    return { success: false, message: `处理设备编号 ${codeLabel} 时返回数据异常` };
  }
  return { success: v.success, message: v.message };
}

/**
 * 从设备查询接口解析可借/可用数量（领取页扫码）：先取根字段，再取 inventory.available_quantity
 */
function getDeviceAvailableQuantityForBorrow(device: any): number {
	if (device == null) return 0;
	const top = device.available_quantity;
	if (top !== undefined && top !== null && String(top) !== '') {
		const n = Number(top);
		if (!Number.isNaN(n)) return Math.max(0, Math.floor(n));
	}
	const inv = device.inventory?.available_quantity;
	if (inv !== undefined && inv !== null && String(inv) !== '') {
		const n = Number(inv);
		if (!Number.isNaN(n)) return Math.max(0, Math.floor(n));
	}
	return 0;
}

// 添加结算单相关的状态
const showSettlementDialog = ref(false);
const settlementData = ref<any>(null);
const borrowForm = ref<any>(null);

// 添加异常操作相关的状态
const showAbnormalDialog = ref(false);
const currentAbnormalDeviceNo = ref<string | number | null>(null);

// 添加查看异常相关的状态
const showViewAbnormalDialog = ref(false);
const currentAbnormalData = ref<AbnormalData>({
  damage_type:0,
  condition: '',
  photos: []
});

//审批
function buildSteps(data: any) {
  steps.value = [
    {
      title: '创建申请',
      description: `创建时间：${data.create_datetime ? dayjs(data.create_datetime).format('YYYY-MM-DD HH:mm:ss') : ''}`,
      status: 'finish'
    },
    {
      title: '待审批',
      description: `待审批人:${getPendingApproverDisplay(data)} 审批`,
      status: data.status >= 2 ? 'finish' : 'process'
    }
  ];

  const approverinfo = data.approver_info ?? data.admin_approver_info


  if (data.status >= 2&&data.status!=3 && data.borrow_type!=1) {
    // 将审批记录倒序排列
    const reversedApprovalRecords = [...data.approval_records]
    // 先找出所有审批通过的记录
    const approvedRecords = reversedApprovalRecords.filter((item:any) => item.status === 1)
    const lastApprovedIndex = approvedRecords.length - 1
    
    reversedApprovalRecords.forEach((item:any,index:number) => {
      if(item.status === 1){
        // 找到当前记录在审批通过记录中的索引
        const currentApprovedIndex = approvedRecords.findIndex((record:any) => record === item)
        // 判断是否是最后一个审批通过的记录
        const isLastApproved = currentApprovedIndex === lastApprovedIndex
        
       /*  if(index == 1){1
        steps.value.push({
          title: '审批通过',
            description: `审批人：${item.approver_name||item.app_user_approver_name}，时 间：${item.approve_time}`,
            status: 'finish'
          });
        }else{ */
          // 只在最后一个审批通过的记录中显示领取仓库
          const warehouseInfo = isLastApproved ? `,领取仓库:${getWarehouseName(data.warehouse)||'暂无仓库'}` : ''
          steps.value.push({
            title: '审批通过',
            description: `审批人：${item.approver_name||item.app_user_approver_name}，时 间：${item.create_datetime ? dayjs(item.create_datetime).format('YYYY-MM-DD HH:mm:ss') : ''}${warehouseInfo}`,
            status: 'finish'
          });
        /* } */
      }
    });
  } else if (data.status === 3) {
    // console.log("data.approver_name:::",data.approver_info.name)
    const rejectNames = data.approval_records
      .filter((item:any) => item.status === 2)
      .map((item:any) => item.approver_name || item.app_user_approver_name || item.name)
      .filter((name:any) => name && name.trim());
    const rejectReason = data.approval_records
      .filter((item:any) => item.status === 2)
      .map((item:any) => item.approve_remark)
      .filter((reason:any) => reason && reason.trim());
    const rejectTime = data.approval_records
      .filter((item:any) => item.status === 2)
      .map((item:any) => item.approve_time)
      .filter((time:any) => time && time.trim());
    steps.value.push({
      title: '审批拒绝',
      description: `审批人：${rejectNames.join('、')}，拒绝原因: ${rejectReason.join('、')},时间：${rejectTime.join('、')}`,
      status: 'error'
    });
  }

  if (data.status >= 4 ||data.borrow_type==1) {
    steps.value.push({
      title: '流程完成',
      description: '流程已结束',
      status: 'finish'
    });
  }
}

// 处理异常操作（按 device_no 定位，避免与「按时间排序的表格」下标错位）
const handleAbnormal = (row: DeviceListItem) => {
  currentAbnormalDeviceNo.value = row.device_no;
  showAbnormalDialog.value = true;
};

// 处理异常操作确认
const onAbnormalConfirm = (data: { condition: string; photos: any[]; damage_type?: number }) => {
  const key = currentAbnormalDeviceNo.value;
  if (key != null && key !== '') {
    const device = returnDeviceList.value.find((d) => d.device_no === key);
    if (device) {
      device.condition = data.condition;
      device.photos = data.photos;
      device.damage_type = data.damage_type;
      touchReturnRowSort(device);
      ElMessage.success('异常信息已保存');
    }
  }
  currentAbnormalDeviceNo.value = null;
};

// 处理查看异常
const handleViewAbnormal = (row: DeviceListItem) => {
  const device = row;
  console.log("device:::",device);
  if (device) {
    if(device.problem_records?.length){
      console.log(device.problem_records?.[0].damage_type.value)
      currentAbnormalData.value = {
        damage_type: Number(device.problem_records?.[0].damage_type.value) || 0,/* ||device.damage_type.value */
        condition: device.problem_records?.[0].device_condition_after ||'',
        photos: device.problem_records?.[0].returned_images.map((item:any)=>item.image_url) ||[]
      };
    }else{
      currentAbnormalData.value = {
        damage_type: device.damage_type ||0,
        condition: device.condition ||'',
        photos: device.photos ||[]
      };
    }
    showViewAbnormalDialog.value = true;
  }
};

// 清理RFID输入定时器
const clearRFIDInputTimer = () => {
  if (rfidInputTimer) {
    clearTimeout(rfidInputTimer);
    rfidInputTimer = null;
  }
};

// 清理标签数组处理延迟定时器
const clearProcessTagArrayTimer = () => {
  if (processTagArrayTimer) {
    clearTimeout(processTagArrayTimer);
    processTagArrayTimer = null;
  }
};

// 清理归还流程RFID输入定时器
const clearReturnRFIDInputTimer = () => {
  if (returnRfidInputTimer) {
    clearTimeout(returnRfidInputTimer);
    returnRfidInputTimer = null;
  }
};

// 清理归还标签数组处理延迟定时器
const clearReturnProcessTagArrayTimer = () => {
  if (returnProcessTagArrayTimer) {
    clearTimeout(returnProcessTagArrayTimer);
    returnProcessTagArrayTimer = null;
  }
};

// 处理RFID标签数组，逐个检索并提交
// 自动循环提交待提交的设备编号（参考 InventoryDialog 实现）
const autoSubmitPendingCodes = async () => {
  // 如果正在提交或没有待提交的设备编号，直接返回
  if (isAutoSubmitting.value || pendingDeviceCodes.value.length === 0) {
    return;
  }
  
  isAutoSubmitting.value = true;
  
  try {
    // 复制待提交的设备编号数组并清空，避免在处理过程中被修改
    const codesToSubmit = [...pendingDeviceCodes.value];
    pendingDeviceCodes.value = [];
    
    console.log(`[autoSubmitPendingCodes] 开始自动提交，共 ${codesToSubmit.length} 个设备编号:`, codesToSubmit);
    
    // 逐个循环提交，每个设备编号独立处理，不受成功或失败影响
    for (let i = 0; i < codesToSubmit.length; i++) {
      const code = codesToSubmit[i];
      if (!code || !code.trim()) continue;
      
      const trimmedCode = code.trim();
      
      try {
        // 查询设备信息
        const res = await deviceApi.GetList({ 
          page: 1, 
          limit: 1, 
          code: trimmedCode,
          status: 1 
        });
        
        if (res.data && res.data.length > 0) {
          const device = res.data[0];
          const avail = getDeviceAvailableQuantityForBorrow(device);
          if (avail <= 0) {
            const label = [device.name, device.code].filter(Boolean).join(' ') || trimmedCode;
            ElMessage.warning(`设备 ${label}（${trimmedCode}）库存不足`);
            continue;
          }
          
          // 检查设备是否已存在于列表中
          const existingDevice = deviceList.value.find(d => d.device_no === device.id);
          if (existingDevice) {
            // 如果已存在，增加借用数量
            existingDevice.borrow_count++;
            console.log(`设备 ${trimmedCode} 已存在，借用数量+1`);
          } else {
            // 如果不存在，添加到列表
            deviceList.value.push({
              device_no: device.id,
              device_code: device.code,
              device_type: device.category_name,
              device_name: device.name || '',
              borrow_count: 1,
              brand: device.brand || device.device_brand || '',
              device_specification: device.specification,
              model: device.model || '',
              warehouse: device.warehouse,
              available_quantity: avail
            });
            console.log(`设备 ${trimmedCode} 已添加到列表`);
          }
        } else {
          console.warn(`未找到设备编号: ${trimmedCode}`);
        }
      } catch (error) {
        // 即使某个设备编号处理失败，也继续处理下一个，不受影响
        console.error(`处理设备编号 ${trimmedCode} 失败:`, error);
      }
      
      // 每个设备编号处理完后稍作延迟，避免请求过快
      if (i < codesToSubmit.length - 1) {
        await new Promise(resolve => setTimeout(resolve, 50));
      }
    }
    
    console.log(`[autoSubmitPendingCodes] 自动提交完成，共处理 ${codesToSubmit.length} 个设备编号`);
  } catch (error) {
    console.error(`[autoSubmitPendingCodes] 自动提交过程中发生错误:`, error);
  } finally {
    isAutoSubmitting.value = false;
    
    // 如果还有待提交的设备编号，继续处理
    if (pendingDeviceCodes.value.length > 0) {
      setTimeout(() => {
        autoSubmitPendingCodes();
      }, 100);
    }
  }
};

const processRfidTagArray = async () => {
  if (rfidTagArray.value.length === 0 || isProcessingTagArray.value) return;
  
  isProcessingTagArray.value = true;
  
  // 使用 try-finally 确保状态总是被重置
  try {
    // 复制标签数组并清空，避免在处理过程中被修改
    const tagsToProcess = [...rfidTagArray.value];
    rfidTagArray.value = [];
    
    console.log(`[processRfidTagArray] 开始处理，收到 ${tagsToProcess.length} 个标签:`, tagsToProcess);
    
    // 去重处理：过滤掉正在处理或已处理的标签
    // 注意：不要在这里就添加到 processingTags，而是在实际开始处理时才添加
    const uniqueTagsToProcess = tagsToProcess.filter(tag => {
      const trimmedTag = tag.trim();
      if (!trimmedTag) return false;
      // 只跳过正在处理的标签，不在这里添加
      const shouldProcess = !processingTags.value.has(trimmedTag);
      if (!shouldProcess) {
        console.log(`[processRfidTagArray] 标签 ${trimmedTag} 正在处理中，跳过`);
      }
      return shouldProcess;
    });
    
    console.log(`[processRfidTagArray] 去重后需要处理 ${uniqueTagsToProcess.length} 个标签:`, uniqueTagsToProcess);
    
    // 将所有标签分割后的设备编号先缓存到 pendingDeviceCodes 数组
    const allCodes: string[] = [];
    
    for (const tag of uniqueTagsToProcess) {
      const trimmedTag = tag.trim();
      if (!trimmedTag) continue;
      
      // 分割标签，可能包含多个设备编号
      const codes = splitDeviceCodes(trimmedTag);
      const uniqueCodes = Array.from(new Set(codes.map(code => code.trim()))).filter(Boolean);
      
      // 添加到缓存数组（去重）
      uniqueCodes.forEach(code => {
        if (!allCodes.includes(code) && !pendingDeviceCodes.value.includes(code)) {
          allCodes.push(code);
        }
      });
    }
    
    // 将设备编号添加到待提交列表
    if (allCodes.length > 0) {
      pendingDeviceCodes.value.push(...allCodes);
      console.log(`[processRfidTagArray] 已将 ${allCodes.length} 个设备编号添加到待提交列表:`, allCodes);
      
      // 触发自动循环提交
      if (!isAutoSubmitting.value) {
        autoSubmitPendingCodes();
      }
    }
    
    // 所有标签处理完成后，清理处理标志并重新聚焦输入框
    console.log(`[processRfidTagArray] 所有标签已缓存到待提交列表，共 ${allCodes.length} 个设备编号`);
    console.log(`[processRfidTagArray] 当前待提交列表中的设备编号数量:`, pendingDeviceCodes.value.length);
  
  } catch (outerError) {
    // 捕获整个处理过程中的任何未预期错误，确保状态被重置
    console.error(`[processRfidTagArray] 处理过程中发生未预期错误:`, outerError);
    ElMessage.error('处理标签时发生错误，但已尝试处理所有标签');
  } finally {
    // 确保无论发生什么，状态都被重置
    isProcessingTagArray.value = false;
    loading.value = false;
    searchText.value = '';
    
    // 清理处理中的标签标记（延迟清理，避免立即重复处理）
    setTimeout(() => {
      processingTags.value.clear();
    }, 1000);
    
    nextTick(() => {
      if (searchInputRef.value) {
        searchInputRef.value.focus();
        searchInputRef.value.select();
      }
    });
  }
};

// 提交RFID缓冲区内容
const submitRFIDBuffer = () => {
  if (!readRuleConfig.value.enableRFIDBuffer) {
    // 如果未启用RFID缓冲，直接使用 searchText 进行搜索
    if (searchText.value.trim()) {
      handleScanSearch();
    }
    return;
  }
  
  // 如果有标签数组，优先处理标签数组
  if (rfidTagArray.value.length > 0) {
    clearRFIDInputTimer();
    consecutiveInputCount = 0;
    lastInputTime = 0;
    processRfidTagArray();
    return;
  }
  
  if (!rfidInputBuffer.value && !currentRfidTag.value) {
    // 如果没有缓冲内容，使用 searchText 进行搜索
    if (searchText.value.trim()) {
      handleScanSearch();
    }
    return;
  }
  
  // 如果有当前标签，先添加到标签数组（去重）
  if (currentRfidTag.value.trim()) {
    const tag = currentRfidTag.value.trim();
    if (!rfidTagArray.value.includes(tag) && !processingTags.value.has(tag)) {
      rfidTagArray.value.push(tag);
    }
    currentRfidTag.value = '';
  }
  
  // 如果有缓冲内容，也添加到标签数组（去重）
  if (rfidInputBuffer.value.trim()) {
    const tag = rfidInputBuffer.value.trim();
    if (!rfidTagArray.value.includes(tag) && !processingTags.value.has(tag)) {
      rfidTagArray.value.push(tag);
    }
    rfidInputBuffer.value = '';
  }
  
  clearRFIDInputTimer();
  consecutiveInputCount = 0;
  lastInputTime = 0;
  
  // 处理标签数组
  if (rfidTagArray.value.length > 0) {
    processRfidTagArray();
  }
};

// 调度RFID缓冲区提交（延迟提交）
const scheduleRFIDBufferSubmit = () => {
  if (!readRuleConfig.value.enableRFIDBuffer) return;
  clearRFIDInputTimer();
  const delay = Math.max(readRuleConfig.value.rfidInputTimeout || 120, 30);
  rfidInputTimer = setTimeout(() => {
    console.log(`[scheduleRFIDBufferSubmit] 延迟提交触发，当前状态:`, {
      currentRfidTag: currentRfidTag.value,
      rfidInputBuffer: rfidInputBuffer.value,
      searchText: searchText.value,
      rfidTagArray: rfidTagArray.value
    });
    
    // 如果 searchText 中有内容，优先检查是否包含多个标签（通过换行、回车等分隔）
    if (searchText.value.trim()) {
      const codes = splitDeviceCodes(searchText.value);
      console.log(`[scheduleRFIDBufferSubmit] searchText 分割得到 ${codes.length} 个代码:`, codes, '原始内容长度:', searchText.value.length);
      
      // 无论有多少个标签，都添加到标签数组
      if (codes.length > 0) {
        codes.forEach(code => {
          const trimmedCode = code.trim();
          if (trimmedCode && !rfidTagArray.value.includes(trimmedCode) && !processingTags.value.has(trimmedCode)) {
            rfidTagArray.value.push(trimmedCode);
            console.log(`[scheduleRFIDBufferSubmit] 添加标签到数组: ${trimmedCode}`);
          }
        });
        searchText.value = '';
      }
    }
    
    // 如果当前标签有内容，先保存到标签数组（去重）
    if (currentRfidTag.value.trim()) {
      const tag = currentRfidTag.value.trim();
      if (!rfidTagArray.value.includes(tag) && !processingTags.value.has(tag)) {
        rfidTagArray.value.push(tag);
        console.log(`[scheduleRFIDBufferSubmit] 添加当前标签到数组: ${tag}`);
      }
      currentRfidTag.value = '';
    }
    // 如果有缓冲内容，也添加到标签数组（去重）
    if (rfidInputBuffer.value.trim()) {
      const tag = rfidInputBuffer.value.trim();
      if (!rfidTagArray.value.includes(tag) && !processingTags.value.has(tag)) {
        rfidTagArray.value.push(tag);
        console.log(`[scheduleRFIDBufferSubmit] 添加缓冲标签到数组: ${tag}`);
      }
      rfidInputBuffer.value = '';
    }
    
    console.log(`[scheduleRFIDBufferSubmit] 延迟提交时，标签数组共有 ${rfidTagArray.value.length} 个标签:`, rfidTagArray.value);
    
    // 处理标签数组，使用统一的延迟处理机制
    if (rfidTagArray.value.length > 0) {
      // 清除之前的延迟处理定时器（如果存在）
      clearProcessTagArrayTimer();
      
      // 设置统一的延迟处理，确保所有标签都被收集后再处理
      processTagArrayTimer = setTimeout(() => {
        processTagArrayTimer = null;
        if (rfidTagArray.value.length > 0 && !isProcessingTagArray.value) {
          console.log(`[scheduleRFIDBufferSubmit] 延迟处理，最终标签数组:`, rfidTagArray.value);
          processRfidTagArray();
        }
      }, 300); // 增加延迟时间到300ms，确保所有标签都被收集
    }
  }, delay);
};

// 处理设备输入（用于同步 textarea 内容，仅在缓冲模式下使用）
const handleDeviceInput = () => {
  // 如果启用了RFID缓冲，检查 searchText 中是否包含多个标签（通过换行、回车等分隔）
  if (readRuleConfig.value.enableRFIDBuffer && searchText.value.trim()) {
    // 检查是否包含换行符或回车符
    if (/[\r\n]/.test(searchText.value)) {
      // 如果包含换行符，说明可能有多个标签
      const codes = splitDeviceCodes(searchText.value);
      console.log(`[handleDeviceInput] 检测到换行符，分割得到 ${codes.length} 个代码:`, codes, '原始内容长度:', searchText.value.length, '原始内容:', searchText.value.substring(0, 200));
      
      // 无论有多少个标签，都添加到标签数组（包括单个标签的情况）
      if (codes.length > 0) {
        codes.forEach(code => {
          const trimmedCode = code.trim();
          if (trimmedCode && !rfidTagArray.value.includes(trimmedCode) && !processingTags.value.has(trimmedCode)) {
            rfidTagArray.value.push(trimmedCode);
            console.log(`[handleDeviceInput] 添加标签到数组: ${trimmedCode}`);
          }
        });
        console.log(`[handleDeviceInput] 标签数组共有 ${rfidTagArray.value.length} 个标签:`, rfidTagArray.value);
        // 清空 searchText，避免重复处理
        searchText.value = '';
        // 清空当前标签和缓冲区，因为已经添加到数组了
        currentRfidTag.value = '';
        rfidInputBuffer.value = '';
        // 如果有标签数组且当前没有在处理，使用统一的延迟处理机制
        if (rfidTagArray.value.length > 0 && !isProcessingTagArray.value) {
          clearRFIDInputTimer();
          
          // 清除之前的延迟处理定时器（如果存在）
          clearProcessTagArrayTimer();
          
          // 设置统一的延迟处理，确保所有标签都被收集后再处理
          processTagArrayTimer = setTimeout(() => {
            processTagArrayTimer = null;
            if (rfidTagArray.value.length > 0 && !isProcessingTagArray.value) {
              console.log(`[handleDeviceInput] 延迟处理，最终标签数组:`, rfidTagArray.value);
              processRfidTagArray();
            }
          }, 300); // 增加延迟时间到300ms，确保所有标签都被收集
        }
        return;
      }
    }
  }
  
  // 如果缓冲区有内容，确保 textarea 显示与缓冲区一致
  // 这主要用于处理退格键等操作后的同步
  if (currentRfidTag.value || rfidInputBuffer.value) {
    const displayValue = currentRfidTag.value || rfidInputBuffer.value;
    if (searchText.value !== displayValue) {
      searchText.value = displayValue;
    }
  }
  // 注意：正常输入时，不干预 textarea 的内容，让默认行为处理
};

// 检测是否是高速扫码输入（通过输入速度判断）
// 返回值：{ isHighSpeed: boolean, isFirstInput: boolean, isNormalInput: boolean, timeSinceLastInput: number }
const checkInputSpeed = () => {
  const now = Date.now();
  const timeSinceLastInput = lastInputTime > 0 ? now - lastInputTime : 0;
  const isFirstInput = lastInputTime === 0;
  
  if (!isFirstInput) {
    lastInputTime = now;
  }
  
  return {
    isFirstInput,
    timeSinceLastInput,
    isHighSpeed: timeSinceLastInput > 0 && timeSinceLastInput < readRuleConfig.value.minInputSpeed,
    isNormalInput: timeSinceLastInput > 200
  };
};

// 处理RFID键盘输入（高速扫码）
const handleRFIDKeydown = (event: KeyboardEvent) => {
  // 如果未启用RFID缓冲，直接返回，不拦截
  if (!readRuleConfig.value.enableRFIDBuffer) {
    return;
  }
  
  // 不拦截修饰键组合（如 Ctrl+C, Ctrl+V 等）
  if (event.ctrlKey || event.metaKey || event.altKey) {
    return;
  }
  
  // 处理回车键
  if (event.key === 'Enter') {
    // 回车键由 @keydown.enter.prevent="handleDeviceEnter" 处理
    // 这里不处理，让 handleDeviceEnter 统一处理
    return;
  }
  
  // 处理退格键
  if (event.key === 'Backspace') {
    // 如果有当前标签或缓冲内容，处理缓冲
    if (currentRfidTag.value || rfidInputBuffer.value) {
      event.preventDefault();
      if (currentRfidTag.value) {
        currentRfidTag.value = currentRfidTag.value.slice(0, -1);
        rfidInputBuffer.value = currentRfidTag.value;
      } else {
        rfidInputBuffer.value = rfidInputBuffer.value.slice(0, -1);
      }
      searchText.value = rfidInputBuffer.value || currentRfidTag.value;
    }
    // 否则让默认行为处理
    return;
  }
  
  // 处理普通字符输入
  if (event.key.length === 1) {
    const inputInfo = checkInputSpeed();
    const { isFirstInput, isHighSpeed, isNormalInput, timeSinceLastInput } = inputInfo;
    
    // 如果是第一次输入，不拦截，让默认行为处理，只记录时间戳
    if (isFirstInput) {
      lastInputTime = Date.now();
      // 不拦截，让字符正常输入到 textarea
      return;
    }
    
    // 如果检测到是正常输入（间隔 > 200ms），处理之前的缓冲内容
    if (isNormalInput) {
      // 如果之前有当前标签或缓冲内容，先保存到标签数组（去重）
      if (currentRfidTag.value.trim()) {
        const tag = currentRfidTag.value.trim();
        if (!rfidTagArray.value.includes(tag) && !processingTags.value.has(tag)) {
          rfidTagArray.value.push(tag);
        }
        currentRfidTag.value = '';
      }
      if (rfidInputBuffer.value.trim()) {
        const tag = rfidInputBuffer.value.trim();
        if (!rfidTagArray.value.includes(tag) && !processingTags.value.has(tag)) {
          rfidTagArray.value.push(tag);
        }
        rfidInputBuffer.value = '';
      }
      // 如果有标签数组，处理它们
      if (rfidTagArray.value.length > 0) {
        processRfidTagArray();
      }
      // 重置状态
      consecutiveInputCount = 0;
      lastInputTime = Date.now();
      // 不拦截，让字符正常输入到 textarea
      return;
    }
    
    // 如果检测到是高速输入（间隔 < 30ms），使用缓冲模式
    if (isHighSpeed) {
      event.preventDefault();
      event.stopPropagation(); // 阻止事件冒泡，避免影响其他元素
      
      // 如果输入间隔超过标签分隔时间，说明是一个新标签的开始
      // 需要保存之前的标签到数组
      if (timeSinceLastInput > readRuleConfig.value.tagSeparatorTimeout) {
        // 保存当前标签到数组（如果存在且去重）
        if (currentRfidTag.value.trim()) {
          const tag = currentRfidTag.value.trim();
          if (!rfidTagArray.value.includes(tag)) {
            rfidTagArray.value.push(tag);
          }
          currentRfidTag.value = '';
        }
        // 保存缓冲内容到数组（如果存在且去重）
        if (rfidInputBuffer.value.trim()) {
          const tag = rfidInputBuffer.value.trim();
          if (!rfidTagArray.value.includes(tag)) {
            rfidTagArray.value.push(tag);
          }
          rfidInputBuffer.value = '';
        }
        // 如果 textarea 中有内容，检查是否需要添加到数组（去重）
        if (searchText.value.trim()) {
          const codes = splitDeviceCodes(searchText.value);
          codes.forEach(code => {
            const trimmedCode = code.trim();
            if (trimmedCode && !rfidTagArray.value.includes(trimmedCode) && !processingTags.value.has(trimmedCode)) {
              rfidTagArray.value.push(trimmedCode);
            }
          });
          searchText.value = ''; // 清空 searchText，避免重复处理
        }
        // 重置，开始新标签
        currentRfidTag.value = event.key;
        rfidInputBuffer.value = event.key;
        searchText.value = event.key;
      } else {
        // 如果是第一次检测到高速输入（之前没有缓冲内容），需要将 textarea 中已有的内容也加入当前标签
        if (currentRfidTag.value === '' && rfidInputBuffer.value === '' && searchText.value) {
          // textarea 中已经有内容（第一个字符已经通过默认行为输入了）
          // 将整个内容作为当前标签的初始值，然后追加当前字符
          currentRfidTag.value = searchText.value + event.key;
        } else {
          // 否则直接追加当前字符到当前标签
          currentRfidTag.value += event.key;
        }
        
        // 同时更新缓冲区和显示
        rfidInputBuffer.value = currentRfidTag.value;
        searchText.value = currentRfidTag.value;
      }
      
      consecutiveInputCount++;
      scheduleRFIDBufferSubmit();
      return;
    }
    
    // 如果输入间隔在 30-200ms 之间，可能是正常输入，不拦截
    // 但如果之前有缓冲内容，说明高速输入已结束，先保存当前标签（去重）
    if (currentRfidTag.value.trim() || rfidInputBuffer.value.trim()) {
      if (currentRfidTag.value.trim()) {
        const tag = currentRfidTag.value.trim();
        if (!rfidTagArray.value.includes(tag) && !processingTags.value.has(tag)) {
          rfidTagArray.value.push(tag);
        }
        currentRfidTag.value = '';
      }
      if (rfidInputBuffer.value.trim()) {
        const tag = rfidInputBuffer.value.trim();
        if (!rfidTagArray.value.includes(tag) && !processingTags.value.has(tag)) {
          rfidTagArray.value.push(tag);
        }
        rfidInputBuffer.value = '';
      }
      // 处理标签数组
      if (rfidTagArray.value.length > 0) {
        processRfidTagArray();
      }
      consecutiveInputCount = 0;
    }
    lastInputTime = Date.now();
    // 不拦截，让字符正常输入到 textarea
  }
};

// 处理输入框失焦
const handleDeviceBlur = (event: FocusEvent) => {
  // 如果焦点转移到其他输入元素（如表单输入框），不自动聚焦
  const relatedTarget = event.relatedTarget as HTMLElement;
  if (relatedTarget && (
    relatedTarget.tagName === 'INPUT' || 
    relatedTarget.tagName === 'TEXTAREA' ||
    relatedTarget.closest('.el-input') ||
    relatedTarget.closest('.el-textarea') ||
    relatedTarget.closest('form')
  )) {
    // 如果有缓冲内容，先提交
    if (rfidInputBuffer.value) {
      submitRFIDBuffer();
    }
    return;
  }
  
  // 其他情况（如点击按钮等），延迟后自动聚焦
  setTimeout(() => {
    if (searchInputRef.value && !loading.value) {
      searchInputRef.value.focus();
    }
  }, 10);
};

// 处理回车键
const handleDeviceEnter = (event: KeyboardEvent) => {
  if (event.shiftKey) return;
  event.preventDefault();
  
  // 如果启用了RFID缓冲，先检查是否有当前标签或缓冲内容
  if (readRuleConfig.value.enableRFIDBuffer) {
    // 如果有当前标签，先保存到标签数组（去重）
    if (currentRfidTag.value.trim()) {
      const tag = currentRfidTag.value.trim();
      if (!rfidTagArray.value.includes(tag) && !processingTags.value.has(tag)) {
        rfidTagArray.value.push(tag);
      }
      currentRfidTag.value = '';
    }
    // 如果有缓冲内容，也添加到标签数组（去重）
    if (rfidInputBuffer.value.trim()) {
      const tag = rfidInputBuffer.value.trim();
      if (!rfidTagArray.value.includes(tag) && !processingTags.value.has(tag)) {
        rfidTagArray.value.push(tag);
      }
      rfidInputBuffer.value = '';
    }
  }
  
  // 检查 searchText 中是否包含多个标签（通过换行、回车等分隔）
  if (searchText.value.trim()) {
    const codes = splitDeviceCodes(searchText.value);
    console.log(`[handleDeviceEnter] 回车键提交时，searchText 分割得到 ${codes.length} 个代码:`, codes, '原始内容长度:', searchText.value.length, '原始内容:', searchText.value.substring(0, 500));
    
    // 将所有标签添加到数组（包括单个标签的情况）
    codes.forEach(code => {
      const trimmedCode = code.trim();
      if (trimmedCode && !rfidTagArray.value.includes(trimmedCode) && !processingTags.value.has(trimmedCode)) {
        rfidTagArray.value.push(trimmedCode);
        console.log(`[handleDeviceEnter] 添加标签到数组: ${trimmedCode}`);
      }
    });
    searchText.value = '';
  }
  
  console.log(`[handleDeviceEnter] 回车键提交时，标签数组共有 ${rfidTagArray.value.length} 个标签:`, rfidTagArray.value);
  
  // 如果有标签数组，使用统一的延迟处理机制，避免多次触发
  if (rfidTagArray.value.length > 0) {
    clearRFIDInputTimer();
    consecutiveInputCount = 0;
    lastInputTime = 0;
    
    // 清除之前的延迟处理定时器（如果存在）
    if (processTagArrayTimer) {
      clearTimeout(processTagArrayTimer);
      processTagArrayTimer = null;
    }
    
    // 设置统一的延迟处理，确保所有标签都被收集后再处理
    processTagArrayTimer = setTimeout(() => {
      processTagArrayTimer = null;
      if (rfidTagArray.value.length > 0 && !isProcessingTagArray.value) {
        console.log(`[handleDeviceEnter] 延迟处理，最终标签数组:`, rfidTagArray.value);
        processRfidTagArray();
      }
    }, 300); // 增加延迟时间到300ms，确保所有标签都被收集
    return;
  }
  
  // 如果没有标签数组，使用 searchText 进行搜索
  if (searchText.value.trim()) {
    handleScanSearch();
  }
};

// 分割多个设备编号（支持分隔符）
const splitDeviceCodes = (input: string): string[] => {
  const trimmed = input.trim();
  if (!trimmed) return [];
  
  const { separator } = readRuleConfig.value;
  
  // 优先处理换行符
  if (/[\r\n]/.test(trimmed)) {
    return trimmed.split(/[\r\n]+/).filter(code => code.trim());
  }
  
  // 处理配置的分隔符
  if (separator && separator.trim() !== '') {
    const escapedSeparator = separator.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    const separatorPattern = new RegExp(escapedSeparator + '+', 'g');
    return trimmed.split(separatorPattern).filter(code => code.trim());
  }
  
  // 处理空格分隔
  if (/\s/.test(trimmed)) {
    return trimmed.split(/\s+/).filter(code => code.trim());
  }
  
  // 单个设备编号
  return [trimmed];
};

// 处理扫码搜索（支持批量，优化并发请求）
const handleScanSearch = async (event?: Event) => {
    // 阻止默认行为，防止表单提交导致页面刷新
    if (event) {
        event.preventDefault();
        event.stopPropagation();
    }
    
    // 如果启用了RFID缓冲，先提交缓冲区
    if (readRuleConfig.value.enableRFIDBuffer) {
      // 如果有当前标签，先保存到标签数组
      if (currentRfidTag.value.trim()) {
        if (!rfidTagArray.value.includes(currentRfidTag.value.trim())) {
          rfidTagArray.value.push(currentRfidTag.value.trim());
        }
        currentRfidTag.value = '';
      }
      // 如果有缓冲内容，也添加到标签数组
      if (rfidInputBuffer.value.trim()) {
        if (!rfidTagArray.value.includes(rfidInputBuffer.value.trim())) {
          rfidTagArray.value.push(rfidInputBuffer.value.trim());
        }
        rfidInputBuffer.value = '';
      }
      clearRFIDInputTimer();
      
      // 如果 searchText 中包含多个标签，先分割并添加到数组（去重）
      if (searchText.value.trim()) {
        const codes = splitDeviceCodes(searchText.value);
        codes.forEach(code => {
          const trimmedCode = code.trim();
          if (trimmedCode && !rfidTagArray.value.includes(trimmedCode) && !processingTags.value.has(trimmedCode)) {
            rfidTagArray.value.push(trimmedCode);
          }
        });
        searchText.value = '';
      }
      
      // 如果有标签数组，优先处理标签数组
      if (rfidTagArray.value.length > 0) {
        processRfidTagArray();
        return;
      }
    }
    
    if (!searchText.value.trim()) return;
    
    // 分割多个设备编号
    const codes = splitDeviceCodes(searchText.value);
    if (codes.length === 0) return;
    
    // 去重处理，避免重复请求同一个设备编号
    const uniqueCodes = Array.from(new Set(codes.map(code => code.trim()))).filter(Boolean);
    if (uniqueCodes.length === 0) return;
    
    loading.value = true;
    let successCount = 0;
    let failCount = 0;
    const errorMessages: string[] = [];
    
    try {
      // 批量并发处理设备编号（使用 Promise.allSettled 确保所有请求都完成）
      // 限制并发数量，避免同时发起过多请求
      const batchSize = 10; // 每批处理10个
      const batches: string[][] = [];
      for (let i = 0; i < uniqueCodes.length; i += batchSize) {
        batches.push(uniqueCodes.slice(i, i + batchSize));
      }
      
      // 用于收集所有成功获取的设备数据，避免并发添加时的竞态条件
      const deviceMap = new Map<number | string, any>();
      const processedCodes = new Set<string>();
      
      // 逐批处理，每批内部并发
      for (const batch of batches) {
        const promises = batch.map(async (code) => {
          try {
            const res = await deviceApi.GetList({ 
              page: 1, 
              limit: 1, 
              code: code,
              status: 1 
            });
            
            if (res.data && res.data.length > 0) {
              const device = res.data[0];
              const avail = getDeviceAvailableQuantityForBorrow(device);
              if (avail <= 0) {
                return { success: false, code, message: `设备 ${code} 可借用数量为0，无法加入领取列表` };
              }
              
              // 收集设备数据，统一处理添加逻辑
              deviceMap.set(device.id, {
                device_no: device.id,
                device_code: device.code,
                device_type: device.category_name,
                device_name: device.name || '',
                borrow_count: 1,
                brand: device.brand || device.device_brand || '',
                device_specification: device.specification,
                model: device.model || '',
                warehouse: device.warehouse,
                available_quantity: avail
              });
              processedCodes.add(code);
              return { success: true, code, deviceId: device.id };
            } else {
              return { success: false, code, message: `未找到设备编号: ${code}` };
            }
          } catch (error) {
            console.error(`处理设备编号 ${code} 失败:`, error);
            return { success: false, code, message: `处理设备编号 ${code} 失败` };
          }
        });
        
        // 等待当前批次完成
        const results = await Promise.allSettled(promises);
        
        // 统计结果（先不处理添加，只统计）
        results.forEach((result, index) => {
          const { success, message } = readSettledListStepResult(result, batch[index] ?? String(index));
          if (success) {
            /* 暂时不增加计数，等统一处理后再统计 */
          } else {
            failCount++;
            if (message) {
              errorMessages.push(message);
            }
          }
        });
      }
      
      // 统一处理设备添加，避免并发竞态条件
      deviceMap.forEach((deviceData, deviceId) => {
        // 再次检查是否已存在（防止在并发过程中被其他请求添加）
        const existingDevice = deviceList.value.find(d => d.device_no === deviceId);
        if (existingDevice) {
          // 如果已存在，增加借用数量
          existingDevice.borrow_count++;
          successCount++;
        } else {
          // 如果不存在，添加新设备
          deviceList.value.push(deviceData);
          successCount++;
        }
      });
      
      // 显示批量处理结果
      if (uniqueCodes.length > 1) {
        if (successCount > 0 && failCount === 0) {
          ElMessage.success(`成功添加 ${successCount} 个设备`);
        } else if (successCount > 0 && failCount > 0) {
          ElMessage.warning(`成功添加 ${successCount} 个设备，失败 ${failCount} 个`);
          // 只显示前3个错误信息，避免消息过多
          if (errorMessages.length > 0) {
            console.warn('批量处理错误详情:', errorMessages.slice(0, 3));
          }
        } else if (failCount > 0) {
          ElMessage.error(`添加失败，共 ${failCount} 个设备编号`);
        }
      } else if (successCount > 0) {
        ElMessage.success('设备已添加到列表');
      } else if (failCount > 0 && errorMessages.length > 0) {
        ElMessage.warning(errorMessages[0]);
      }
    } catch (error) {
        console.error('批量处理设备失败:', error);
        ElMessage.error('搜索设备失败');
    } finally {
        searchText.value = ''; // 清空搜索框
        loading.value = false;
        // 重新聚焦输入框，保持选中状态
        nextTick(() => {
            if (searchInputRef.value) {
              searchInputRef.value.focus();
              searchInputRef.value.select();
            }
        });
    }
};

// 处理归还流程RFID标签数组，逐个检索并提交
const processReturnRfidTagArray = async () => {
  if (returnRfidTagArray.value.length === 0 || isProcessingReturnTagArray.value) return;
  
  isProcessingReturnTagArray.value = true;
  
  // 使用 try-finally 确保状态总是被重置
  try {
    // 复制标签数组并清空，避免在处理过程中被修改
    const tagsToProcess = [...returnRfidTagArray.value];
    returnRfidTagArray.value = [];
    
    console.log(`[processReturnRfidTagArray] 开始处理归还标签，收到 ${tagsToProcess.length} 个标签:`, tagsToProcess);
    
    // 去重处理：过滤掉正在处理或已处理的标签
    // 注意：不要在这里就添加到 returnProcessingTags，而是在实际开始处理时才添加
    const uniqueTagsToProcess = tagsToProcess.filter(tag => {
      const trimmedTag = tag.trim();
      if (!trimmedTag) return false;
      // 只跳过正在处理的标签，不在这里添加
      const shouldProcess = !returnProcessingTags.value.has(trimmedTag);
      if (!shouldProcess) {
        console.log(`[processReturnRfidTagArray] 归还标签 ${trimmedTag} 正在处理中，跳过`);
      }
      return shouldProcess;
    });
    
    console.log(`[processReturnRfidTagArray] 去重后需要处理 ${uniqueTagsToProcess.length} 个标签:`, uniqueTagsToProcess);
    
    // 逐个处理标签
    for (let i = 0; i < uniqueTagsToProcess.length; i++) {
    const tag = uniqueTagsToProcess[i];
    if (!tag || !tag.trim()) {
      console.log(`[processReturnRfidTagArray] 跳过空标签: ${tag}`);
      continue;
    }
    
    const trimmedTag = tag.trim();
    
    // 在处理前检查并添加到 returnProcessingTags，防止重复处理
    if (returnProcessingTags.value.has(trimmedTag)) {
      console.log(`[processReturnRfidTagArray] 归还标签 ${trimmedTag} 正在处理中，跳过`);
      continue;
    }
    returnProcessingTags.value.add(trimmedTag);
    
    console.log(`[processReturnRfidTagArray] 开始处理归还标签 ${i + 1}/${uniqueTagsToProcess.length}: ${trimmedTag}`);
    
    // 确保每个标签处理前状态都是干净的
    returnSearchText.value = '';
    loading.value = false;
    
    try {
      // 设置搜索文本
      returnSearchText.value = trimmedTag;
      
      // 分割多个设备编号
      const codes = splitDeviceCodes(returnSearchText.value);
      console.log(`[processReturnRfidTagArray] 归还标签 ${trimmedTag} 分割后得到 ${codes.length} 个代码:`, codes);
      
      if (codes.length === 0) {
        // 如果分割后没有有效代码，从 returnProcessingTags 中移除并继续处理下一个标签
        returnProcessingTags.value.delete(trimmedTag);
        console.log(`[processReturnRfidTagArray] 归还标签 ${trimmedTag} 分割后没有有效代码，跳过`);
        continue;
      }
      
      const uniqueCodes = Array.from(new Set(codes.map(code => code.trim()))).filter(Boolean);
      console.log(`[processReturnRfidTagArray] 归还标签 ${trimmedTag} 去重后得到 ${uniqueCodes.length} 个唯一代码:`, uniqueCodes);
      
      if (uniqueCodes.length === 0) {
        // 如果没有有效代码，从 returnProcessingTags 中移除并继续处理下一个标签
        returnProcessingTags.value.delete(trimmedTag);
        console.log(`[processReturnRfidTagArray] 归还标签 ${trimmedTag} 没有有效代码，跳过`);
        continue;
      }
      
      loading.value = true;
      let successCount = 0;
      let failCount = 0;
      const errorMessages: string[] = [];
      
      // 批量并发处理设备编号（使用 Promise.allSettled 确保所有请求都完成）
      const batchSize = 10;
      const batches: string[][] = [];
      for (let j = 0; j < uniqueCodes.length; j += batchSize) {
        batches.push(uniqueCodes.slice(j, j + batchSize));
      }
      
      // 逐批处理，每批内部并发
      for (const batch of batches) {
        try {
          const promises = batch.map(async (code) => {
            try {
              const res = await deviceApi.GetList({ 
                page: 1, 
                limit: 1, 
                code: code,
                status: 1 
              });
              
              if (res.data && res.data.length > 0) {
                const device = res.data[0];
                // 检查是否已存在
                const existingDeviceIndex = returnDeviceList.value.findIndex(d => d.device_no === device.id);
                if (existingDeviceIndex !== -1) {
                  const row = returnDeviceList.value[existingDeviceIndex];
                  const errMsg = tryApplyReturnScanIncrement(row);
                  if (errMsg) {
                    return { success: false, code, message: errMsg };
                  }
                  return { success: true, code };
                } else {
                  // 设备不存在于归还列表中
                  return { 
                    success: false, 
                    code, 
                    message: `设备 ${device.code || device.category_name} 不在当前归还列表中，请先通过手动归还添加该设备` 
                  };
                }
              } else {
                return { success: false, code, message: `未找到设备编号: ${code}` };
              }
            } catch (error) {
              console.error(`处理设备编号 ${code} 失败:`, error);
              return { success: false, code, message: `处理设备编号 ${code} 失败` };
            }
          });
          
          // 等待当前批次完成
          const results = await Promise.allSettled(promises);
          
          // 统计结果
          results.forEach((result, index) => {
            const { success, message } = readSettledListStepResult(result, batch[index] ?? String(index));
            if (success) {
              successCount++;
            } else {
              failCount++;
              if (message) {
                errorMessages.push(message);
              }
            }
          });
        } catch (batchError) {
          // 即使某批处理失败，也继续处理下一批
          console.error(`处理批次失败:`, batchError);
          failCount += batch.length;
          errorMessages.push(
            `处理批次时发生错误${
              batchError instanceof Error ? `：${batchError.message}` : ''
            }`
          );
        }
      }
      
      // 显示处理结果
      console.log(`[processReturnRfidTagArray] 归还标签 ${trimmedTag} 处理完成: 成功 ${successCount} 个，失败 ${failCount} 个`);
      
      if (uniqueCodes.length > 1) {
        if (successCount > 0 && failCount === 0) {
          ElMessage.success(`标签 ${trimmedTag}: 成功增加 ${successCount} 个设备的归还数量`);
        } else if (successCount > 0 && failCount > 0) {
          ElMessage.warning(`标签 ${trimmedTag}: 成功增加 ${successCount} 个设备的归还数量，失败 ${failCount} 个`);
          if (errorMessages.length > 0) {
            console.warn('[processReturnRfidTagArray] 批量处理错误详情:', errorMessages.slice(0, 3));
          }
        } else if (failCount > 0) {
          ElMessage.error(`标签 ${trimmedTag}: 处理失败，共 ${failCount} 个设备编号`);
        }
      } else if (successCount > 0) {
        ElMessage.success(`标签 ${trimmedTag}: 已增加 1 个归还数量`);
      } else if (failCount > 0 && errorMessages.length > 0) {
        ElMessage.warning(`标签 ${trimmedTag}: ${errorMessages[0]}`);
      }
      
      // 处理成功后，从 returnProcessingTags 中移除，允许后续再次处理（如果需要）
      // 但保留一段时间，防止立即重复处理
      setTimeout(() => {
        returnProcessingTags.value.delete(trimmedTag);
      }, 5000);
      
      console.log(`[processReturnRfidTagArray] 归还标签 ${trimmedTag} 处理完成，继续处理下一个标签`);
      
      // 每个标签处理完后稍作延迟，避免请求过快
      if (uniqueTagsToProcess.length > 1 && i < uniqueTagsToProcess.length - 1) {
        await new Promise(resolve => setTimeout(resolve, 100));
      }
    } catch (error) {
      // 即使某个标签处理失败，也要继续处理其他标签
      console.error(`[processReturnRfidTagArray] 处理归还标签 ${trimmedTag} 失败:`, error);
      const errorMsg = error instanceof Error ? error.message : String(error);
      ElMessage.error(`处理标签 ${trimmedTag} 失败: ${errorMsg}`);
      // 从 returnProcessingTags 中移除失败的标签，允许后续重试
      returnProcessingTags.value.delete(trimmedTag);
      console.log(`[processReturnRfidTagArray] 归还标签 ${trimmedTag} 处理失败，继续处理下一个标签`);
      // 确保即使出错也继续处理下一个标签
    } finally {
      // 确保每个标签处理完后都重置状态，无论成功还是失败
      try {
        returnSearchText.value = '';
        loading.value = false;
        console.log(`[processReturnRfidTagArray] 归还标签 ${trimmedTag} 状态已重置，准备处理下一个标签`);
      } catch (stateError) {
        console.error(`[processReturnRfidTagArray] 重置状态失败:`, stateError);
      }
    }
  }
  
  // 所有标签处理完成后，清理处理标志并重新聚焦输入框
  console.log(`[processReturnRfidTagArray] 所有归还标签处理完成，共处理 ${uniqueTagsToProcess.length} 个标签，标签列表:`, uniqueTagsToProcess);
  console.log(`[processReturnRfidTagArray] 当前归还设备列表中的设备数量:`, returnDeviceList.value.length);
  
  } catch (outerError) {
    // 捕获整个处理过程中的任何未预期错误，确保状态被重置
    console.error(`[processReturnRfidTagArray] 处理过程中发生未预期错误:`, outerError);
    ElMessage.error('处理归还标签时发生错误，但已尝试处理所有标签');
  } finally {
    // 确保无论发生什么，状态都被重置
    isProcessingReturnTagArray.value = false;
    loading.value = false;
    returnSearchText.value = '';
    
    // 清理处理中的标签标记（延迟清理，避免立即重复处理）
    setTimeout(() => {
      returnProcessingTags.value.clear();
    }, 1000);
  }
  
  nextTick(() => {
    if (returnSearchInputRef.value) {
      returnSearchInputRef.value.focus();
      returnSearchInputRef.value.select();
    }
  });
};

// 提交归还流程RFID缓冲区内容
const submitReturnRFIDBuffer = () => {
  if (!readRuleConfig.value.enableRFIDBuffer) {
    // 如果未启用RFID缓冲，直接使用 returnSearchText 进行搜索
    if (returnSearchText.value.trim()) {
      handleReturnScanSearch();
    }
    return;
  }
  
  // 如果有标签数组，优先处理标签数组
  if (returnRfidTagArray.value.length > 0) {
    clearReturnRFIDInputTimer();
    returnConsecutiveInputCount = 0;
    returnLastInputTime = 0;
    processReturnRfidTagArray();
    return;
  }
  
  if (!returnRfidInputBuffer.value && !returnCurrentRfidTag.value) {
    // 如果没有缓冲内容，使用 returnSearchText 进行搜索
    if (returnSearchText.value.trim()) {
      handleReturnScanSearch();
    }
    return;
  }
  
  // 如果有当前标签，先添加到标签数组（去重）
  if (returnCurrentRfidTag.value.trim()) {
    const tag = returnCurrentRfidTag.value.trim();
    if (!returnRfidTagArray.value.includes(tag) && !returnProcessingTags.value.has(tag)) {
      returnRfidTagArray.value.push(tag);
    }
    returnCurrentRfidTag.value = '';
  }
  
  // 如果有缓冲内容，也添加到标签数组（去重）
  if (returnRfidInputBuffer.value.trim()) {
    const tag = returnRfidInputBuffer.value.trim();
    if (!returnRfidTagArray.value.includes(tag) && !returnProcessingTags.value.has(tag)) {
      returnRfidTagArray.value.push(tag);
    }
    returnRfidInputBuffer.value = '';
  }
  
  clearReturnRFIDInputTimer();
  returnConsecutiveInputCount = 0;
  returnLastInputTime = 0;
  
  // 处理标签数组
  if (returnRfidTagArray.value.length > 0) {
    processReturnRfidTagArray();
  }
};

// 调度归还流程RFID缓冲区提交（延迟提交）
const scheduleReturnRFIDBufferSubmit = () => {
  if (!readRuleConfig.value.enableRFIDBuffer) return;
  clearReturnRFIDInputTimer();
  const delay = Math.max(readRuleConfig.value.rfidInputTimeout || 120, 30);
  returnRfidInputTimer = setTimeout(() => {
    console.log(`[scheduleReturnRFIDBufferSubmit] 延迟提交触发，当前状态:`, {
      returnCurrentRfidTag: returnCurrentRfidTag.value,
      returnRfidInputBuffer: returnRfidInputBuffer.value,
      returnSearchText: returnSearchText.value,
      returnRfidTagArray: returnRfidTagArray.value
    });
    
    // 如果 returnSearchText 中有内容，优先检查是否包含多个标签（通过换行、回车等分隔）
    if (returnSearchText.value.trim()) {
      const codes = splitDeviceCodes(returnSearchText.value);
      console.log(`[scheduleReturnRFIDBufferSubmit] returnSearchText 分割得到 ${codes.length} 个代码:`, codes, '原始内容长度:', returnSearchText.value.length);
      
      // 无论有多少个标签，都添加到标签数组
      if (codes.length > 0) {
        codes.forEach(code => {
          const trimmedCode = code.trim();
          if (trimmedCode && !returnRfidTagArray.value.includes(trimmedCode) && !returnProcessingTags.value.has(trimmedCode)) {
            returnRfidTagArray.value.push(trimmedCode);
            console.log(`[scheduleReturnRFIDBufferSubmit] 添加标签到数组: ${trimmedCode}`);
          }
        });
        returnSearchText.value = '';
      }
    }
    
    // 如果当前标签有内容，先保存到标签数组（去重）
    if (returnCurrentRfidTag.value.trim()) {
      const tag = returnCurrentRfidTag.value.trim();
      if (!returnRfidTagArray.value.includes(tag) && !returnProcessingTags.value.has(tag)) {
        returnRfidTagArray.value.push(tag);
        console.log(`[scheduleReturnRFIDBufferSubmit] 添加当前标签到数组: ${tag}`);
      }
      returnCurrentRfidTag.value = '';
    }
    // 如果有缓冲内容，也添加到标签数组（去重）
    if (returnRfidInputBuffer.value.trim()) {
      const tag = returnRfidInputBuffer.value.trim();
      if (!returnRfidTagArray.value.includes(tag) && !returnProcessingTags.value.has(tag)) {
        returnRfidTagArray.value.push(tag);
        console.log(`[scheduleReturnRFIDBufferSubmit] 添加缓冲标签到数组: ${tag}`);
      }
      returnRfidInputBuffer.value = '';
    }
    
    console.log(`[scheduleReturnRFIDBufferSubmit] 延迟提交时，标签数组共有 ${returnRfidTagArray.value.length} 个标签:`, returnRfidTagArray.value);
    
    // 处理标签数组，使用统一的延迟处理机制
    if (returnRfidTagArray.value.length > 0) {
      // 清除之前的延迟处理定时器（如果存在）
      clearReturnProcessTagArrayTimer();
      
      // 设置统一的延迟处理，确保所有标签都被收集后再处理
      returnProcessTagArrayTimer = setTimeout(() => {
        returnProcessTagArrayTimer = null;
        if (returnRfidTagArray.value.length > 0 && !isProcessingReturnTagArray.value) {
          console.log(`[scheduleReturnRFIDBufferSubmit] 延迟处理，最终标签数组:`, returnRfidTagArray.value);
          processReturnRfidTagArray();
        }
      }, 300); // 增加延迟时间到300ms，确保所有标签都被收集
    }
  }, delay);
};

// 处理归还设备输入（用于同步 textarea 内容，仅在缓冲模式下使用）
const handleReturnDeviceInput = () => {
  // 如果启用了RFID缓冲，检查 returnSearchText 中是否包含多个标签（通过换行、回车等分隔）
  if (readRuleConfig.value.enableRFIDBuffer && returnSearchText.value.trim()) {
    // 检查是否包含换行符或回车符
    if (/[\r\n]/.test(returnSearchText.value)) {
      // 如果包含换行符，说明可能有多个标签
      const codes = splitDeviceCodes(returnSearchText.value);
      console.log(`[handleReturnDeviceInput] 检测到换行符，分割得到 ${codes.length} 个代码:`, codes, '原始内容长度:', returnSearchText.value.length, '原始内容:', returnSearchText.value.substring(0, 200));
      
      // 无论有多少个标签，都添加到标签数组（包括单个标签的情况）
      if (codes.length > 0) {
        codes.forEach(code => {
          const trimmedCode = code.trim();
          if (trimmedCode && !returnRfidTagArray.value.includes(trimmedCode) && !returnProcessingTags.value.has(trimmedCode)) {
            returnRfidTagArray.value.push(trimmedCode);
            console.log(`[handleReturnDeviceInput] 添加标签到数组: ${trimmedCode}`);
          }
        });
        console.log(`[handleReturnDeviceInput] 标签数组共有 ${returnRfidTagArray.value.length} 个标签:`, returnRfidTagArray.value);
        // 清空 returnSearchText，避免重复处理
        returnSearchText.value = '';
        // 清空当前标签和缓冲区，因为已经添加到数组了
        returnCurrentRfidTag.value = '';
        returnRfidInputBuffer.value = '';
        // 如果有标签数组且当前没有在处理，使用统一的延迟处理机制
        if (returnRfidTagArray.value.length > 0 && !isProcessingReturnTagArray.value) {
          clearReturnRFIDInputTimer();
          
          // 清除之前的延迟处理定时器（如果存在）
          clearReturnProcessTagArrayTimer();
          
          // 设置统一的延迟处理，确保所有标签都被收集后再处理
          returnProcessTagArrayTimer = setTimeout(() => {
            returnProcessTagArrayTimer = null;
            if (returnRfidTagArray.value.length > 0 && !isProcessingReturnTagArray.value) {
              console.log(`[handleReturnDeviceInput] 延迟处理，最终标签数组:`, returnRfidTagArray.value);
              processReturnRfidTagArray();
            }
          }, 300); // 增加延迟时间到300ms，确保所有标签都被收集
        }
        return;
      }
    }
  }
  
  // 如果缓冲区有内容，确保 textarea 显示与缓冲区一致
  // 这主要用于处理退格键等操作后的同步
  if (returnCurrentRfidTag.value || returnRfidInputBuffer.value) {
    const displayValue = returnCurrentRfidTag.value || returnRfidInputBuffer.value;
    if (returnSearchText.value !== displayValue) {
      returnSearchText.value = displayValue;
    }
  }
  // 注意：正常输入时，不干预 textarea 的内容，让默认行为处理
};

// 检测归还流程是否是高速扫码输入（通过输入速度判断）
// 返回值：{ isHighSpeed: boolean, isFirstInput: boolean, timeSinceLastInput: number }
const checkReturnInputSpeed = () => {
  const now = Date.now();
  const timeSinceLastInput = returnLastInputTime > 0 ? now - returnLastInputTime : 0;
  const isFirstInput = returnLastInputTime === 0;
  
  if (!isFirstInput) {
    returnLastInputTime = now;
  }
  
  return {
    isFirstInput,
    timeSinceLastInput,
    isHighSpeed: timeSinceLastInput > 0 && timeSinceLastInput < readRuleConfig.value.minInputSpeed,
    isNormalInput: timeSinceLastInput > 200
  };
};

// 处理归还流程RFID键盘输入（高速扫码）
const handleReturnRFIDKeydown = (event: KeyboardEvent) => {
  // 如果未启用RFID缓冲，直接返回，不拦截
  if (!readRuleConfig.value.enableRFIDBuffer) {
    return;
  }
  
  // 不拦截修饰键组合（如 Ctrl+C, Ctrl+V 等）
  if (event.ctrlKey || event.metaKey || event.altKey) {
    return;
  }
  
  // 处理回车键
  if (event.key === 'Enter') {
    // 回车键由 @keydown.enter.prevent="handleReturnDeviceEnter" 处理
    // 这里不处理，让 handleReturnDeviceEnter 统一处理
    return;
  }
  
  // 处理退格键
  if (event.key === 'Backspace') {
    // 如果有当前标签或缓冲内容，处理缓冲
    if (returnCurrentRfidTag.value || returnRfidInputBuffer.value) {
      event.preventDefault();
      if (returnCurrentRfidTag.value) {
        returnCurrentRfidTag.value = returnCurrentRfidTag.value.slice(0, -1);
        returnRfidInputBuffer.value = returnCurrentRfidTag.value;
      } else {
        returnRfidInputBuffer.value = returnRfidInputBuffer.value.slice(0, -1);
      }
      returnSearchText.value = returnRfidInputBuffer.value || returnCurrentRfidTag.value;
    }
    // 否则让默认行为处理
    return;
  }
  
  // 处理普通字符输入
  if (event.key.length === 1) {
    const inputInfo = checkReturnInputSpeed();
    const { isFirstInput, isHighSpeed, isNormalInput, timeSinceLastInput } = inputInfo;
    
    // 如果是第一次输入，不拦截，让默认行为处理，只记录时间戳
    if (isFirstInput) {
      returnLastInputTime = Date.now();
      // 不拦截，让字符正常输入到 textarea
      return;
    }
    
    // 如果检测到是正常输入（间隔 > 200ms），处理之前的缓冲内容
    if (isNormalInput) {
      // 如果之前有当前标签或缓冲内容，先保存到标签数组（去重）
      if (returnCurrentRfidTag.value.trim()) {
        const tag = returnCurrentRfidTag.value.trim();
        if (!returnRfidTagArray.value.includes(tag) && !returnProcessingTags.value.has(tag)) {
          returnRfidTagArray.value.push(tag);
        }
        returnCurrentRfidTag.value = '';
      }
      if (returnRfidInputBuffer.value.trim()) {
        const tag = returnRfidInputBuffer.value.trim();
        if (!returnRfidTagArray.value.includes(tag) && !returnProcessingTags.value.has(tag)) {
          returnRfidTagArray.value.push(tag);
        }
        returnRfidInputBuffer.value = '';
      }
      // 如果有标签数组，处理它们
      if (returnRfidTagArray.value.length > 0) {
        processReturnRfidTagArray();
      }
      // 重置状态
      returnConsecutiveInputCount = 0;
      returnLastInputTime = Date.now();
      // 不拦截，让字符正常输入到 textarea
      return;
    }
    
    // 如果检测到是高速输入（间隔 < 30ms），使用缓冲模式
    if (isHighSpeed) {
      event.preventDefault();
      event.stopPropagation(); // 阻止事件冒泡，避免影响其他元素
      
      // 如果输入间隔超过标签分隔时间，说明是一个新标签的开始
      // 需要保存之前的标签到数组
      if (timeSinceLastInput > readRuleConfig.value.tagSeparatorTimeout) {
        // 保存当前标签到数组（如果存在且去重）
        if (returnCurrentRfidTag.value.trim()) {
          const tag = returnCurrentRfidTag.value.trim();
          if (!returnRfidTagArray.value.includes(tag) && !returnProcessingTags.value.has(tag)) {
            returnRfidTagArray.value.push(tag);
          }
          returnCurrentRfidTag.value = '';
        }
        // 保存缓冲内容到数组（如果存在且去重）
        if (returnRfidInputBuffer.value.trim()) {
          const tag = returnRfidInputBuffer.value.trim();
          if (!returnRfidTagArray.value.includes(tag) && !returnProcessingTags.value.has(tag)) {
            returnRfidTagArray.value.push(tag);
          }
          returnRfidInputBuffer.value = '';
        }
        // 如果 textarea 中有内容，检查是否需要添加到数组（去重）
        if (returnSearchText.value.trim()) {
          const codes = splitDeviceCodes(returnSearchText.value);
          codes.forEach(code => {
            const trimmedCode = code.trim();
            if (trimmedCode && !returnRfidTagArray.value.includes(trimmedCode) && !returnProcessingTags.value.has(trimmedCode)) {
              returnRfidTagArray.value.push(trimmedCode);
            }
          });
          returnSearchText.value = ''; // 清空 searchText，避免重复处理
        }
        // 重置，开始新标签
        returnCurrentRfidTag.value = event.key;
        returnRfidInputBuffer.value = event.key;
        returnSearchText.value = event.key;
      } else {
        // 如果是第一次检测到高速输入（之前没有缓冲内容），需要将 textarea 中已有的内容也加入当前标签
        if (returnCurrentRfidTag.value === '' && returnRfidInputBuffer.value === '' && returnSearchText.value) {
          // textarea 中已经有内容（第一个字符已经通过默认行为输入了）
          // 将整个内容作为当前标签的初始值，然后追加当前字符
          returnCurrentRfidTag.value = returnSearchText.value + event.key;
        } else {
          // 否则直接追加当前字符到当前标签
          returnCurrentRfidTag.value += event.key;
        }
        
        // 同时更新缓冲区和显示
        returnRfidInputBuffer.value = returnCurrentRfidTag.value;
        returnSearchText.value = returnCurrentRfidTag.value;
      }
      
      returnConsecutiveInputCount++;
      scheduleReturnRFIDBufferSubmit();
      return;
    }
    
    // 如果输入间隔在 30-200ms 之间，可能是正常输入，不拦截
    // 但如果之前有缓冲内容，说明高速输入已结束，先保存当前标签（去重）
    if (returnCurrentRfidTag.value.trim() || returnRfidInputBuffer.value.trim()) {
      if (returnCurrentRfidTag.value.trim()) {
        const tag = returnCurrentRfidTag.value.trim();
        if (!returnRfidTagArray.value.includes(tag) && !returnProcessingTags.value.has(tag)) {
          returnRfidTagArray.value.push(tag);
        }
        returnCurrentRfidTag.value = '';
      }
      if (returnRfidInputBuffer.value.trim()) {
        const tag = returnRfidInputBuffer.value.trim();
        if (!returnRfidTagArray.value.includes(tag) && !returnProcessingTags.value.has(tag)) {
          returnRfidTagArray.value.push(tag);
        }
        returnRfidInputBuffer.value = '';
      }
      // 处理标签数组
      if (returnRfidTagArray.value.length > 0) {
        processReturnRfidTagArray();
      }
      returnConsecutiveInputCount = 0;
    }
    returnLastInputTime = Date.now();
    // 不拦截，让字符正常输入到 textarea
  }
};

// 处理归还输入框失焦
const handleReturnDeviceBlur = (event: FocusEvent) => {
  // 如果焦点转移到其他输入元素（如表单输入框），不自动聚焦
  const relatedTarget = event.relatedTarget as HTMLElement;
  if (relatedTarget && (
    relatedTarget.tagName === 'INPUT' || 
    relatedTarget.tagName === 'TEXTAREA' ||
    relatedTarget.closest('.el-input') ||
    relatedTarget.closest('.el-textarea') ||
    relatedTarget.closest('form')
  )) {
    // 如果有缓冲内容，先提交
    if (returnRfidInputBuffer.value) {
      submitReturnRFIDBuffer();
    }
    return;
  }
  
  // 其他情况（如点击按钮等），延迟后自动聚焦
  setTimeout(() => {
    if (returnSearchInputRef.value && !loading.value) {
      returnSearchInputRef.value.focus();
    }
  }, 10);
};

// 处理归还回车键
const handleReturnDeviceEnter = (event: KeyboardEvent) => {
  if (event.shiftKey) return;
  event.preventDefault();
  
  // 如果启用了RFID缓冲，先检查是否有当前标签或缓冲内容
  if (readRuleConfig.value.enableRFIDBuffer) {
    // 如果有当前标签，先保存到标签数组（去重）
    if (returnCurrentRfidTag.value.trim()) {
      const tag = returnCurrentRfidTag.value.trim();
      if (!returnRfidTagArray.value.includes(tag) && !returnProcessingTags.value.has(tag)) {
        returnRfidTagArray.value.push(tag);
      }
      returnCurrentRfidTag.value = '';
    }
    // 如果有缓冲内容，也添加到标签数组（去重）
    if (returnRfidInputBuffer.value.trim()) {
      const tag = returnRfidInputBuffer.value.trim();
      if (!returnRfidTagArray.value.includes(tag) && !returnProcessingTags.value.has(tag)) {
        returnRfidTagArray.value.push(tag);
      }
      returnRfidInputBuffer.value = '';
    }
  }
  
  // 检查 returnSearchText 中是否包含多个标签（通过换行、回车等分隔）
  if (returnSearchText.value.trim()) {
    const codes = splitDeviceCodes(returnSearchText.value);
    console.log(`[handleReturnDeviceEnter] 回车键提交时，returnSearchText 分割得到 ${codes.length} 个代码:`, codes, '原始内容长度:', returnSearchText.value.length, '原始内容:', returnSearchText.value.substring(0, 500));
    
    // 将所有标签添加到数组（包括单个标签的情况）
    codes.forEach(code => {
      const trimmedCode = code.trim();
      if (trimmedCode && !returnRfidTagArray.value.includes(trimmedCode) && !returnProcessingTags.value.has(trimmedCode)) {
        returnRfidTagArray.value.push(trimmedCode);
        console.log(`[handleReturnDeviceEnter] 添加标签到数组: ${trimmedCode}`);
      }
    });
    returnSearchText.value = '';
  }
  
  console.log(`[handleReturnDeviceEnter] 回车键提交时，标签数组共有 ${returnRfidTagArray.value.length} 个标签:`, returnRfidTagArray.value);
  
  // 如果有标签数组，使用统一的延迟处理机制，避免多次触发
  if (returnRfidTagArray.value.length > 0) {
    clearReturnRFIDInputTimer();
    returnConsecutiveInputCount = 0;
    returnLastInputTime = 0;
    
    // 清除之前的延迟处理定时器（如果存在）
    clearReturnProcessTagArrayTimer();
    
    // 设置统一的延迟处理，确保所有标签都被收集后再处理
    returnProcessTagArrayTimer = setTimeout(() => {
      returnProcessTagArrayTimer = null;
      if (returnRfidTagArray.value.length > 0 && !isProcessingReturnTagArray.value) {
        console.log(`[handleReturnDeviceEnter] 延迟处理，最终标签数组:`, returnRfidTagArray.value);
        processReturnRfidTagArray();
      }
    }, 300); // 增加延迟时间到300ms，确保所有标签都被收集
    return;
  }
  
  // 如果没有标签数组，使用 returnSearchText 进行搜索
  if (returnSearchText.value.trim()) {
    handleReturnScanSearch();
  }
};

// 处理归还扫码搜索（支持批量，优化并发请求）
const handleReturnScanSearch = async (event?: Event) => {
    // 阻止默认行为，防止表单提交导致页面刷新
    if (event) {
        event.preventDefault();
        event.stopPropagation();
    }
    
    // 如果启用了RFID缓冲，先提交缓冲区
    if (readRuleConfig.value.enableRFIDBuffer && returnRfidInputBuffer.value) {
      const bufferedValue = returnRfidInputBuffer.value;
      returnRfidInputBuffer.value = '';
      clearReturnRFIDInputTimer();
      returnSearchText.value = bufferedValue;
    }
    
    if (!returnSearchText.value.trim()) return;
    
    // 分割多个设备编号
    const codes = splitDeviceCodes(returnSearchText.value);
    if (codes.length === 0) return;
    
    // 去重处理，避免重复请求同一个设备编号
    const uniqueCodes = Array.from(new Set(codes.map(code => code.trim()))).filter(Boolean);
    if (uniqueCodes.length === 0) return;
    
    loading.value = true;
    let successCount = 0;
    let failCount = 0;
    const errorMessages: string[] = [];
    
    try {
      // 批量并发处理设备编号（使用 Promise.allSettled 确保所有请求都完成）
      // 限制并发数量，避免同时发起过多请求
      const batchSize = 10; // 每批处理10个
      const batches: string[][] = [];
      for (let i = 0; i < uniqueCodes.length; i += batchSize) {
        batches.push(uniqueCodes.slice(i, i + batchSize));
      }
      
      // 逐批处理，每批内部并发
      for (const batch of batches) {
        const promises = batch.map(async (code) => {
    try {
        const res = await deviceApi.GetList({ 
            page: 1, 
            limit: 1, 
              code: code,
            status: 1 
        });
        
        if (res.data && res.data.length > 0) {
            const device = res.data[0];
            const existingDeviceIndex = returnDeviceList.value.findIndex(d => d.device_no === device.id);
            if (existingDeviceIndex !== -1) {
                const row = returnDeviceList.value[existingDeviceIndex];
                const errMsg = tryApplyReturnScanIncrement(row);
                if (errMsg) {
                  return { success: false, code, message: errMsg };
                }
                return { success: true, code };
            } else {
                // 设备不存在于归还列表中
                return { 
                  success: false, 
                  code, 
                  message: `设备 ${device.code || device.category_name} 不在当前归还列表中，请先通过手动归还添加该设备` 
                };
            }
        } else {
              return { success: false, code, message: `未找到设备编号: ${code}` };
        }
    } catch (error) {
            console.error(`处理设备编号 ${code} 失败:`, error);
            return { success: false, code, message: `处理设备编号 ${code} 失败` };
          }
        });
        
        // 等待当前批次完成
        const results = await Promise.allSettled(promises);
        
        // 统计结果
        results.forEach((result, index) => {
          const { success, message } = readSettledListStepResult(result, batch[index] ?? String(index));
          if (success) {
            successCount++;
          } else {
            failCount++;
            if (message) {
              errorMessages.push(message);
            }
          }
        });
      }
      
      // 显示批量处理结果
      if (uniqueCodes.length > 1) {
        if (successCount > 0 && failCount === 0) {
          ElMessage.success(`成功增加 ${successCount} 个设备的归还数量`);
        } else if (successCount > 0 && failCount > 0) {
          ElMessage.warning(`成功增加 ${successCount} 个设备的归还数量，失败 ${failCount} 个`);
          // 只显示前3个错误信息，避免消息过多
          if (errorMessages.length > 0) {
            console.warn('批量处理错误详情:', errorMessages.slice(0, 3));
          }
        } else if (failCount > 0) {
          ElMessage.error(`处理失败，共 ${failCount} 个设备编号`);
        }
      } else if (successCount > 0) {
        ElMessage.success('已增加 1 个归还数量');
      } else if (failCount > 0 && errorMessages.length > 0) {
        ElMessage.warning(errorMessages[0]);
      }
    } catch (error) {
        console.error('批量处理设备失败:', error);
        ElMessage.error('搜索设备失败');
    } finally {
        returnSearchText.value = ''; // 清空搜索框
        loading.value = false;
        // 重新聚焦输入框，保持选中状态
        nextTick(() => {
            if (returnSearchInputRef.value) {
              returnSearchInputRef.value.focus();
              returnSearchInputRef.value.select();
            }
        });
    }
};

// 异常记录列表数据
const abnormalList = ref([
    /* {
        borrowNo: '202409002',
        borrower: '张同学',
        time: '2024-09-12 10:21:32',
        type: '逾期'
    },
    {
        borrowNo: '202505013',
        borrower: '张同学',
        time: '2025-05-13 15:12:35',
        type: '损坏'
    } */
]);
/* 归还设备异常记录 */
const returnAbnormalList = ref([
    
]);

// 附件文件列表
const attachmentFileList = ref<any[]>([]);

// 查看异常记录详情
const handleView = (row: any) => {
    console.log('查看异常记录:', row);
    // 这里可以添加查看详情的逻辑
};

const selectedDeviceCodes = ref<any[]>([]);

// 计算已选中设备的ID列表（用于禁用已选中的设备）
const disabledDeviceIds = computed(() => {
	if (activeName.value === 'first') {
		// first tab: 从 form.value.items 中获取 device ID
		return form.value.items.map((item: any) => item.device).filter(Boolean);
	} else if (activeName.value === 'second') {
		// second tab: 从 deviceList.value 中获取 device_no ID
		return deviceList.value.map((item: any) => item.device_no).filter(Boolean);
	}
	// third tab (归还模式) 不需要禁用，因为已经有特殊的处理逻辑
	return [];
});

// 借用列表相关方法
const handleAdd = () => {
  if (activeName.value === 'third' && allReturned.value) {
    ElMessage.info('当前列表设备均已归还，无可选择设备');
    return;
  }
  if(activeName.value === 'third'){
    selectedDeviceCodes.value = [];
    returnDeviceList.value.forEach(item => {
      console.log("item:::",item);
      if(item.device_no){
        selectedDeviceCodes.value.push(item.device_code);
      }
    });
    console.log("selectedDeviceCodes.value:::",selectedDeviceCodes.value);
  }
  showSelectDeviceDialog.value = true;
};

const handleRemove = (index: number) => {
  deviceList.value.splice(index, 1);
};
const handleReturnRemove = (index: number) => {
  returnDeviceList.value.splice(index, 1);
};

// 处理表格多选变化
const handleSelectionChange = (selection: DeviceListItem[]) => {
  selectedDevices.value = selection;
};

// 设备选择处理
function onDeviceSelected(devices: Device[]) {
  console.log("devices:::",devices,"activeName:::",activeName.value);
  if (activeName.value === 'first') {
    // 获取已存在的设备ID列表
    const existingIds = new Set(form.value.items.map((item: any) => item.device).filter(Boolean));
    
    // 过滤掉已存在的设备，只添加新的
    const newDevices = devices.filter((d) => !existingIds.has(d.id));
    
    if (newDevices.length === 0) {
      ElMessage.warning('所选设备已存在，未添加重复项');
      return;
    }
    
    // 如果有部分重复，提示用户
    if (newDevices.length < devices.length) {
      ElMessage.warning(`已过滤 ${devices.length - newDevices.length} 个重复的设备`);
    }
    
    form.value.items.push(
      ...newDevices.map((d) => ({
        device: d.id,
        device_code: d.code,
        remark: d.category_name,
        quantity: 1,
        location: d.warehouse,
        device_name: d.name,
        device_specification: d.device_specification
      }))
    );
  } else if (activeName.value === 'second') {
    // 获取已存在的设备ID列表
    const existingIds = new Set(deviceList.value.map((item: any) => item.device_no).filter(Boolean));
    
    // 过滤掉已存在的设备，只添加新的
    const newDevices = devices.filter((d) => !existingIds.has(d.id));
    
    if (newDevices.length === 0) {
      ElMessage.warning('所选设备已存在，未添加重复项');
      return;
    }
    
    // 如果有部分重复，提示用户
    if (newDevices.length < devices.length) {
      ElMessage.warning(`已过滤 ${devices.length - newDevices.length} 个重复的设备`);
    }
    
    deviceList.value.push(
      ...newDevices.map(d => ({
        device_no: d.id,
        device_code: d.code,
        device_type: d.category_name,
        device_name: d.name || '',
        borrow_count: 1,
        brand: d.brand || '',
        model: d.model,
        device_specification: d.specification,
        warehouse: d.warehouse,
        available_quantity:d.available_quantity
      }))
    );
  }else if(activeName.value === 'third'){
    // 在添加前检查每个设备是否已存在；手动选设备：将本次归还数量记满至「待归还」上限
    devices.forEach(d => {
      const existingDeviceIndex = returnDeviceList.value.findIndex(item => item.device_no === d.id);
      if (existingDeviceIndex !== -1) {
        const row = returnDeviceList.value[existingDeviceIndex];
        const cap = row.available_quantity ?? 0;
        if (cap <= 0) {
          ElMessage.warning('该设备无待归还数量');
          return;
        }
        row.borrow_count = cap;
        row.is_return = true;
        row.return_time = dayjs().format('YYYY-MM-DD HH:mm:ss');
        row.brand = d.brand || row.brand || '';
        if (row.return_status) {
          row.return_status = { value: 2, label: '已归还' };
        }
        touchReturnRowSort(row);
        ElMessage.success(`已将该设备本次归还记为 ${cap} 件`);
      } else {
        // 如果设备不存在，添加新记录
        /* returnDeviceList.value.push({
          device_no: d.id,
          device_type: d.category_name,
          device_name: d.name || '',
          borrow_count: 1,
          brand: d.brand || '',
          model: d.model || '',
          warehouse: d.warehouse,
          status: '已归还'
        }); */
        /* ElMessage.success(`设备 ${d.category_name} 已添加到归还列表`); */
      }
    });
  }
}

// 移除同步相关的 watch
// const handleClick = (tab: TabsPaneContext, event: Event) => {
//   if (tab.props.name === 'second') {
//     deviceList.value = form.value.items.map(item => ({
//       device_no: item.device,
//       device_type: item.remark,
//       device_name: '',
//       borrow_count: item.quantity,
//       brand: '',
//       model: '',
//       warehouse: item.location
//     }));
//   }
// }

function handleClick(tab: TabsPaneContext) {
  console.log('Tab clicked:', tab.props.name);
  // 当切换到设备清单标签页时，自动聚焦输入框
  if (tab.props.name === 'second') {
    nextTick(() => {
      if (searchInputRef.value) {
        searchInputRef.value.focus();
        searchInputRef.value.select();
      }
    });
  } else if (tab.props.name === 'third') {
    // 当切换到归还设备清单标签页时，自动聚焦输入框
    nextTick(() => {
      returnSearchInputRef.value?.focus?.();
    });
  }
}

function handleUploadSuccess(response: any, file: any, fileList: any) {
	// eslint-disable-next-line no-console
  console.log('上传成功:', file.name);
}

function handleUploadError(err: any, file: any, fileList: any) {
	// eslint-disable-next-line no-console
  console.error('上传失败:', file.name);
}

// 图片预览处理函数
const handlePictureCardPreview = (uploadFile: any) => {
  dialogImageUrl.value = uploadFile.url || uploadFile.response?.url || form.value.attachments;
  dialogVisible.value = true;
};

// 处理附件删除
const handleRemoves = (file: any, fileList: any) => {
  // 由于是禁用状态，这里只是示例，实际不会执行删除
  console.log('删除附件:', file.name);
};


const form = ref<FormData>({
  borrower_info:{
    user_code:'',
    mobile:''
  },
	application_no: '',
	emergency_contact: '',
	emergency_phone: '',
	app_user_borrower: { id: '', name: '', user_code: '', mobile: '' },
	team_type: 0,
	team_members_count: 1,
	team_members: '',
	expected_start_time:'',
	expected_end_time: '',
	borrower_dept: '',
	purpose: '',
	applicant_remark_type: "1",
	applicant_remark: '',
	items: [],
	accessory_info: '',
	borrow_type: 2,
	return_location:'',
	approver_info: {
		name: ''
	}
});
const showSelectDeviceDialog = ref(false);


const rules = {
  emergency_contact: [
    { required: true, message: '请输入借用人', trigger: 'change' },
  ],
  app_user_borrower: [
    { required: true, message: '请输入学号或工号', trigger: 'change' },
  ],
  emergency_phone: [
    { required: true, message: '请输入联系电话', trigger: 'change' },
  ],
  /* borrower_dept: [
    { required: true, message: '请输入借用部门', trigger: 'change' },
  ], */
  expected_end_time: [
    { required: true, message: '请输选择归还时间', trigger: 'change' },
  ],
  team_type: [
    { required: true, message: '请选择个人或者团队', trigger: 'change' },
  ],
  purpose: [
    { required: true, message: '请输入借用原因', trigger: 'change' },
  ],
  applicant_remark_type: [
    { required: true, message: '请选择审批人', trigger: 'change' },
  ],
  applicant_remark: [
    { required: false, message: '请输入备注', trigger: 'change' },
  ],
};


// 自动填充用户信息
onMounted(() => {
	loadWarehouses()
	getAdminList()
	getAllUserList()
	try {
		const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');
		if (userInfo) {
			form.value.emergency_contact = userInfo.username || '';
			// 借用人从用户列表加载完成后再统一回显/设置
			form.value.emergency_phone = userInfo.mobile || '';
			form.value.borrower_dept = userInfo.dept_info?.dept_name || '';
		}
	} catch (e) {
		/* empty */
	}
});

watch(
	() => props.visible,
	(v) => {
		visible.value = v;
		// 当对话框打开且当前标签页是设备清单时，自动聚焦输入框
		if (v && activeName.value === 'second' && isCollect.value) {
			nextTick(() => {
				if (searchInputRef.value) {
					searchInputRef.value.focus();
					searchInputRef.value.select();
				}
			});
		} else if (v && activeName.value === 'third' && !isView.value) {
			// 当对话框打开且当前标签页是归还设备清单时，自动聚焦输入框
			nextTick(() => {
				returnSearchInputRef.value?.focus?.();
			});
		}
		// 清理RFID缓冲状态
		if (v) {
			rfidInputBuffer.value = '';
			currentRfidTag.value = '';
			rfidTagArray.value = [];
			clearRFIDInputTimer();
			consecutiveInputCount = 0;
			lastInputTime = 0;
			// 清空待提交的设备编号数组
			pendingDeviceCodes.value = [];
			isAutoSubmitting.value = false;
			// 清理归还流程RFID缓冲状态
			returnRfidInputBuffer.value = '';
			returnCurrentRfidTag.value = '';
			returnRfidTagArray.value = [];
			returnProcessingTags.value.clear();
			isProcessingReturnTagArray.value = false;
			clearReturnRFIDInputTimer();
			returnConsecutiveInputCount = 0;
			returnLastInputTime = 0;
		}
	}
);

watch(() => props.modelValue, async (val) => {
  if (val && val.id) {
			try {
			const res = await api.GetApplicationDetail(val.id);
      console.log("res:::::",res)
			if (res.code === 2000 && res.data) {
				const data = res.data;
				Object.assign(form.value, data);
        buildSteps(data);
                // 领取模式下不回显历史配件内容
                if (isCollect.value) {
                  collectAccessories.value = '';
                }
				timeline.value.create = data.create_datetime ? dayjs(data.create_datetime).format('YYYY-MM-DD HH:mm:ss') : '';
				timeline.value.approve = data.approve_time || '';
        const approverinfo = data.approver_info ?? data.admin_approver_info
        timeline.value.approver = approverinfo?.name || '审批人'

				// timeline.value.approver = data.admin_approver_info?.name || '审批人';
                // console.log("data:::",form.value);
				// activeStep.value = 1; // 创建
				// if (data.status >= 1) activeStep.value = 2; // 待审批
				// if (data.status >= 2) activeStep.value = 3; // 审批通过
				// if (data.status >= 3) activeStep.value = 4; // 完成

                // 同步 form.items 到 returnDeviceList
                if (form.value.items && form.value.items.length > 0) {
                    returnDeviceList.value = (form.value.items as any[])
                        .filter((item) => item.device !== null)
                        .map(mapFormItemToReturnDeviceListRow);
                }
                // 同步 form.records 到 returnAbnormalList
                if (form.value.records && form.value.records.length > 0) {
                    // 添加损坏类型记录
                    const damageRecord: AbnormalRecord = {
                        application_no: form.value.application_no,
                        operator_name: form.value.app_user_borrower?.name||form.value.external_borrower_name||'',
                        user_code: form.value.borrower_info?.user_code || form.value.app_user_borrower?.user_code||'',
                        emergency_phone: form.value.app_user_borrower?.mobile||form.value.external_borrower_phone || '',
                        type: '损坏',
                        condition: form.value.borrower_damage_count || 0,
                        create_time: dayjs().format('YYYY-MM-DD HH:mm:ss')
                    };

                    // 添加逾期类型记录
                    const overdueRecord: AbnormalRecord = {
                        application_no: form.value.application_no,
                        operator_name: form.value.app_user_borrower?.name||form.value.external_borrower_name||'',
                        user_code: form.value.borrower_info?.user_code || form.value.app_user_borrower?.user_code||'',
                        emergency_phone: form.value.app_user_borrower?.mobile||form.value.external_borrower_phone || '',
                        type: '逾期',
                        condition: form.value.borrower_overdue_count || 0, // 逾期数量设为1
                        create_time: dayjs().format('YYYY-MM-DD HH:mm:ss')
                    };

                    returnAbnormalList.value = [damageRecord, overdueRecord];
                    abnormalList.value = [damageRecord, overdueRecord];
                }
                
                // 处理附件回显
                if (data.attachments) {
                    if (typeof data.attachments === 'string') {
                        // 如果attachments是字符串URL
                        attachmentFileList.value = [{
                            name: data.attachments.split('/').pop() || '附件',
                            url: data.attachments,
                            status: 'success'
                        }];
                    } else if (Array.isArray(data.attachments)) {
                        // 如果attachments是数组
                        attachmentFileList.value = data.attachments.map((item: any, index: number) => {
                            if (typeof item === 'string') {
                                return {
                                    name: item.split('/').pop() || `附件${index + 1}`,
                                    url: item,
                                    status: 'success'
                                };
                            } else if (typeof item === 'object' && item.url) {
                                return {
                                    name: item.name || item.url.split('/').pop() || `附件${index + 1}`,
                                    url: item.url,
                                    status: 'success'
                                };
                            }
                            return null;
                        }).filter(Boolean);
                    }
                }
			}
			} catch (e) {
        console.log("审判失败:::",e)
			  ElMessage.error('获取审批信息失败');
			}
	}else if(val&& isEdit.value){
		try {
			const res = await api.GetApplicationDetail(val.id);
			if (res.code === 2000 && res.data) {
				const data = res.data;
				Object.assign(form.value, data);

                // 同步 form.items 到 returnDeviceList
                if (form.value.items && form.value.items.length > 0) {
                    returnDeviceList.value = (form.value.items as any[])
                        .filter((item) => item.device !== null)
                        .map(mapFormItemToReturnDeviceListRow);
                }
                
                // 处理附件回显 (编辑模式)
                if (data.attachments) {
                    if (typeof data.attachments === 'string') {
                        attachmentFileList.value = [{
                            name: data.attachments.split('/').pop() || '附件',
                            url: data.attachments,
                            status: 'success'
                        }];
                    } else if (Array.isArray(data.attachments)) {
                        attachmentFileList.value = data.attachments.map((item: any, index: number) => {
                            if (typeof item === 'string') {
                                return {
                                    name: item.split('/').pop() || `附件${index + 1}`,
                                    url: item,
                                    status: 'success'
                                };
                            } else if (typeof item === 'object' && item.url) {
                                return {
                                    name: item.name || item.url.split('/').pop() || `附件${index + 1}`,
                                    url: item.url,
                                    status: 'success'
                                };
                            }
                            return null;
                        }).filter(Boolean);
                    }
                }
			}
			} catch (e) {
			ElMessage.error('获取审批信息失败');
			}
	}
}, { immediate: true });


// watch(
// 	() => props.modelValue,
// 	(v) => {
// 		if (v) {
// 			// eslint-disable-next-line no-console
// 			console.log("val:::::",v);
// 			Object.assign(form.value, v);
// 		}
// 	}, { immediate: true }
// );
// 监听借用人选择变化
watch(() => form.value.app_user_borrower?.id, (newId) => {
	if (!newId || allUserList.value.length === 0) return;
	const selectedUser: any = allUserList.value.find((u: any) => String(u.id) === String(newId));
	if (selectedUser) {
		form.value.app_user_borrower = {
			id: selectedUser.id,
			name: selectedUser.name,
			user_code: selectedUser.user_code || '',
			mobile: selectedUser.mobile || ''
		};
	}
});
function addItem() {
    if (activeName.value === 'third' && allReturned.value) {
        ElMessage.info('当前列表设备均已归还，无可选择设备');
        return;
    }
    showSelectDeviceDialog.value = true;
}
function removeItem(index: number) {
	form.value.items.splice(index, 1);
}
function onCancel() {
    // 重置标签页到第一个
    activeName.value = 'first';
    // 清理异常记录列表
    returnAbnormalList.value = [];
    abnormalList.value = [];
    // 清理设备列表
    deviceList.value = [];
    returnDeviceList.value = [];
    // 清理RFID相关定时器和状态
    clearRFIDInputTimer();
    clearProcessTagArrayTimer();
    clearReturnRFIDInputTimer();
    clearReturnProcessTagArrayTimer();
    rfidInputBuffer.value = '';
    currentRfidTag.value = '';
    rfidTagArray.value = [];
    returnRfidInputBuffer.value = '';
    returnCurrentRfidTag.value = '';
    returnRfidTagArray.value = [];
    processingTags.value.clear();
    returnProcessingTags.value.clear();
    isProcessingTagArray.value = false;
    isProcessingReturnTagArray.value = false;
    // 清空待提交的设备编号数组
    pendingDeviceCodes.value = [];
    isAutoSubmitting.value = false;
    consecutiveInputCount = 0;
    lastInputTime = 0;
    returnConsecutiveInputCount = 0;
    returnLastInputTime = 0;
    // 清理搜索框
    searchText.value = '';
    returnSearchText.value = '';
    // 清理备注
    remark.value = '';
    // 清理领取模式配件信息
    collectAccessories.value = '';
    returnRemark.value = '';
    // 重置状态
    returnStatus.value = '未归还';
    // 清理选中的设备
    selectedDevices.value = [];
    // 清理附件文件列表
    attachmentFileList.value = [];
    // 清理RFID缓冲
    rfidInputBuffer.value = '';
    currentRfidTag.value = '';
    rfidTagArray.value = [];
    clearRFIDInputTimer();
    consecutiveInputCount = 0;
    lastInputTime = 0;
    // 清理归还流程RFID缓冲
    returnRfidInputBuffer.value = '';
    returnCurrentRfidTag.value = '';
    returnRfidTagArray.value = [];
    returnProcessingTags.value.clear();
    isProcessingReturnTagArray.value = false;
    clearReturnRFIDInputTimer();
    returnConsecutiveInputCount = 0;
    returnLastInputTime = 0;
    // 关闭所有对话框
    showSelectDeviceDialog.value = false;
    showSettlementDialog.value = false;
    showAbnormalDialog.value = false;
    showViewAbnormalDialog.value = false;
    // 重置当前异常数据
    currentAbnormalData.value = {
        damage_type: 0,
        condition: '',
        photos: []
    };
    // 发出关闭事件
    emit('update:visible', false);
}
// 提交时合并数据
function onSubmit() {
  if(isCollect.value){
    // 验证是否有设备信息
    const hasDevicesInFirstTab = form.value.items && form.value.items.length > 0;
    const hasDevicesInSecondTab = deviceList.value && deviceList.value.length > 0;
    
    if (!hasDevicesInFirstTab && !hasDevicesInSecondTab) {
      ElMessage.warning('请添加设备信息后再提交');
      activeName.value = 'second'; // 自动切换到借用列表标签页
      return;
    }

    // 验证设备数量
    const hasInvalidQuantityInFirstTab = form.value.items.some(item => !item.quantity || item.quantity <= 0);
    const hasInvalidQuantityInSecondTab = deviceList.value.some(item => !item.borrow_count || item.borrow_count <= 0);

    if (hasInvalidQuantityInFirstTab || hasInvalidQuantityInSecondTab) {
      ElMessage.warning('请确保所有设备的数量大于0');
      activeName.value = 'second'; // 自动切换到借用列表标签页
      return;
    }

    // 合并两个标签页的设备数据
    const allDevices = [
      ...deviceList.value.map(item => ({
        condition: remark.value,
        quantity: item.borrow_count,
        device_id: Number(item.device_no) || 0
      }))
    ];
    
    const submitData = {
        id:form.value.id,
        item_id:form.value.id,
        device_assignments: allDevices,
        remark:remark.value,
        pre_borrow_accessories: collectAccessories.value,
    };

    CollectEquipment(submitData).then((res: ApiResponse) => {
      if(res.code===2000){
        ElMessage.success("领取成功");
        // 准备结算单数据
        settlementData.value = {
          ...form.value,
          items: deviceList.value.map(item => ({
            ...item,
            device_category_name: item.device_type,
            device_name: item.device_name,
            device_specification: item.device_specification,
            device_storage_location: getWarehouseName(item.warehouse) || item.warehouse,
            remark: item.device_type,
            quantity: item.borrow_count,
            device_id: item.device_no,
            device_category: item.device_type,
            device_code: item.device_no,
            borrow_type: form.value.borrow_type,
            borrower_dept: form.value.borrower_dept,
            emergency_contact: form.value.emergency_contact,
            emergency_phone: form.value.emergency_phone,
            team_type: form.value.team_type,
          })),
          accessory_info: accessoryInfo.value,
          pre_borrow_accessories:collectAccessories.value,
          remark: remark.value,
          expected_start_time: dayjs().format('YYYY-MM-DD HH:mm:ss')
        };
        
        // 先触发提交事件进行页面刷新
        emit('submit');
        
        // 关闭当前对话框
        emit('update:visible', false);
        
        // 使用 nextTick 确保在 DOM 更新后再显示结算单
        nextTick(() => {
          borrowForm.value = {...settlementData.value,mode: 'settlement' };
          showSettlementDialog.value = true;
        });
      }
    });
  } else {
    // 归还：按每行「归还数量」提交，须大于 0 且不超过待归还
    const toReturn = returnDeviceList.value.filter(
      (item) => (Number(item.borrow_count) || 0) > 0
    );
    if (toReturn.length === 0) {
      ElMessage.warning('请通过扫码/输入填写归还数量，或从手动归还中确认设备');
      return;
    }
    const over = toReturn.find(
      (item) => (Number(item.borrow_count) || 0) > (Number(item.available_quantity) || 0)
    );
    if (over) {
      ElMessage.error('存在归还数量超过待归还数量，请检查');
      return;
    }
    const allDevices = toReturn.map((item) => ({
      device: item.device_no,
      quantity: item.borrow_count,
      remark: returnRemark.value,
      device_id: Number(item.device_no) || 0,
      condition: item.condition,
      damage_type: item.damage_type,
      photo_urls: item.photos || [],
    }));
    
    const submitData = {
      id: form.value.id,
      items: allDevices,
      status: returnStatus.value,
      pre_borrow_accessories: form.value.pre_borrow_accessories,
    };
    
    ReturnEquipment(submitData).then(async (res: ApiResponse) => {
      if(res.code===2000){
        ElMessage.success("归还成功");
        try {
          if (form.value.id) {
            const detailRes = await api.GetApplicationDetail(form.value.id);
            if (detailRes.code === 2000 && detailRes.data) {
              returnStatus.value = detailRes.data.status_label || returnStatus.value;
            }
          }
        } catch (e) {
          ElMessage.error('获取最新状态失败');
        }
        emit('submit');
        emit('update:visible', false);
      }
    });
  }
}

function clickReturn(){
  returnStatus.value = '已归还';
  // 自动选择所有设备
  const tableRef = document.querySelector('.el-table__header-wrapper th.el-table__cell.is-leaf .el-checkbox');
  if (tableRef) {
    (tableRef as HTMLElement).click();
  }
}

// 组件卸载时清理定时器和状态
onBeforeUnmount(() => {
  clearRFIDInputTimer();
  clearProcessTagArrayTimer();
  rfidInputBuffer.value = '';
  currentRfidTag.value = '';
  rfidTagArray.value = [];
  consecutiveInputCount = 0;
  lastInputTime = 0;
  processingTags.value.clear();
  isProcessingTagArray.value = false;
  // 清空待提交的设备编号数组
  pendingDeviceCodes.value = [];
  isAutoSubmitting.value = false;
  // 清理归还流程定时器和状态
  clearReturnRFIDInputTimer();
  clearReturnProcessTagArrayTimer();
  returnRfidInputBuffer.value = '';
  returnCurrentRfidTag.value = '';
  returnRfidTagArray.value = [];
  returnProcessingTags.value.clear();
  isProcessingReturnTagArray.value = false;
  returnConsecutiveInputCount = 0;
  returnLastInputTime = 0;
});

	/* formRef.value.validate((valid: boolean) => {
		if (valid) {
			form.value.items = form.value.items.map(item => ({
                ...item,
                quantity: Number(item.quantity) || 0  
            }));
			const firstLocation = form.value.items[0]?.location || '';
            form.value.return_location = firstLocation;
			form.value.expected_start_time = now;
			form.value.expected_end_time = dayjs(form.value.expected_end_time).format('YYYY-MM-DD HH:mm:ss')|| now;
			form.team_members_count=Number(form.team_members_count)||1;
			emit('submit', { ...form.value });
			emit('update:visible', false);
			ElMessage.success("添加成功！");
		}
	}); */
	

</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .return-cell-placeholder {
    color: #c0c4cc;
  }
  .return-cell-text {
    color: #606266;
  }
  .device-code-input {
    padding: 8px 12px;
    font-size: 14px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    outline: none;
    resize: vertical;
    transition: all 0.3s;
    font-family: 'Microsoft YaHei', sans-serif;
    line-height: 1.5;
  }
  .device-code-input:focus {
    border-color: #409EFF;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  }
  .device-code-input:disabled {
    background-color: #f5f7fa;
    cursor: not-allowed;
  }
  </style>