<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.material?.materialCode }}
        </el-descriptions-item>
        <el-descriptions-item label="物资名称">
          {{ detail.material?.materialName }}
        </el-descriptions-item>
        <el-descriptions-item label="规格型号">
          {{ detail.material?.specification }}
        </el-descriptions-item>
        <el-descriptions-item label="计划出库数量">
          <span class="planned-quantity">{{ detail.planQuantity }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="实际出库数量">
          <span class="actual-quantity">{{ detail.actualQuantity }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="拣货状态">
          <span class="picked-status">
             <dict-tag :options="out_order_status" :value="detail.pickingStatus" />
          </span>
        </el-descriptions-item>
      </el-descriptions>
    </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="index" label="序号" width="60" align="center" fixed="left" />
        <el-table-column label="RFID标签" align="center" prop="rfidCode" />
        <el-table-column label="批次号" align="center" prop="batchNo" width="120" />
        <el-table-column label="仓库" align="center" prop="warehouse.warehouseName" />
        <el-table-column label="库区" align="center" prop="area.areaName" />
        <el-table-column label="货架" align="center" prop="location.locationName" />
        <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="110">
          <template #default="scope">
            <span>{{ parseTime(scope.row.outboundTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否撤销" align="center" prop="isCanceled">
          <template #default="scope">
              <dict-tag :options="is_cancel" :value="scope.row.isCanceled" />
          </template>
        </el-table-column>
        <el-table-column label="撤销时间" align="center" prop="cancelTime" width="110">
          <template #default="scope">
            <span>{{ parseTime(scope.row.cancelTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
            <el-button link v-if="scope.row.isCanceled === '0'" type="primary" @click="handleCancelByRelation(scope.row)">撤销</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"
import useUserStore from '@/store/modules/user'
import { cancelByRelationId } from '@/api/ware/wmsOutboundOrder'

const { proxy } = getCurrentInstance()
const { outbound_type, out_order_status, is_cancel } = proxy.useDict('outbound_type', 'out_order_status', 'is_cancel')

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const userStore = useUserStore()
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.material?.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.isCanceled === '1').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 = (outboundOrderItem) => {
  detail.value = outboundOrderItem
  listWmsOutboundItemInventory({
    itemId: outboundOrderItem.itemId,
    pageNum: 1,
    pageSize: 1000
  }).then(res => {
    transactions.value = res.rows || []
  })
}

/**
 * 撤销关联流水
 * @param row 关联流水行数据
 */
const handleCancelByRelation = async (row) => {
  try {
    const result = await cancelByRelationId(row, userStore.id)

    if (result.code !== 200) {
      ElMessage.error(result.msg || '撤销失败')
      return
    }
    row.isCanceled = '1'
    ElMessage.success('已撤销成功')
  } catch (error) {
    console.error('撤销失败:', error)
    ElMessage.error('撤销失败')
  }
}

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: 120px;
  font-weight: 500;
}

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