<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="入库单号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" placeholder="请输入入库单号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="关联单号" prop="relatedOrderNo">
        <el-input v-model="queryParams.relatedOrderNo" placeholder="请输入关联单号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="仓库" prop="warehouseId">
        <el-row :gutter="10">
          <el-col :span="18">
            <el-input v-model="queryParams.warehouseId" placeholder="请选择仓库" readonly clearable />
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="openQueryWarehouseSelect">选择仓库</el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['ware:wmsInboundOrder:add']">新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="wmsInboundOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="入库单号" align="center" prop="orderNo" width="180" fixed="left" />
      <el-table-column label="入库类型" align="center" prop="orderType">
        <template #default="scope">
          <dict-tag :options="inbound_type" :value="scope.row.orderType" />
        </template>
      </el-table-column>
      <el-table-column label="仓库ID" align="center" prop="warehouseId" />
      <el-table-column label="供应商ID" align="center" prop="supplierId" />
      <el-table-column label="关联单号" align="center" prop="relatedOrderNo" />
      <el-table-column label="总数量" align="center" prop="totalQuantity" />
      <el-table-column label="总金额" align="center" prop="totalAmount" />
      <!-- <el-table-column label="单据状态" align="center" prop="orderStatus" /> -->
      <el-table-column label="入库人" align="center" prop="applicantId" />
      <el-table-column label="入库时间" align="center" prop="applyTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="预计到货日期" align="center" prop="expectedArrivalDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expectedArrivalDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="实际到货日期" align="center" prop="actualArrivalDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.actualArrivalDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="质检员" align="center" prop="qualityCheckerId" />
      <el-table-column label="质检时间" align="center" prop="qualityCheckTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.qualityCheckTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="质检状态" align="center" prop="qualityStatus" />
      <el-table-column label="上架员" align="center" prop="putawayPersonId" />
      <el-table-column label="上架时间" align="center" prop="putawayTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.putawayTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审批状态" align="center" prop="approvalStatus" /> -->
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="400" fixed="right">
        <template #default="scope">
          <el-button v-if="scope.row.orderStatus === '0'" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['ware:wmsInboundOrder:edit']">修改入库单</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['ware:wmsInboundOrder:remove']">删除</el-button>
          <el-button link type="primary" icon="Document" @click="handlePrint(scope.row)"
            v-hasPermi="['ware:wmsInboundOrder:print']">打印入库单</el-button>
          <el-button link type="primary" icon="Check" @click="handleInventory(scope.row)"
            v-hasPermi="['ware:wmsInboundOrder:inventory']">入库</el-button>
          <el-button v-if="scope.row.orderStatus !== '0'" link type="primary" icon="SetUp" @click="handleAdjustInventory(scope.row)"
            v-hasPermi="['ware:wmsInboundOrder:adjust']">调整入库明细信息</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改入库单主对话框 -->
    <el-dialog :title="title" v-model="open" width="1500px" append-to-body>
      <el-form ref="wmsInboundOrderRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="入库单号" prop="orderNo">
              <el-input v-model="form.orderNo" placeholder="请输入入库单号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="仓库" prop="warehouseId">
              <el-row :gutter="10">
                <el-col :span="18">
                  <el-input v-model="form.warehouseId" placeholder="请选择仓库" readonly />
                </el-col>
                <el-col :span="6">
                  <el-button type="primary" @click="openWarehouseSelect">选择仓库</el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商" prop="supplierId">
              <el-row :gutter="10">
                <el-col :span="18">
                  <el-input v-model="form.supplierId" placeholder="请选择供应商" readonly />
                </el-col>
                <el-col :span="6">
                  <el-button type="primary" @click="openSupplierSelect">选择供应商</el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="关联单号" prop="relatedOrderNo">
              <el-input v-model="form.relatedOrderNo" placeholder="请输入关联单号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总数量" prop="totalQuantity">
              <el-input v-model="form.totalQuantity" placeholder="请输入总数量" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总金额" prop="totalAmount">
              <el-input v-model="form.totalAmount" placeholder="请输入总金额" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="入库人" prop="applicantId">
              <el-input v-model="form.applicantId" placeholder="请输入申请人" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库时间" prop="applyTime">
              <el-date-picker clearable v-model="form.applyTime" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择申请时间" disabled >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实际到货日期" prop="actualArrivalDate">
              <el-date-picker clearable v-model="form.actualArrivalDate" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择实际到货日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <!-- <el-col :span="12">
            <el-form-item label="预计到货日期" prop="expectedArrivalDate">
              <el-date-picker clearable v-model="form.expectedArrivalDate" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择预计到货日期">
              </el-date-picker>
            </el-form-item>
          </el-col> -->
          
        </el-row>
        <!-- <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="质检员" prop="qualityCheckerId">
              <el-input v-model="form.qualityCheckerId" placeholder="请输入质检员" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检时间" prop="qualityCheckTime">
              <el-date-picker clearable v-model="form.qualityCheckTime" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择质检时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row> -->
        <!-- <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上架员" prop="putawayPersonId">
              <el-input v-model="form.putawayPersonId" placeholder="请输入上架员" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上架时间" prop="putawayTime">
              <el-date-picker clearable v-model="form.putawayTime" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择上架时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"  />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 入库单明细 -->
        <el-divider>入库单明细</el-divider>
        <el-row :gutter="20" style="margin-bottom: 10px;">
          <el-col :span="24" style="text-align: right;">
            <el-button v-if="title !== '修改入库单'" type="primary" size="small" icon="Plus" @click="addDetail">添加明细</el-button>
          </el-col>
        </el-row>
        <el-table :data="form.items" border style="width: 100%">
          <el-table-column prop="materialName" label="物资名称" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.materialName" placeholder="请输入物资名称" size="small" disabled />
            </template>
          </el-table-column>
          <el-table-column prop="planQuantity" label="计划数量" width="100">
            <template #default="scope">
              <el-input 
                v-model.number="scope.row.planQuantity" 
                placeholder="请输入计划数量" 
                size="small" 
                type="number" 
                :precision="3" 
                :step="0.001"
              />
            </template>
          </el-table-column>
          <el-table-column prop="actualQuantity" label="实际数量" width="100">
            <template #default="scope">
              <el-input 
                v-model.number="scope.row.actualQuantity" 
                placeholder="请输入实际数量" 
                size="small" 
                @change="calculateAmount(scope.row)" 
                type="number" 
                :precision="3" 
                :step="0.001"
              />
            </template>
          </el-table-column>
          <el-table-column prop="unit" label="单位" width="80">
            <template #default="scope">
              <el-input v-model="scope.row.unit" placeholder="请输入单位" size="small" disabled />
            </template>
          </el-table-column>
          <el-table-column prop="unitPrice" label="单价" width="100">
            <template #default="scope">
              <el-input 
                v-model.number="scope.row.unitPrice" 
                placeholder="请输入单价" 
                size="small" 
                @change="calculateAmount(scope.row)" 
                type="number" 
                :precision="2" 
                :step="0.01"
              />
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="金额" width="100">
            <template #default="scope">
              <el-input 
                v-model.number="scope.row.amount" 
                placeholder="请输入金额" 
                size="small" 
                disabled 
                type="number" 
                :precision="2"
              />
            </template>
          </el-table-column>
          <el-table-column prop="batchNo" label="批次号" width="180">
            <template #default="scope">
              <el-input v-model="scope.row.batchNo" placeholder="请输入批次号" size="small" />
            </template>
          </el-table-column>
          <el-table-column prop="productionDate" label="生产日期" width="180">
            <template #default="scope">
              <el-date-picker clearable v-model="scope.row.productionDate" type="date" value-format="YYYY-MM-DD"
                  placeholder="请选择生产日期" size="small" format="YYYY-MM-DD" class="!w-full">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column prop="expirationDate" label="失效日期" width="180">
            <template #default="scope">
              <el-date-picker clearable v-model="scope.row.expirationDate" type="date" value-format="YYYY-MM-DD"
                  placeholder="请选择失效日期" size="small" format="YYYY-MM-DD" class="!w-full">
              </el-date-picker>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="qualityStatus" label="质检状态" width="100">
            <template #default="scope">
              <el-input v-model="scope.row.qualityStatus" placeholder="请输入质检状态" size="small" />
            </template>
          </el-table-column>
          <el-table-column prop="checkQuantity" label="质检数量" width="100">
            <template #default="scope">
              <el-input v-model.number="scope.row.checkQuantity" placeholder="请输入质检数量" size="small" />
            </template>
          </el-table-column> -->
          <!-- <el-table-column prop="unqualifiedQuantity" label="不合格数量" width="120">
            <template #default="scope">
              <el-input v-model.number="scope.row.unqualifiedQuantity" placeholder="请输入不合格数量" size="small" />
            </template>
          </el-table-column>
          <el-table-column prop="unqualifiedReason" label="不合格原因" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.unqualifiedReason" placeholder="请输入不合格原因" size="small" />
            </template>
          </el-table-column> -->
          <el-table-column prop="locationId" label="货架" width="300">
            <template #default="scope">
              <LocationCascaderSelect 
                :model-value="{warehouseId: form.warehouseId, areaId: scope.row.areaId, locationId: scope.row.locationId}"
                @update:model-value="(value) => {
                  scope.row.warehouseId = value.warehouseId;
                  scope.row.areaId = value.areaId;
                  scope.row.locationId = value.locationId;
                }"

              />
            </template>
          </el-table-column>
          
          <el-table-column prop="remark" label="备注" width="150">
            <template #default="scope">
              <el-input type="textarea" v-model="scope.row.remark" placeholder="请输入备注" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center" fixed="right">
            <template #default="scope">
              <el-button type="danger" size="small" icon="Delete" @click="deleteDetail(scope.$index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 物资选择对话框组件 -->
    <MaterialSelectDialog ref="materialSelectDialogRef" v-model:visible="materialDialogVisible" title="选择物资"
      @confirm="handleMaterialConfirm" />

    <!-- 仓库选择对话框组件 -->
    <WarehouseSelectDialog ref="warehouseSelectDialogRef" v-model:visible="warehouseDialogVisible" title="选择仓库"
      @confirm="handleWarehouseConfirm" />

    <!-- 供应商选择对话框组件 -->
    <SupplierSelectDialog ref="supplierSelectDialogRef" v-model:visible="supplierDialogVisible" title="选择供应商"
      @confirm="handleSupplierConfirm" />

    <!-- RFID标签选择对话框组件 -->
    <RfidTagSelectDialog ref="rfidTagSelectDialogRef" v-model:visible="rfidTagDialogVisible" title="选择RFID标签"
      @confirm="handleRfidTagConfirm" />

    <!-- PTL标签选择对话框组件 -->
    <PtlTagSelectDialog ref="ptlTagSelectDialogRef" v-model:visible="ptlTagDialogVisible" title="选择PTL标签"
      @confirm="handlePtlTagConfirm" />

    <!-- 二维码打印对话框组件 -->
    <QrcodePrintDialog
      ref="qrcodePrintDialogRef"
      v-model:visible="qrcodePrintDialogVisible"
      :qrcode-value="currentQrcodeValue"
      @print="handleQrcodePrint"
    />

    <!-- 入库对话框 -->
    <el-dialog
      title="入库操作"
      v-model="inventoryDialogVisible"
      width="1200px"
      append-to-body
    >
      <el-form :model="inventoryQueryParams" ref="inventoryQueryRef" :inline="true" label-width="120px">
        <el-form-item label="批次号" prop="batchNo">
          <el-input 
            v-model="inventoryQueryParams.batchNo" 
            placeholder="请输入或扫描批次号" 
            clearable 
            @keyup.enter="handleInventoryQuery"
            @input="handleBatchNoInput"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleInventoryQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetInventoryQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="inventoryDetailList" border style="width: 100%; margin-top: 20px;" height="600px">
        <!-- <el-table-column prop="materialCode" label="物资编码" width="150" /> -->
        <el-table-column prop="wmsMaterial.materialName" label="物资名称" width="200" />
        <el-table-column prop="batchNo" label="批次号" width="150" />
        <el-table-column prop="actualQuantity" label="数量" width="100" />
        <el-table-column prop="unitPrice" label="单价" width="100" />
        <el-table-column label="金额" width="100">
          <template #default="scope">
            <span>{{ scope.row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="wmsWarehouse.warehouseName" label="仓库" width="100" />
        <el-table-column prop="wmsArea.areaName" label="库区" width="100" />
        <el-table-column prop="wmsLocation.locationName" label="货架" width="100" />
        <el-table-column prop="storageLocation" label="PTL标签" width="180">
            <template #default="scope">
              <el-input v-model="scope.row.storageLocation" placeholder="请选择PTL标签" size="small" readonly />
              <el-button slot="append" type="primary" size="small" @click="openPtlTagSelect(scope.$index)">选择</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="rfidTagIds" label="RFID标签" width="180">
            <template #default="scope">
              <el-input v-model="scope.row.rfidTagIds" placeholder="请选择RFID标签" size="small" readonly />
              <el-button slot="append" type="primary" size="small" @click="openRfidTagSelect(scope.$index)">选择</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="wmsInboundOrderItemId" label="操作" width="100" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleExportQrcode(scope.row)">打印二维码</el-button>
            </template>
          </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="inventoryDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmInventory">确认入库</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 入库明细调整对话框 -->
    <el-dialog
      title="调整入库明细信息"
      v-model="adjustInventoryDialogVisible"
      width="1200px"
      append-to-body
    >
      <el-table :data="adjustInventoryDetailList" border style="width: 100%" height="600px">
        <el-table-column prop="wmsMaterial.materialName" label="物资名称" width="200" />
        <el-table-column prop="batchNo" label="批次号" width="150" />
        <el-table-column prop="actualQuantity" label="数量" width="120">
          <template #default="scope">
            <el-input 
              v-if="scope.row.isEditing" 
              v-model.number="scope.row.actualQuantity" 
              placeholder="请输入实际数量" 
              size="small" 
              type="number"
              :precision="3"
              :step="0.001"
              @input="() => {
                scope.row.amount = scope.row.actualQuantity && scope.row.unitPrice ? (scope.row.actualQuantity * scope.row.unitPrice).toFixed(2) : '0.00'
              }"
            />
            <span v-else>{{ scope.row.actualQuantity }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="unitPrice" label="单价" width="100">
          <template #default="scope">
            <el-input 
              v-if="scope.row.isEditing" 
              v-model.number="scope.row.unitPrice" 
              placeholder="请输入单价" 
              size="small" 
              type="number"
              :precision="2"
              :step="0.01"
              @input="() => {
                scope.row.amount = scope.row.actualQuantity && scope.row.unitPrice ? (scope.row.actualQuantity * scope.row.unitPrice).toFixed(2) : '0.00'
              }"
            />
            <span v-else>{{ scope.row.unitPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="金额" width="100">
          <template #default="scope">
            <span>{{ scope.row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="locationId" label="货架" width="300">
          <template #default="scope">
            <LocationCascaderSelect 
              v-if="scope.row.isEditing"
              :model-value="{warehouseId: currentAdjustOrder.warehouseId, areaId: scope.row.areaId, locationId: scope.row.locationId}"
              @update:model-value="(value) => {
                scope.row.warehouseId = value.warehouseId;
                scope.row.areaId = value.areaId;
                scope.row.locationId = value.locationId;
              }"
            />
            <span v-else>{{ scope.row.wmsLocation?.locationName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button 
              v-if="!scope.row.isEditing" 
              type="primary" 
              size="small" 
              icon="Edit" 
              @click="handleEditDetail(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              v-else 
              type="success" 
              size="small" 
              icon="Check" 
              @click="handleSaveDetail(scope.row)"
            >
              保存
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              icon="Delete" 
              @click="handleDelDetail(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="adjustInventoryDialogVisible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="WmsInboundOrder">
import { listWmsInboundOrder, getWmsInboundOrder, delWmsInboundOrder, addWmsInboundOrder, updateWmsInboundOrder, delWmsInboundOrderItem, updateWmsInboundOrderItem, saveWmsInboundOrder, addToInventory } from "@/api/ware/wmsInboundOrder"
import { generateBatchNo, generateInboundOrderNo } from "@/api/ware/codeGenerator"
import MaterialSelectDialog from "@/components/MaterialSelectDialog.vue"
import WarehouseSelectDialog from "@/components/WarehouseSelectDialog.vue"
import SupplierSelectDialog from "@/components/SupplierSelectDialog.vue"
import LocationCascaderSelect from "@/components/LocationCascaderSelect.vue"
import RfidTagSelectDialog from "@/components/RfidTagSelectDialog.vue"
import PtlTagSelectDialog from "@/components/PtlTagSelectDialog.vue"
import QrcodePrintDialog from "@/components/QrcodePrintDialog.vue"
import { listWmsMaterial } from "@/api/ware/wmsMaterial"
import useUserStore from '@/store/modules/user'
import { listWmsInboundOrderItem } from "@/api/ware/wmsInboundOrderItem"


const { proxy } = getCurrentInstance()

const { inbound_type } = proxy.useDict('inbound_type')

const wmsInboundOrderList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 物资选择对话框状态
const materialDialogVisible = ref(false)
// 物资选择对话框实例引用
const materialSelectDialogRef = ref(null)

// 仓库选择对话框状态
const warehouseDialogVisible = ref(false)
// 仓库选择对话框实例引用
const warehouseSelectDialogRef = ref(null)

// 供应商选择对话框状态
const supplierDialogVisible = ref(false)
// 供应商选择对话框实例引用
const supplierSelectDialogRef = ref(null)

// RFID标签选择对话框状态
const rfidTagDialogVisible = ref(false)
// RFID标签选择对话框实例引用
const rfidTagSelectDialogRef = ref(null)

// PTL标签选择对话框状态
const ptlTagDialogVisible = ref(false)
// PTL标签选择对话框实例引用
const ptlTagSelectDialogRef = ref(null)

// 二维码打印对话框状态
const qrcodePrintDialogVisible = ref(false)
// 二维码打印对话框实例引用
const qrcodePrintDialogRef = ref(null)

const inventoryQueryRef = ref(null)
// 入库对话框状态
const inventoryDialogVisible = ref(false)
// 当前入库的入库单
const currentInventoryOrder = ref(null)
// 入库查询参数
const inventoryQueryParams = ref({
  batchNo: null
})
// 入库明细列表
const inventoryDetailList = ref([])

// 入库明细调整对话框状态
const adjustInventoryDialogVisible = ref(false)
// 当前调整的入库单
const currentAdjustOrder = ref(null)
// 入库明细调整列表
const adjustInventoryDetailList = ref([])

// 记录当前编辑的明细行索引
const currentEditingRowIndex = ref(-1)

// 当前选中的入库单
const currentRow = ref(null)
// 当前要打印的二维码值
const currentQrcodeValue = ref('')



const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    orderType: null,
    warehouseId: null,
    supplierId: null,
    relatedOrderNo: null,
    totalQuantity: null,
    totalAmount: null,
    orderStatus: null,
    applicantId: null,
    applyTime: null,
    expectedArrivalDate: null,
    actualArrivalDate: null,
    qualityCheckerId: null,
    qualityCheckTime: null,
    qualityStatus: null,
    putawayPersonId: null,
    putawayTime: null,
    approvalStatus: null,
  },
  rules: {
    orderNo: [
      { required: true, message: "入库单号不能为空", trigger: "blur" }
    ],
    orderType: [
      { required: true, message: "入库类型不能为空", trigger: "change" }
    ],
    warehouseId: [
      { required: true, message: "仓库ID不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

// 入库相关方法
// 打开入库对话框
function handleInventory(row) {
  currentInventoryOrder.value = row
  inventoryDetailList.value = []
  resetInventoryQuery()
  inventoryDialogVisible.value = true
}

// 处理批次号输入（支持扫描枪）
function handleBatchNoInput() {
  // 扫描枪通常会自动添加换行符，这里可以根据实际情况调整
  if (inventoryQueryParams.value.batchNo && inventoryQueryParams.value.batchNo.endsWith('\n')) {
    inventoryQueryParams.value.batchNo = inventoryQueryParams.value.batchNo.trim()
    handleInventoryQuery()
  }
}

// 入库明细查询
function handleInventoryQuery() {
  if (!inventoryQueryParams.value.batchNo) {
    proxy.$message.warning('请输入批次号')
    return
  }
  
  listWmsInboundOrderItem({ batchNo: inventoryQueryParams.value.batchNo }).then(response => {
    if(response.rows.length){
      const currentOrder = response.rows[0];
      if(currentOrder.putawayStatus === '1'){
        proxy.$message.warning('该批次号已上架，不能重复上架')
      }else{
        inventoryDetailList.value = [currentOrder];
      }
    }else{
      proxy.$message.warning('未查询到相关入库明细')
    }
  }).catch(error => {
    proxy.$message.error('查询入库明细失败：' + error.message)
  })
}

// 重置入库查询
function resetInventoryQuery() {
  inventoryQueryParams.value = {
    batchNo: null
  }
}

// 确认入库
function confirmInventory() {
  if (inventoryDetailList.value.length === 0) {
    proxy.$message.warning('请先添加入库明细')
    return
  }
  
  proxy.$messageBox.confirm('确定要执行入库操作吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    currentInventoryOrder.value.items = inventoryDetailList.value;
    // 调用入库API
    addToInventory(currentInventoryOrder.value).then(response => {
      proxy.$message.success('入库成功')
      inventoryDialogVisible.value = false
      getList() // 刷新列表
    }).catch(error => {
      proxy.$message.error('入库失败：' + error.message)
    })
  }).catch(() => {
    // 取消操作
  })
}

// 调整已入库信息相关方法
// 打开调整入库信息对话框
function handleAdjustInventory(row) {
  currentAdjustOrder.value = row
  // 深拷贝明细列表，避免直接修改原数据

  listWmsInboundOrderItem({ orderId: row.orderId, pageSize: 1000, pageNum: 1 }).then(response => {
     adjustInventoryDetailList.value = response.rows.map(item => ({
    ...item,
    isEditing: false // 添加编辑状态标志
  }))
  adjustInventoryDialogVisible.value = true
  }).catch(error => {
    proxy.$message.error('查询入库明细失败：' + error.message)
  })


}

// 编辑明细
function handleEditDetail(row) {
  // 保存原始值，以便取消编辑时恢复
  row.originalData = JSON.parse(JSON.stringify(row))
  row.isEditing = true
}

// 保存明细
function handleSaveDetail(row) {
  // 计算金额
  if (row.actualQuantity && row.unitPrice) {
    row.amount = (row.actualQuantity * row.unitPrice).toFixed(2)
  } else {
    row.amount = '0.00'
  }
  
  // 调用更新接口
  updateWmsInboundOrderItem(row).then(response => {
    proxy.$message.success('保存成功')
    row.isEditing = false
  }).catch(error => {
    proxy.$message.error('保存失败：' + error.message)
    // 恢复原始值
    if (row.originalData) {
      Object.assign(row, row.originalData)
      delete row.originalData
    }
  })
}

// 删除明细
function handleDelDetail(row) {
  proxy.$messageBox.confirm('确定要删除这条明细吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 调用删除接口
    delWmsInboundOrderItem(row.itemId).then(response => {
      proxy.$message.success('删除成功')
      // 从列表中移除
      const index = adjustInventoryDetailList.value.findIndex(item => item.itemId === row.itemId)
      if (index !== -1) {
        adjustInventoryDetailList.value.splice(index, 1)
      }
      // 从原入库单中移除
      const originalIndex = currentAdjustOrder.value.items.findIndex(item => item.itemId === row.itemId)
      if (originalIndex !== -1) {
        currentAdjustOrder.value.items.splice(originalIndex, 1)
      }
    }).catch(error => {
      proxy.$message.error('删除失败：' + error.message)
    })
  }).catch(() => {
    // 取消操作
  })
}

/** 查询入库单主列表 */
function getList() {
  loading.value = true
  listWmsInboundOrder(queryParams.value).then(response => {
    wmsInboundOrderList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    orderId: null,
    orderNo: null,
    orderType: '0', // 默认采购入库
    warehouseId: null,
    supplierId: null,
    relatedOrderNo: null,
    totalQuantity: null,
    totalAmount: null,
    orderStatus: '0', // 默认未上架 1 部分上架 2 全部上架
    applicantId: null,
    applyTime: null,
    expectedArrivalDate: null,
    actualArrivalDate: null,
    qualityCheckerId: null,
    qualityCheckTime: null,
    qualityStatus: null,
    putawayPersonId: null,
    putawayTime: null,
    approvalStatus: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    items: []
  }
  proxy.resetForm("wmsInboundOrderRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.orderId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加入库单主"
  
  // 获取当前用户信息
  const userStore = useUserStore()
  // 设置申请人为当前用户
  form.value.applicantId = userStore.id
  // 设置申请时间为当前时间
  form.value.applyTime = new Date().toISOString().split('T')[0]
  
  // 调用接口生成入库单号
  generateInboundOrderNo().then(response => {
    form.value.orderNo = response.msg;
  }).catch(error => {
    console.error('生成入库单号失败:', error)
    proxy.$modal.msgError('生成入库单号失败，请重试')
  })
}

/** 打开仓库选择对话框（用于表单） */
function openWarehouseSelect() {
  warehouseDialogVisible.value = true
  if (warehouseSelectDialogRef.value) {
    warehouseSelectDialogRef.value.handleQuery()
  }
}

/** 打开仓库选择对话框（用于搜索） */
/** 打开搜索仓库选择对话框 */
function openQueryWarehouseSelect() {
  warehouseDialogVisible.value = true
  if (warehouseSelectDialogRef.value) {
    warehouseSelectDialogRef.value.handleQuery()
  }
}

/** 处理仓库选择结果 */
function handleWarehouseConfirm(selectedWarehouses) {
  if (selectedWarehouses.length > 0) {
    const warehouse = selectedWarehouses[0]
    // 同时更新表单和搜索参数
    form.value.warehouseId = warehouse.warehouseId
    queryParams.value.warehouseId = warehouse.warehouseId
    // 可以根据需要添加更多仓库信息字段
  }
}

/** 打开供应商选择对话框 */
function openSupplierSelect() {
  supplierDialogVisible.value = true
  if (supplierSelectDialogRef.value) {
    supplierSelectDialogRef.value.handleQuery()
  }
}

/** 处理供应商选择结果 */
function handleSupplierConfirm(selectedSuppliers) {
  if (selectedSuppliers.length > 0) {
    const supplier = selectedSuppliers[0]
    form.value.supplierId = supplier.supplierId
    // 可以根据需要添加更多供应商信息字段
  }
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _orderId = row.orderId || ids.value
  getWmsInboundOrder(_orderId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改入库单"
  })
}

/** 提交按钮 */
function submitForm() {
  // 表单基础验证
  proxy.$refs["wmsInboundOrderRef"].validate(valid => {
    if (valid) {
      // 验证入库单明细
      if (!form.value.items || form.value.items.length === 0) {
        proxy.$modal.msgError("请至少添加一条入库单明细")
        return
      }

      // 验证每条明细的必填字段
      for (let i = 0; i < form.value.items.length; i++) {
        const detail = form.value.items[i]
        if (!detail.materialId) {
          proxy.$modal.msgError(`第${i + 1}条明细的物资ID不能为空`)
          return
        }
        if (!detail.planQuantity) {
          proxy.$modal.msgError(`第${i + 1}条明细的计划数量不能为空`)
          return
        }
        // 确保数量为正数
        if (detail.planQuantity <= 0) {
          proxy.$modal.msgError(`第${i + 1}条明细的计划数量必须大于0`)
          return
        }
      }

      // 提交数据，统一调用saveWmsInboundOrder接口
      saveWmsInboundOrder(form.value).then(response => {
        proxy.$modal.msgSuccess(title.value === '新增入库单' ? "新增成功" : "修改成功")
        open.value = false
        getList()
      })
    }
  })
}

/** 添加明细 */
function addDetail() {
  if (!form.value.items) {
    form.value.items = []
  }
  // 打开物资选择对话框
  materialDialogVisible.value = true
  // 调用组件方法加载物资分类和列表
  materialSelectDialogRef.value.getTreeselect()
  materialSelectDialogRef.value.handleQuery()
}

/** 打开PTL标签选择对话框 */
function openPtlTagSelect(rowIndex) {
  currentEditingRowIndex.value = rowIndex
  ptlTagDialogVisible.value = true
}

/** 处理PTL标签选择确认 */
function handlePtlTagConfirm(selectedPtlTags) {
  if (selectedPtlTags.length > 0) {
    const ptlTag = selectedPtlTags[0]
    // 使用天线编码作为PTL标签值
    // form.value.items[currentEditingRowIndex.value].storageLocation = ptlTag.antennaCode
    inventoryDetailList.value[currentEditingRowIndex.value].storageLocation = ptlTag.antennaCode
  }
}

/** 打开RFID标签选择对话框 */
function openRfidTagSelect(rowIndex) {
  currentEditingRowIndex.value = rowIndex
  rfidTagDialogVisible.value = true
}

/** 处理RFID标签选择确认 */
function handleRfidTagConfirm(selectedRfidTags) {
  if (selectedRfidTags.length > 0) {
    const rfidTag = selectedRfidTags[0]
    // 使用标签编码作为RFID标签值
    // form.value.items[currentEditingRowIndex.value].rfidTagIds = rfidTag.tagCode
    inventoryDetailList.value[currentEditingRowIndex.value].rfidTagIds = rfidTag.tagCode
  }
}

/** 处理物资选择确认 */
function handleMaterialConfirm(selectedMaterials) {
  if (selectedMaterials.length === 0) {
    proxy.$modal.msgWarning("请至少选择一个物资")
    return
  }

  // 将选中的物资添加到明细列表
  selectedMaterials.forEach(material => {
    const newItem = {
      materialId: material.materialId,
      materialName: material.materialName,
      planQuantity: null,
      actualQuantity: null,
      unit: material.unit,
      unitPrice: null,
      amount: null,
      batchNo: null,
      productionDate: null,
      expirationDate: null,
      qualityStatus: null,
      checkQuantity: null,
      unqualifiedQuantity: null,
      unqualifiedReason: null,
      storageLocation: null,
      warehouseId: null, // 仓库ID
      areaId: null, // 库区ID
      locationId: null, // 货架ID
      putawayStatus: '0', // 默认待上架
      remark: null
    }
  
    // 调用接口生成批次号
    generateBatchNo().then(response => {
        newItem.batchNo = response.msg;
       form.value.items.push(newItem)
    }).catch(error => {
      console.error('生成批次号失败:', error)
    })
  })
}

/** 计算明细金额 */
function calculateAmount(row) {
  // 实际数量 * 单价 = 金额
  if (row.actualQuantity && row.unitPrice) {
    // 计算金额并保留2位小数
    row.amount = Number((row.actualQuantity * row.unitPrice).toFixed(2))
  } else {
    row.amount = null
  }
  // 更新主表总数量和总金额
  updateTotal()
}

/** 更新主表总数量和总金额 */
function updateTotal() {
  if (!form.value.items || form.value.items.length === 0) {
    form.value.totalQuantity = 0
    form.value.totalAmount = 0
    return
  }
  
  // 计算总数量（实际数量之和）
  const totalQuantity = form.value.items.reduce((sum, item) => {
    return sum + (item.actualQuantity || 0)
  }, 0)
  
  // 计算总金额（金额之和）
  const totalAmount = form.value.items.reduce((sum, item) => {
    return sum + (item.amount || 0)
  }, 0)
  
  form.value.totalQuantity = totalQuantity
  form.value.totalAmount = totalAmount
}

/** 删除明细 */
function deleteDetail(index) {
  const item = form.value.items[index]
  if (item.itemId) {
    // 已有ID的明细，标记为删除
    item.delFlag = 1
    // 从显示列表中移除
    form.value.items.splice(index, 1)
  } else {
    // 新增的明细，直接删除
    form.value.items.splice(index, 1)
  }
  // 更新主表总数量和总金额
  updateTotal()
}

// 移除了编辑和保存明细的功能
// 所有修改直接在表单中进行，统一通过saveWmsInboundOrder保存

/** 删除按钮操作 */
function handleDelete(row) {
  const _orderIds = row.orderId || ids.value
  proxy.$modal.confirm('是否确认删除？').then(function () {
    return delWmsInboundOrder(_orderIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('ware/wmsInboundOrder/export', {
    ...queryParams.value
  }, `wmsInboundOrder_${new Date().getTime()}.xlsx`)
}

/** 打印按钮操作 */
function handlePrint(row) {
  // 获取完整的入库单数据，包括明细
  getWmsInboundOrder(row.orderId).then(response => {
    const orderData = response.data
    // 创建打印窗口
    const printWindow = window.open('', '_blank')

    // 构建打印内容
    let printContent = `
      <!DOCTYPE html>
      <html lang="zh-CN">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>入库单打印</title>
        <style>
          body {
            font-family: Arial, sans-serif;
            margin: 20px;
            padding: 20px;
            border: 1px solid #ccc;
          }
          h1 {
            text-align: center;
            color: #333;
            margin-bottom: 30px;
          }
          .order-info {
            margin-bottom: 20px;
            padding: 10px;
            border: 1px solid #eee;
          }
          .info-row {
            display: flex;
            margin-bottom: 10px;
          }
          .info-label {
            width: 120px;
            font-weight: bold;
            margin-right: 10px;
          }
          .table-container {
            margin-top: 20px;
          }
          table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
          }
          th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
          }
          th {
            background-color: #f2f2f2;
          }
          .footer {
            margin-top: 30px;
            text-align: right;
          }
        </style>
      </head>
      <body>
        <h1>入库单</h1>
        <div class="order-info">
          <div class="info-row">
            <span class="info-label">入库单号：</span>
            <span>${orderData.orderNo}</span>
          </div>
          <div class="info-row">
            <span class="info-label">仓库：</span>
            <span>${orderData.warehouseId}</span>
          </div>
          <div class="info-row">
            <span class="info-label">供应商：</span>
            <span>${orderData.supplierId}</span>
          </div>
          <div class="info-row">
            <span class="info-label">总数量：</span>
            <span>${orderData.totalQuantity}</span>
          </div>
          <div class="info-row">
            <span class="info-label">总金额：</span>
            <span>${orderData.totalAmount}</span>
          </div>
          <div class="info-row">
            <span class="info-label">申请人：</span>
            <span>${orderData.applicantId}</span>
          </div>
          <div class="info-row">
            <span class="info-label">申请时间：</span>
            <span>${orderData.applyTime ? new Date(orderData.applyTime).toLocaleDateString() : ''}</span>
          </div>
          <div class="info-row">
            <span class="info-label">备注：</span>
            <span>${orderData.remark || ''}</span>
          </div>
        </div>
        
        <div class="table-container">
          <h3>入库单明细</h3>
          <table>
            <thead>
              <tr>
                <th>物资名称</th>
                <th>计划数量</th>
                <th>实际数量</th>
                <th>单位</th>
                <th>单价</th>
                <th>金额</th>
                <th>批次号</th>
                <th>生产日期</th>
                <th>失效日期</th>
                <th>备注</th>
              </tr>
            </thead>
            <tbody>
    `

    // 添加明细数据
    if (orderData.items && orderData.items.length > 0) {
      orderData.items.forEach(detail => {
        printContent += `
          <tr>
            <td>${detail.materialName}</td>
            <td>${detail.planQuantity}</td>
            <td>${detail.actualQuantity}</td>
            <td>${detail.unit}</td>
            <td>${detail.unitPrice}</td>
            <td>${detail.amount}</td>
            <td>${detail.batchNo || ''}</td>
            <td>${detail.productionDate ? new Date(detail.productionDate).toLocaleDateString() : ''}</td>
            <td>${detail.expirationDate ? new Date(detail.expirationDate).toLocaleDateString() : ''}</td>
            <td>${detail.remark || ''}</td>
          </tr>
        `
      })
    } else {
      printContent += `
        <tr>
          <td colspan="10">无明细数据</td>
        </tr>
      `
    }

    // 完成打印内容
    printContent += `
            </tbody>
          </table>
        </div>
        
        <div class="footer">
          <p>打印时间：${new Date().toLocaleString()}</p>
        </div>
      </body>
      </html>
    `

    // 写入打印窗口
    printWindow.document.write(printContent)
    printWindow.document.close()

    // 执行打印
    printWindow.print()

    // 关闭打印窗口
    printWindow.close()
  })
}

function CreatePrintPage() {
  LODOP = getLodop(document.getElementById('LODOP1'), document.getElementById('LODOP_EM1'));
  LODOP.PRINT_INITA(0, 0, 800, 1600, "打印控件功能演示_Lodop功能_打印条码");
  LODOP.ADD_PRINT_BARCODE(28, 34, 307, 47, "128A", "123456789012");
  LODOP.ADD_PRINT_BARCODE(88, 32, 206, 78, "128B", "123456789012");
  LODOP.SET_PRINT_STYLEA(0, "FontSize", 18);
  LODOP.ADD_PRINT_BARCODE(107, 255, 161, 64, "128C", "888888");
  LODOP.SET_PRINT_STYLEA(0, "Color", "#FF0000");
  LODOP.ADD_PRINT_BARCODE(179, 42, 130, 47, "128Auto", "12345678901");
  LODOP.ADD_PRINT_BARCODE(252, 42, 153, 54, "EAN8", "12345678");
  LODOP.SET_PRINT_STYLEA(0, "Angle", 180);
  LODOP.ADD_PRINT_BARCODE(173, 244, 235, 172, "EAN13", "1234567890123");
  LODOP.SET_PRINT_STYLEA(0, "Angle", 35);
  LODOP.ADD_PRINT_BARCODE(351, 34, 360, 36, "EAN128A", "123456789012");
  LODOP.SET_PRINT_STYLEA(0, "ShowBarText", 0);
  LODOP.ADD_PRINT_BARCODE(403, 34, 360, 47, "EAN128B", "123456789012");
  LODOP.SET_PRINT_STYLEA(0, "AlignJustify", 2);
  LODOP.ADD_PRINT_BARCODE(462, 34, 360, 47, "EAN128C", "123456789012");
  LODOP.ADD_PRINT_BARCODE(513, 34, 360, 47, "Code39", "*123ABC4567890*");
  LODOP.SET_PRINT_STYLEA(0, "Color", "#0000FF");
  LODOP.ADD_PRINT_BARCODE(570, 34, 360, 47, "39Extended", "*1234567890*");
  LODOP.ADD_PRINT_BARCODE(621, 34, 360, 47, "2_5interleaved", "123456789012");
  LODOP.ADD_PRINT_BARCODE(677, 34, 360, 47, "2_5industrial", "123456789012");
  LODOP.ADD_PRINT_BARCODE(729, 34, 360, 47, "2_5matrix", "123456789012");
  LODOP.SET_PRINT_STYLEA(0, "Color", "#408080");
  LODOP.ADD_PRINT_BARCODE(787, 34, 360, 47, "UPC_A", "089600124569");
  LODOP.ADD_PRINT_BARCODE(844, 34, 135, 64, "UPC_E0", "08960007");
  LODOP.ADD_PRINT_BARCODE(65, 595, 45, 95, "UPC_E1", "1122333");
  LODOP.SET_PRINT_STYLEA(0, "Angle", 90);
  LODOP.ADD_PRINT_BARCODE(87, 676, 57, 122, "UPCsupp2", "12345");
  LODOP.SET_PRINT_STYLEA(0, "Angle", 90);
  LODOP.ADD_PRINT_BARCODE(359, 435, 78, 181, "UPCsupp5", "123456789012");
  LODOP.SET_PRINT_STYLEA(0, "Angle", 90);
  LODOP.ADD_PRINT_BARCODE(309, 579, 44, 238, "Code93", "BJ100080");
  LODOP.SET_PRINT_STYLEA(0, "Angle", 90);
  LODOP.ADD_PRINT_BARCODE(241, 663, 73, 246, "93Extended", "123456789012");
  LODOP.SET_PRINT_STYLEA(0, "Angle", -90);
  LODOP.ADD_PRINT_BARCODE(583, 419, 58, 251, "MSI", "123456789012");
  LODOP.SET_PRINT_STYLEA(0, "Color", "#FF00FF");
  LODOP.SET_PRINT_STYLEA(0, "ShowBarText", 0);
  LODOP.SET_PRINT_STYLEA(0, "Angle", 90);
  LODOP.ADD_PRINT_BARCODE(589, 504, 74, 270, "PostNet", "123456789012");
  LODOP.SET_PRINT_STYLEA(0, "Angle", 90);
  LODOP.ADD_PRINT_BARCODE(565, 626, 115, 253, "Codabar", "123456789012");
  LODOP.SET_PRINT_STYLEA(0, "Angle", 285);
  LODOP.ADD_PRINT_BARCODE(30, 405, 176, 67, "PDF417", "我是pdf417value");
  LODOP.ADD_PRINT_BARCODE(130, 434, 168, 146, "QRCode", "1234567890版本7的最大值是122个字符123123");
  LODOP.SET_PRINT_STYLEA(0, "GroundColor", "#0080FF");
};

function handleExportQrcode(row) {
  currentRow.value = row
  // 这里假设二维码内容是入库单号，实际项目中可以根据需求调整
  currentQrcodeValue.value = row.orderNo
  qrcodePrintDialogVisible.value = true
}

/** 处理二维码打印 */
function handleQrcodePrint(params) {
  const { width, height, qrcodeValue } = params
  
  // 使用LODOP打印二维码
  const LODOP = getLodop(document.getElementById('LODOP1'), document.getElementById('LODOP_EM1'))
  
  // 设置打印纸张大小（自定义纸张）
  // LODOP.PRINT_INITA(0, 0, width * 3.7795275591, height * 3.7795275591, '打印二维码')
  
  // 或者设置为标签打印模式
  LODOP.PRINT_INIT('打印二维码')
  LODOP.SET_PRINT_PAGESIZE(1, width * 10, height * 10, '自定义二维码标签')
  
  // 添加二维码
  // 参数：top, left, width, height, type, value
  // 注意：这里的单位是缇(1mm = 10缇)
  LODOP.ADD_PRINT_BARCODE(10, 10, width * 10 - 20, height * 10 - 20, 'QRCode', qrcodeValue)
  
  // 设置二维码样式
  LODOP.SET_PRINT_STYLEA(0, 'GroundColor', '#FFFFFF')
  
  // 执行打印
  LODOP.PRINT_DESIGN() // 打印设计模式，方便调整
  // LODOP.PRINT() // 直接打印
}

getList()
</script>