<template>
  <el-dialog title="入库操作" v-model="dialogVisible" 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="wmsMaterial.materialName" label="物资名称" width="200" />
      <el-table-column prop="batchNo" label="批次号" width="150" />
      <el-table-column prop="planQuantity" label="计划数量" width="100" />
      <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="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="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="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmInventory">确认入库</el-button>
      </div>
    </template>

    <!-- 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>
</template>

<script setup>
import { ref, computed, getCurrentInstance } from 'vue'
import { listWmsInboundOrderItem } from "@/api/ware/wmsInboundOrderItem"
import { addToInventory } from "@/api/ware/wmsInboundOrder"
import RfidTagSelectDialog from "@/components/RfidTagSelectDialog.vue"
import PtlTagSelectDialog from "@/components/PtlTagSelectDialog.vue"
import QrcodePrintDialog from "@/components/QrcodePrintDialog.vue"

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  currentOrder: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:visible', 'inventory-success', 'inventory-error'])

const dialogVisible = computed({
  get() {
    return props.visible
  },
  set(value) {
    emit('update:visible', value)
  }
})

const { proxy } = getCurrentInstance()

// 入库查询参数
const inventoryQueryParams = ref({
  batchNo: null
})

// 入库明细列表
const inventoryDetailList = ref([])

const inboundOrder = ref(null)

// RFID标签选择对话框状态
const rfidTagDialogVisible = ref(false)
const rfidTagSelectDialogRef = ref(null)
// PTL标签选择对话框状态
const ptlTagDialogVisible = ref(false)
const ptlTagSelectDialogRef = ref(null)
// 二维码打印对话框状态
const qrcodePrintDialogVisible = ref(false)
const qrcodePrintDialogRef = ref(null)
// 记录当前编辑的明细行索引
const currentEditingRowIndex = ref(-1)
// 当前要打印的二维码值
const currentQrcodeValue = ref('')

// 处理批次号输入（支持扫描枪）
function handleBatchNoInput() {
  if (inventoryQueryParams.value.batchNo && inventoryQueryParams.value.batchNo.endsWith('\n')) {
    inventoryQueryParams.value.batchNo = inventoryQueryParams.value.batchNo.trim()
    handleInventoryQuery()
  }
}

// 计算金额（数量 * 单价）
function calculateAmount(row) {
  if (row && row.actualQuantity !== undefined && row.unitPrice !== undefined) {
    // 确保数量和单价都是数字
    const quantity = parseFloat(row.actualQuantity) || 0;
    const unitPrice = parseFloat(row.unitPrice) || 0;
    // 计算金额，保留2位小数
    row.amount = parseFloat((quantity * unitPrice).toFixed(2));
  }
}

// 入库明细查询
function handleInventoryQuery() {
  listWmsInboundOrderItem({ batchNo: inventoryQueryParams.value.batchNo, orderId: inboundOrder.value.orderId, putawayStatus: '0' }).then(response => {
    if (response.rows.length) {
      inventoryDetailList.value = response.rows;
    } else {
      proxy.$message.warning('未查询到相关入库明细或已全部入库')
    }
  }).catch(error => {
    proxy.$message.error('查询入库明细失败：' + error.message)
    emit('inventory-error', error)
  })
}

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

// 确认入库
function confirmInventory() {
  if (inventoryDetailList.value.length === 0) {
    proxy.$message.warning('请先添加入库明细')
    return
  }
  
  // 确认前重新计算所有行的金额，确保数据准确性
  inventoryDetailList.value.forEach(item => {
    calculateAmount(item);
  });

  proxy.$messageBox.confirm('确定要执行入库操作吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const orderData = { ...props.currentOrder, items: inventoryDetailList.value }
    addToInventory(orderData).then(response => {
      proxy.$message.success('入库成功')
      dialogVisible.value = false
      emit('inventory-success')
    }).catch(error => {
      proxy.$message.error('入库失败：' + error.message)
      emit('inventory-error', error)
    })
  }).catch(() => {
    // 取消操作
  })
}

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

// 处理RFID标签选择确认
function handleRfidTagConfirm(selectedTags) {
  if (currentEditingRowIndex.value >= 0 && inventoryDetailList.value[currentEditingRowIndex.value]) {
    inventoryDetailList.value[currentEditingRowIndex.value].rfidTagIds = selectedTags.map(tag => tag.tagId).join(',')
  }
  currentEditingRowIndex.value = -1
}

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

// 处理PTL标签选择确认
function handlePtlTagConfirm(selectedTags) {
  if (currentEditingRowIndex.value >= 0 && inventoryDetailList.value[currentEditingRowIndex.value]) {
    inventoryDetailList.value[currentEditingRowIndex.value].storageLocation = selectedTags.map(tag => tag.antennaId).join(',')
  }
  currentEditingRowIndex.value = -1
}

// 导出二维码
function handleExportQrcode(row) {
  currentQrcodeValue.value = JSON.stringify({
    orderItemId: row.wmsInboundOrderItemId,
    materialName: row.wmsMaterial.materialName,
    batchNo: row.batchNo,
    quantity: row.actualQuantity
  })
  qrcodePrintDialogVisible.value = true
}

// 处理二维码打印
function handleQrcodePrint() {
  proxy.$message.success('二维码打印成功')
}

function openDialog(currentInboundOrder) {
  inboundOrder.value = currentInboundOrder
  handleInventoryQuery()
}

defineExpose({
  openDialog
})
</script>
