<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="1200px"
    :close-on-click-modal="false"
  >
    <!-- 物资信息摘要 -->
    <div v-if="detail" class="material-summary">
      <el-descriptions :column="3" border size="small">
        <el-descriptions-item label="物资编码">
          {{ detail.materialCode }}
        </el-descriptions-item>
        <el-descriptions-item label="物资名称">
          {{ detail.materialName }}
        </el-descriptions-item>
        <el-descriptions-item label="规格型号">
          {{ detail.specification }}
        </el-descriptions-item>
        <el-descriptions-item label="计划数量">
          <span class="planned-quantity">{{ detail.plannedQuantity }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="实际出库">
          <span :class="{
            'completed': detail.actualQuantity >= detail.plannedQuantity,
            'in-progress': detail.actualQuantity > 0 && detail.actualQuantity < detail.plannedQuantity
          }">
            {{ detail.actualQuantity }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="剩余需求">
          <span class="remaining-need">
            {{ Math.max(0, detail.plannedQuantity - detail.actualQuantity) }}
          </span>
        </el-descriptions-item>
      </el-descriptions>
      
      <el-progress 
        :percentage="completionPercentage"
        :status="completionPercentage >= 100 ? 'success' : 'primary'"
        :stroke-width="12"
        style="margin-top: 15px;"
      />
    </div>

    <!-- 批次出库记录 -->
    <div class="batch-transactions">
      <div class="section-header">
        <h4>批次出库记录</h4>
        <span class="total-info">
          共 {{ transactions.length }} 个批次
        </span>
      </div>
      
      <el-table
        :data="transactions"
        stripe
        border
        size="small"
        height="300px"
      >
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column type="index" label="序号" width="60" align="center" fixed="left" />
      <el-table-column label="关联ID" align="center" prop="relationId" />
      <el-table-column label="出库明细ID" align="center" prop="itemId" />
      <el-table-column label="出库单ID" align="center" prop="orderId" />
      <el-table-column label="库存ID" align="center" prop="inventoryId" />
      <el-table-column label="RFID标签ID" align="center" prop="rfidTagId" />
      <el-table-column label="RFID编码" align="center" prop="rfidCode" />
      <el-table-column label="EPC编码" align="center" prop="epcCode" />
      <el-table-column label="TID编码" align="center" prop="tidCode" />
      <el-table-column label="物资ID" align="center" prop="materialId" />
      <el-table-column label="批次号" align="center" prop="batchNo" width="120" />
      <el-table-column label="仓库id" align="center" prop="warehouseId" />
      <el-table-column label="库区id" align="center" prop="areaId" />
      <el-table-column label="库位ID" align="center" prop="locationId" />
      <el-table-column label="数量" align="center" prop="quantity" />
      <el-table-column label="单位成本" align="center" prop="unitCost" />
      <el-table-column label="出库时间" align="center" prop="outboundTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.outboundTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否已撤销" align="center" prop="isCanceled" />
      <el-table-column label="撤销时间" align="center" prop="cancelTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.cancelTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="撤销人" align="center" prop="cancelBy" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['ware:wmsOutboundItemInventory:remove']">撤销</el-button>
        </template>
      </el-table-column>
      </el-table>
    </div>

    <!-- 汇总信息 -->
    <div class="summary-section">
      <el-descriptions :column="4" border size="small">
        <el-descriptions-item label="批次总数">
          <span class="summary-value">{{ batchCount }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="正常出库">
          <span class="summary-value success">
            {{ normalTransactionCount }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="已撤销">
          <span class="summary-value danger">
            {{ reversedTransactionCount }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="合计数量">
          <span class="summary-value highlight">
            {{ totalAmount }}
          </span>
        </el-descriptions-item>
      </el-descriptions>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">关闭</el-button>
        <el-button 
          v-if="detail?.actualQuantity < detail?.plannedQuantity"
          type="primary"
          @click="handleContinueOutbound"
        >
          继续出库
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { Close } from '@element-plus/icons-vue'
import { listWmsOutboundItemInventory } from "@/api/ware/wmsOutboundItemInventory"
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const detail = ref({})
const transactions = ref([])

const emit = defineEmits()

// 响应式数据
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 计算属性
const dialogTitle = computed(() => {
  if (!detail.value) return '批次详情'
  return `${detail.value.materialName} - 批次出库详情`
})

const completionPercentage = computed(() => {
  if (!detail.value || detail.value.plannedQuantity === 0) return 0
  return Math.min((detail.value.actualQuantity / detail.value.plannedQuantity) * 100, 100)
})

const batchCount = computed(() => {
  const batchNos = new Set(transactions.value.map(t => t.batchNo))
  return batchNos.size
})

const normalTransactionCount = computed(() => {
  return transactions.value.filter(t => t.isCanceled === '0').length
})

const reversedTransactionCount = computed(() => {
  return transactions.value.filter(t => t.status === 'REVERSED').length
})

const totalAmount = computed(() => {
  return transactions.value
    .filter(t => t.isCanceled === '0')
    .reduce((sum, t) => sum + t.quantity, 0)
})

// 方法
const formatTime = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const formatAmount = (amount) => {
  return amount.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

const handleContinueOutbound = () => {
  emit('continue-outbound')
  visible.value = false
}

const openDialog = (row) => {
  detail.value = row
  listWmsOutboundItemInventory({
    orderId: row.orderId,
    pageNum: 1,
    pageSize: 1000
  }).then(res => {
    transactions.value = res.rows || []
  })
}
defineExpose({
  openDialog
})
</script>

<style scoped>
.material-summary {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8fafc;
  border-radius: 6px;
}

.planned-quantity {
  font-weight: 600;
  color: #303133;
}

.completed {
  color: #67c23a;
  font-weight: 600;
}

.in-progress {
  color: #e6a23c;
  font-weight: 600;
}

.remaining-need {
  color: #f56c6c;
  font-weight: 600;
}

.batch-transactions {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.section-header h4 {
  margin: 0;
  color: #303133;
  font-weight: 600;
}

.total-info {
  color: #606266;
  font-size: 14px;
}

.batch-no-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.batch-no {
  font-family: 'Monaco', 'Consolas', monospace;
  font-size: 13px;
}

.quantity-cell {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 5px;
}

.quantity-cell.reversed {
  text-decoration: line-through;
  color: #f56c6c;
}

.amount-cell.reversed {
  text-decoration: line-through;
  color: #f56c6c;
}

.summary-section {
  margin-top: 20px;
}

.summary-value {
  font-weight: 500;
  color: #303133;
}

.summary-value.success {
  color: #67c23a;
}

.summary-value.danger {
  color: #f56c6c;
}

.summary-value.highlight {
  color: #f56c6c;
  font-size: 16px;
  font-weight: 600;
}

:deep(.el-descriptions__label) {
  width: 80px;
  font-weight: 500;
}

:deep(.el-descriptions__content) {
  font-weight: 400;
}
</style>