<template>
  <el-dialog title="入库操作" v-model="dialogVisible" fullscreen append-to-body>
    <el-form :model="inventoryQueryParams" ref="inventoryQueryRef" :inline="true" label-width="120px" v-if="showSearch">
      <el-form-item label="物资编码/名称" prop="materialCodeOrName">
        <el-input v-model="inventoryQueryParams.materialCodeOrName" placeholder="请输入物资编码/名称" clearable
          @keyup.enter="handleInventoryQuery" @input="handleMaterialCodeOrNameInput" />
      </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 ref="inventoryTableRef" :data="inventoryDetailList" row-key="itemDetailId" border height="calc(100vh - 200px)"
      @expand-change="handleExpandChange">
      <el-table-column type="expand" fixed="left">
        <template #default="props">
          <el-table :data="props.row.inBoundItem" row-key="itemId" border>
            <el-table-column prop="batchNo" label="批次号" width="150" />
            <el-table-column prop="actualQuantity" label="入库数量">
              <template #default="scope">
                <el-tag type="success" effect="dark">{{ scope.row.actualQuantity }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="unitPrice" label="单价(元)" />
            <el-table-column label="金额(元)"  prop="amount" />
            <el-table-column label="仓库/库区/货架">
              <template #default="scope">
                {{ scope.row.wmsWarehouse?.warehouseName || '-' }}/{{ scope.row.wmsArea?.areaName || '-' }}/{{ scope.row.wmsLocation?.locationName || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="storageLocation" label="PTL标签" />
            <el-table-column prop="rfidTagIds" label="RFID标签" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" fixed="right">
              <template #default="scope">
                <el-button link type="primary" @click="handleDelDetail(scope.row)">移除</el-button>
                <el-button link type="primary" @click="handleEditDetail(scope.row)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column prop="wmsMaterial.materialName" label="物资名称" width="150" />
      <el-table-column prop="wmsMaterial.materialCode" label="物资编码" width="150" />
      <el-table-column prop="wmsMaterial.specification" label="规格型号" width="150" />
      <el-table-column prop="planQuantity" label="计划入库" width="100" >
        <template #default="scope">
          <el-tag type="primary" effect="dark" class="bg-[#409eff] border-[#409eff]">{{ scope.row.planQuantity }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="actualQuantity" label="实际入库" width="100">
        <template #default="scope">
          <el-tag type="success" effect="dark" v-if="scope.row.actualQuantity">{{ scope.row.actualQuantity }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="unitPrice" label="单价(元)" width="100" />
      <el-table-column prop="unit" label="计量单位" />
      <el-table-column label="计划金额(元)" width="100" prop="amount" />
      <el-table-column prop="remark" label="备注">
        <template #default="scope">
          {{ scope.row.remark }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleAddInBoundItem(scope.row)">添加入库</el-button>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
    <!-- 添加入库明细对话框组件 -->
    <AddInBoundItemDialog ref="addInBoundItemDialogRef" @submit="handleAddInBoundItemSubmit" />
  </el-dialog>
</template>

<script setup>
import { ref, computed, getCurrentInstance, nextTick } from 'vue'
import { listWmsInboundOrderItemDetail, getWmsInboundOrderItemDetail } from "@/api/ware/wmsInboundOrderItemDetail"
import { addToInventory } from "@/api/ware/wmsInboundOrder"
import QrcodePrintDialog from "@/components/QrcodePrintDialog.vue"
import LocationCascaderSelect from "@/components/LocationCascaderSelect.vue"
import AddInBoundItemDialog from "@/views/ware/wmsInboundOrder/components/AddInBoundItemDialog.vue"
import { listWmsInboundOrderItem } from "@/api/ware/wmsInboundOrderItem"
import { delWmsInboundOrderItem, updateWmsInboundOrderItem } from "@/api/ware/wmsInboundOrder"

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 showSearch = ref(false)

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

const inboundOrder = ref(null)
// 添加入库明细对话框状态
const addInBoundItemDialogRef = ref(null)
const currentInBoundOrderItemDetail = ref(null)
// 表格 ref
const inventoryTableRef = ref(null)

const expandedRows = ref(new Set())

// 入库明细查询
function handleInventoryQuery() {
  listWmsInboundOrderItemDetail({ orderId: inboundOrder.value.orderId }).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 handleClose() {
  dialogVisible.value = false
}

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

function handleAddInBoundItem(row) {
  if (row.planQuantity == row.actualQuantity) {
    proxy.$message.warning('计划入库数量等于实际入库数量，无需添加入库')
    return
  }
  row.warehouseId = inboundOrder.value.warehouseId
  currentInBoundOrderItemDetail.value = row
  addInBoundItemDialogRef.value?.handleAdd(row)
}

function handleEditDetail(row) {
  currentInBoundOrderItemDetail.value = row
  addInBoundItemDialogRef.value?.handleUpdate(row)
}

function handleAddInBoundItemSubmit(inBoundOrderItem) {
  if (inBoundOrderItem.itemId) {

    // 调用更新接口
    updateWmsInboundOrderItem(inBoundOrderItem).then(response => {
     // 获取当前行
      const currentRow = inventoryDetailList.value.find(item => item.itemDetailId === inBoundOrderItem.itemDetailId)
      getWmsInboundOrderItemDetail(currentRow.itemDetailId).then(response => {
        currentRow.actualQuantity = response.data?.actualQuantity
      })
      // 使用 toggleRowExpansion 方法处理展开收缩
      if (inventoryTableRef.value) {
        // 先收缩
        inventoryTableRef.value.toggleRowExpansion(currentRow, false)
        // 再展开
        nextTick(() => {
          inventoryTableRef.value.toggleRowExpansion(currentRow, true)
        })
      }
      proxy.$message.success('保存成功')
      emit('inventory-success')
    }).catch(error => {
      emit('inventory-error', error)
    })
  } else {
    inBoundOrderItem.itemDetailId = currentInBoundOrderItemDetail.value.itemDetailId
    const orderData = { ...props.currentOrder, items: [inBoundOrderItem] }
    addToInventory(orderData).then(response => {
      proxy.$message.success('入库成功')

      // 获取当前行
      const currentRow = currentInBoundOrderItemDetail.value

      currentInBoundOrderItemDetail.value.actualQuantity += inBoundOrderItem.actualQuantity

      // 使用 toggleRowExpansion 方法处理展开收缩
      if (inventoryTableRef.value) {
        // 先收缩
        inventoryTableRef.value.toggleRowExpansion(currentRow, false)
        // 再展开
        nextTick(() => {
          inventoryTableRef.value.toggleRowExpansion(currentRow, true)
        })
      }
      emit('inventory-success')
    }).catch(error => {
      proxy.$message.error('入库失败：' + error.message)
      emit('inventory-error', error)
    })
  }
}

function loadOutboundItemDetail(row) {
  listWmsInboundOrderItem({ itemDetailId: row.itemDetailId }).then(response => {
    if (response.rows.length) {
      row.inBoundItem = response.rows;
    }
  }).catch(error => {
    proxy.$message.error('查询入库明细失败：' + error.message)
    emit('inventory-error', error)
  })
}

function handleExpandChange(row, currentExpandedRows) {
  // 维护expandedRows集合
  if (currentExpandedRows.includes(row)) {
    expandedRows.value.add(row.itemDetailId)
    // 展开时加载交易记录
    loadOutboundItemDetail(row)
  } else {
    expandedRows.value.delete(row.itemDetailId)
    // 收起时清空交易记录
    row.inBoundItem = []
  }
}

function handleDelDetail(row) {
  proxy.$messageBox.confirm('确定移除当前入库吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    delWmsInboundOrderItem(row.orderId, row.itemId).then(response => {

      // 获取当前行
      const currentRow = inventoryDetailList.value.find(item => item.itemDetailId === row.itemDetailId)

      getWmsInboundOrderItemDetail(currentRow.itemDetailId).then(response => {
        currentRow.actualQuantity = response.data?.actualQuantity
      })

      // 使用 toggleRowExpansion 方法处理展开收缩
      if (inventoryTableRef.value) {
        // 先收缩
        inventoryTableRef.value.toggleRowExpansion(currentRow, false)
        // 再展开
        nextTick(() => {
          inventoryTableRef.value.toggleRowExpansion(currentRow, true)
        })
      }

      proxy.$message.success('删除成功')
      emit('inventory-success')
    }).catch(error => {
      proxy.$message.error('删除失败：' + error.message)
      emit('inventory-error', error)
    })
  }).catch(() => {
    // 取消操作
  })
}

defineExpose({
  openDialog
})
</script>
