<template>
  <div class="delivery-report" v-loading="loading">
    <!-- 时间筛选 -->
    <div class="filter-container">
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd"
        :default-time="['00:00:00', '23:59:59']"
        @change="handleDateChange"
      />
      <el-button type="primary" @click="getReport">查询</el-button>
      <el-button @click="resetDate">重置</el-button>
    </div>

    <!-- 汇总信息 -->
    <el-card class="summary-card" v-if="summary">
      <template #header>
        <div class="card-header">
          <span>发货报表汇总</span>
        </div>
      </template>
      <el-descriptions :column="2" border>
        <!-- <el-descriptions-item label="总运单数">{{ summary.waybillCount || 0 }}</el-descriptions-item> -->
        <el-descriptions-item label="总卷数">{{ summary.coilCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="总重量(吨)">{{ formatWeight(summary.totalWeight) }}</el-descriptions-item>
        <!-- <el-descriptions-item label="日均运单数">{{ formatDailyValue(summary.dailyWaybillCount) }}</el-descriptions-item> -->
        <el-descriptions-item label="日均卷数">{{ formatDailyValue(summary.dailyCoilCount) }}</el-descriptions-item>
        <el-descriptions-item label="日均重量(吨)">{{ formatWeight(summary.dailyWeight) }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ summary.startTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ summary.endTime || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 详细数据表格 -->
    <el-card class="table-card" v-if="details && details.length > 0">
      <template #header>
        <div class="card-header">
          <span>产品发货计划</span>
          <span>共 {{ details.length }} 个计划</span>
        </div>
      </template>
      <el-table
        :data="details"
        style="width: 100%"
        stripe
        v-loading="loading"
      >
        <el-table-column prop="productName" label="计划名称" min-width="120" fixed="left" />
        <!-- <el-table-column prop="waybillCount" label="运单数量" min-width="100" align="center">
          <template #default="{ row }">
            <span>{{ row.waybillCount || 0 }}</span>
          </template>
        </el-table-column> -->
        <el-table-column prop="coilCount" label="卷数" min-width="100" align="center">
          <template #default="{ row }">
            <span>{{ row.coilCount || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalWeight" label="总重量(吨)" min-width="120" align="right">
          <template #default="{ row }">
            <span>{{ formatWeight(row.totalWeight) }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="dailyWaybillCount" label="日均运单数" min-width="120" align="right">
          <template #default="{ row }">
            <span>{{ formatDailyValue(row.dailyWaybillCount) }}</span>
          </template>
        </el-table-column> -->
        <el-table-column prop="dailyCoilCount" label="日均卷数" min-width="120" align="right">
          <template #default="{ row }">
            <span>{{ formatDailyValue(row.dailyCoilCount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="dailyWeight" label="日均重量(吨)" min-width="120" align="right">
          <template #default="{ row }">
            <span>{{ formatWeight(row.dailyWeight) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 空状态 -->
    <el-card v-else-if="!loading">
      <el-empty description="暂无数据" />
    </el-card>
  </div>
</template>

<script>
import { getReceiptReport } from '@/api/wms/deliveryPlan'

export default {
  name: 'DeliveryReport',
  data() {
    return {
      summary: null,
      details: [],
      dateRange: [],
      loading: false
    }
  },
  mounted() {
    this.initDateRange()
    this.getReport()
  },
  methods: {
    // 初始化日期范围（当月）
    initDateRange() {
      const now = new Date()
      const firstDay = new Date(now.getFullYear(), now.getMonth(), 1)
      // const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0)
      const today = new Date()
      
      this.dateRange = [
        this.formatDate(firstDay),
        this.formatDate(today)
      ]
    },

    // 格式化日期为 YYYY-MM-dd
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    // 处理日期变化
    handleDateChange() {
      this.getReport()
    },

    // 重置日期
    resetDate() {
      this.initDateRange()
      this.getReport()
    },

    // 获取报表数据
    async getReport() {
      if (!this.dateRange || this.dateRange.length !== 2) {
        this.$message.warning('请选择日期范围')
        return
      }

      this.loading = true
      try {
        const query = {
          startTime: `${this.dateRange[0]} 00:00:00`,
          endTime: `${this.dateRange[1]} 23:59:59`
        }

        const res = await getReceiptReport(query)
        this.summary = res.data?.summary || null
        this.details = res.data?.details || []
      } catch (error) {
        console.error('获取发货报表失败:', error)
        this.$message.error('获取数据失败')
        this.summary = null
        this.details = []
      } finally {
        this.loading = false
      }
    },

    // 格式化重量显示
    formatWeight(weight) {
      if (!weight && weight !== 0) return '0.000'
      const num = Number(weight)
      return isNaN(num) ? '0.000' : num.toFixed(3)
    },

    // 格式化日均值显示
    formatDailyValue(value) {
      if (!value && value !== 0) return '0.00'
      const num = Number(value)
      return isNaN(num) ? '0.00' : num.toFixed(2)
    }
  }
}
</script>

<style scoped>
.delivery-report {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.summary-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-card {
  margin-bottom: 20px;
}

:deep(.el-descriptions__label) {
  font-weight: bold;
}

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