<template>
  <el-dialog
    title="调整入库明细信息"
    v-model="dialogVisible"
    width="1200px"
    append-to-body
  >
    <el-table :data="adjustInventoryDetailList" border style="width: 100%" height="600px">
      <el-table-column prop="wmsMaterial.materialName" label="物资名称" width="120" fixed="left" />
      <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="80">
        <template #default="scope">
          <span>{{ scope.row.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="locationId" label="货架" width="180">
        <template #default="scope">
          <LocationCascaderSelect 
            v-if="scope.row.isEditing"
            :model-value="{warehouseId: scope.row.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>
      <!-- PLT标签 -->
      <el-table-column prop="storageLocation" label="PTL标签" width="150">
        <template #default="scope">
          <div v-if="scope.row.isEditing">
            <el-input v-model="scope.row.storageLocation" placeholder="请选择PTL标签" size="small" readonly>
              <template #append>
                <el-button slot="append" type="primary" size="small" @click="openPtlTagSelect(scope.$index)">选择</el-button>
              </template>
            </el-input>
          </div>
          <span v-else>{{ scope.row.storageLocation || '-' }}</span>
        </template>
      </el-table-column>
      <!-- RFID标签 -->
      <el-table-column prop="rfidTagIds" label="RFID标签" width="150">
        <template #default="scope">
          <div v-if="scope.row.isEditing">
            <el-input v-model="scope.row.rfidTagCodes" placeholder="请选择RFID标签" size="small" readonly>
              <template #append>
                <el-button slot="append" type="primary" size="small" @click="openRfidTagSelect(scope.$index)">选择</el-button>
              </template>
            </el-input>
          </div>
          <span v-else>{{ scope.row.rfidTagCodes || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center" fixed="right">
        <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="dialogVisible = false">关 闭</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" />
  </el-dialog>
</template>

<script setup>
import { ref, computed, getCurrentInstance, watch, onMounted } from 'vue'
import { listWmsInboundOrderItem } from "@/api/ware/wmsInboundOrderItem"
import { updateWmsInboundOrderItem, delWmsInboundOrderItem } from "@/api/ware/wmsInboundOrder"
import LocationCascaderSelect from "@/components/LocationCascaderSelect.vue"
import RfidTagSelectDialog from "@/components/RfidTagSelectDialog.vue"
import PtlTagSelectDialog from "@/components/PtlTagSelectDialog.vue"

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

const emit = defineEmits(['update:visible', 'detail-updated', 'detail-deleted', 'error'])

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

const { proxy } = getCurrentInstance()

// 当前调整的入库单
const currentAdjustOrder = ref(null)
// 入库明细调整列表
const adjustInventoryDetailList = ref([])
// RFID标签选择对话框状态
const rfidTagDialogVisible = ref(false)
const rfidTagSelectDialogRef = ref(null)
// PTL标签选择对话框状态
const ptlTagDialogVisible = ref(false)
const ptlTagSelectDialogRef = ref(null)
// 记录当前编辑的明细行索引
const currentEditingRowIndex = ref(-1)

// 监听orderId变化，加载明细数据
watch(
  () => props.orderId,
  (newId) => {
    if (newId && props.visible) {
      loadAdjustInventoryDetails()
    }
  }
)

// 监听visible变化，加载明细数据
watch(
  () => props.visible,
  (newVisible) => {
    if (newVisible && props.orderId) {
      loadAdjustInventoryDetails()
    }
  }
)

// 加载调整入库明细
function loadAdjustInventoryDetails() {
  if (!props.orderId) {
    return
  }
  
  listWmsInboundOrderItem({ orderId: props.orderId, pageSize: 1000, pageNum: 1 }).then(response => {
    adjustInventoryDetailList.value = response.rows.map(item => ({
      ...item,
      isEditing: false // 添加编辑状态标志
    }))
  }).catch(error => {
    proxy.$message.error('查询入库明细失败：' + error.message)
    emit('error', error)
  })
}

// 编辑明细
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
    emit('detail-updated', row)
  }).catch(error => {
    proxy.$message.error('保存失败：' + error.message)
    // 恢复原始值
    if (row.originalData) {
      Object.assign(row, row.originalData)
      delete row.originalData
    }
    emit('error', error)
  })
}

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

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

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

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

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