<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="orderType">
        <el-select v-model="queryParams.orderType" placeholder="请选择入库类型">
          <el-option v-for="item in inbound_type" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </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="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择状态">
          <el-option v-for="item in in_order_status" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </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="仓库" align="center" prop="warehouseName" />
      <el-table-column label="供应商" align="center" prop="supplierName" />
      <el-table-column label="关联单号" align="center" prop="relatedOrderNo" width="180" />
      <!-- <el-table-column label="总数量" align="center" prop="totalQuantity" /> -->
      <el-table-column label="总金额(元)" align="center" prop="totalAmount" />
      <el-table-column label="状态" align="center" prop="orderStatus">
        <template #default="scope">
          <dict-tag :options="in_order_status" :value="scope.row.orderStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="center" prop="applicantUserName" />
      <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">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expectedArrivalDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" width="200" />
      <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="showAdjustBtn(scope.row)" 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="orderType">
              <el-radio-group v-model="form.orderType">
                <el-radio v-for="(item, index) in inbound_type" :key="index" :label="item.value">{{ item.label }}</el-radio>
              </el-radio-group>
            </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.warehouseName" 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-row>
        <el-row :gutter="20">
           <el-col :span="8">
            <el-form-item label="供应商" prop="supplierId">
              <el-row :gutter="10">
                <el-col :span="18">
                  <el-input v-model="form.supplierName" 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-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="applicantId">
              <el-input v-model="form.applicantName" placeholder="请输入操作人" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
         
          <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="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="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  type="primary" size="small" icon="Plus" @click="addDetail">添加明细</el-button>
          </el-col>
        </el-row>
        <el-table :data="form.itemDetails" border style="width: 100%" height="400">
          <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="materialCode" label="物资编号" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.materialCode" placeholder="请输入物资编号" size="small" disabled />
            </template>
          </el-table-column>
          <el-table-column prop="specification" label="规格型号">
            <template #default="scope">
              <el-input v-model="scope.row.specification" placeholder="请输入规格型号" size="small" disabled />
            </template>
          </el-table-column>
          <el-table-column prop="planQuantity" label="计划数量" width="150">
            <template #default="scope">
              <el-input 
                v-model.number="scope.row.planQuantity" 
                placeholder="请输入计划数量" 
                size="small" 
                type="number" 
                @change="calculateAmount(scope.row)"
                :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="180">
            <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="180">
            <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="remark" label="备注">
            <template #default="scope">
              <el-input type="textarea" v-model="scope.row.remark" placeholder="请输入备注" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center" fixed="right">
            <template #default="scope">
              <el-button type="danger" size="small" icon="Delete" @click="deleteDetail(scope.$index)">
                {{ scope.row.delFlag === '1' ? '撤销删除' : '标记删除' }}
              </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" />

    <!-- 入库对话框 -->
    <InventoryDialog
      ref="inventoryDialogRef"
      v-model:visible="inventoryDialogVisible"
      :current-order="currentInventoryOrder"
      @inventory-success="getList"
    />

    <!-- 入库明细调整对话框 -->
    <AdjustInventoryDialog
      v-model:visible="adjustInventoryDialogVisible"
      :order-id="currentAdjustOrder?.orderId"
      :current-order="currentAdjustOrder"
      @detail-updated="getList"
    />
  </div>
</template>

<script setup name="WmsInboundOrder">
import { listWmsInboundOrder, getWmsInboundOrder, delWmsInboundOrder, saveWmsInboundOrder } from "@/api/ware/wmsInboundOrder"
import { generateInboundOrderNo } from "@/api/ware/codeGenerator"
import MaterialSelectDialog from "@/components/MaterialSelectDialog.vue"
import WarehouseSelectDialog from "@/components/WarehouseSelectDialog.vue"
import SupplierSelectDialog from "@/components/SupplierSelectDialog.vue"
import InventoryDialog from "./components/InventoryDialog.vue"
import AdjustInventoryDialog from "./components/AdjustInventoryDialog.vue"
import useUserStore from '@/store/modules/user'
import { dayjs } from "element-plus"


const { proxy } = getCurrentInstance()

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

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 inventoryDialogRef = ref(null)

// 入库对话框状态
const inventoryDialogVisible = ref(false)
// 当前入库的入库单
const currentInventoryOrder = ref(null)

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

// 当前选中的入库单
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
  inventoryDialogVisible.value = true
  inventoryDialogRef.value?.openDialog(currentInventoryOrder.value)
}

// 调整已入库信息相关方法
// 打开调整入库信息对话框
function handleAdjustInventory(row) {
  currentAdjustOrder.value = row
  adjustInventoryDialogVisible.value = true
}



/** 查询入库单列表 */
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,
    itemDetails: []
  }
  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.applicantName = userStore.nickName
  // 设置申请时间为当前时间
  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
    form.value.warehouseName = warehouse.warehouseName
    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
    form.value.supplierName = supplier.supplierName
    // 可以根据需要添加更多供应商信息字段
  }
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _orderId = row.orderId || ids.value
  getWmsInboundOrder(_orderId).then(response => {
    form.value = response.data

    form.value.itemDetails?.forEach(item => {
      item.materialName = item.wmsMaterial?.materialName || ''
      item.materialCode = item.wmsMaterial?.materialCode || ''
      item.specification = item.wmsMaterial?.specification || ''
    })

    open.value = true
    title.value = "修改入库单"
  })
}

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

      // 验证每条明细的必填字段
      for (let i = 0; i < form.value.itemDetails.length; i++) {
        const detail = form.value.itemDetails[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.itemDetails) {
    form.value.itemDetails = []
  }
  // 打开物资选择对话框
  materialDialogVisible.value = true
  // 调用组件方法加载物资分类和列表
  materialSelectDialogRef.value.getTreeselect()
  materialSelectDialogRef.value.handleQuery()
}



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

  // 将选中的物资添加到明细列表
  selectedMaterials.forEach(material => {
    const newItem = {
      materialId: material.materialId,
      materialName: material.materialName,
      materialCode: material.materialCode,
      specification: material.specification,
      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,
      delFlag: '0'
    }
    form.value.itemDetails.push(newItem)
  })
}

/** 计算明细金额 */
function calculateAmount(row) {
  // 计划数量 * 单价 = 金额
  if (row.planQuantity && row.unitPrice) {
    // 计算金额并保留2位小数
    row.amount = Number((row.planQuantity * row.unitPrice).toFixed(2))
  } else {
    row.amount = null
  }
}

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

/** 删除明细 */
function deleteDetail(index) {
  const item = form.value.itemDetails[index]
  if (item.itemDetailId) {
    // 已有ID的明细，标记为删除
    item.delFlag = item.delFlag === '1' ? '0' : '1'
  } else {
    // 新增的明细，直接删除
    form.value.itemDetails.splice(index, 1)
  }
}

// 移除了编辑和保存明细的功能
// 所有修改直接在表单中进行，统一通过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 handlePrint(row) {
  // 获取完整的入库单数据，包括明细
  getWmsInboundOrder(row.orderId).then(response => {
    const orderData = response.data

    orderData.itemDetails.forEach(item => {
      item.actualAmount =  item.actualQuantity ? (item.actualQuantity * item.unitPrice).toFixed(2) : ''
    })

    // 创建打印窗口
    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>
          @media print {
            size: landscape;
          }
          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;
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
          }
          .info-row {
            display: flex;
            flex-direction: column;
          }
          .info-label {
            font-weight: bold;
            margin-bottom: 5px;
          }
          .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.warehouseName}</span>
          </div>
          <div class="info-row">
            <span class="info-label">供应商：</span>
            <span>${orderData.supplierName || ''}</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.applicantUserName}</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>
              </tr>
            </thead>
            <tbody>
    `

    // 添加明细数据
    if (orderData.itemDetails && orderData.itemDetails.length > 0) {
      orderData.itemDetails.forEach(detail => {
        printContent += `
          <tr>
            <td>${detail.wmsMaterial?.materialName}</td>
            <td>${detail.wmsMaterial?.materialCode}</td>
            <td>${detail.wmsMaterial?.specification}</td>
            <td>${detail.planQuantity}</td>
            <td>${detail.amount}</td>
            <td>${detail.unit}</td>
            <td>${detail.unitPrice}</td>
            <td>${detail.actualQuantity || ''}</td>
            <td>${detail.actualAmount || ''}</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 handleExportQrcode(row) {
  currentRow.value = row
  // 这里假设二维码内容是入库单号，实际项目中可以根据需求调整
  currentQrcodeValue.value = row.orderNo
  qrcodePrintDialogVisible.value = true
}

function showAdjustBtn(row) {
  // 当订单状态不是'0'且操作时间（applyTime）小于等于7天时显示调整按钮
  return row.orderStatus !== '0' && dayjs(row.applyTime).isSameOrAfter(dayjs().subtract(7, 'day'))
}

getList()
</script>