<template>
  <div class="daily-report-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <Icon icon="ep:data-analysis" class="title-icon" />
          MES生产日报
        </h1>
        <div class="report-date">
          <Icon icon="ep:calendar" />
          {{ formatDate(reportData.summary?.reportDate) }}
        </div>
      </div>
      <div class="query-actions">
        <el-date-picker
          v-model="queryDate"
          type="date"
          placeholder="选择日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :clearable="false"
          :disabled-date="disabledDate"
          @change="handleDateChange"
        />
        <el-button
          type="primary"
          :icon="RefreshIcon"
          :loading="loading"
          @click="loadReportData"
        >
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 数据加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="8" animated />
    </div>

    <!-- 报表内容 -->
    <div v-else class="report-content">
      <!-- 概览卡片 -->
      <div class="overview-cards">
        <div class="card-item">
          <div class="card-icon material">
            <Icon icon="ep:box" />
          </div>
          <div class="card-content">
            <div class="card-value">{{ reportData.summary?.totalMaterialTypes || 0 }}</div>
            <div class="card-label">物料种类</div>
          </div>
        </div>
        <div class="card-item">
          <div class="card-icon product">
            <Icon icon="ep:goods" />
          </div>
          <div class="card-content">
            <div class="card-value">{{ reportData.summary?.totalProductTypes || 0 }}</div>
            <div class="card-label">产品种类</div>
          </div>
        </div>
        <div class="card-item">
          <div class="card-icon water">
            <Icon icon="ep:coffee-cup" />
          </div>
          <div class="card-content">
            <div class="card-value">{{ reportData.utilityConsumption?.waterConsumption || 0 }}</div>
            <div class="card-label">用水量(吨)</div>
          </div>
        </div>
        <div class="card-item">
          <div class="card-icon electricity">
            <Icon icon="ep:lightning" />
          </div>
          <div class="card-content">
            <div class="card-value">{{ reportData.utilityConsumption?.electricityConsumption || 0 }}</div>
            <div class="card-label">用电量(kWh)</div>
          </div>
        </div>
      </div>

      <!-- 详细数据表格 -->
      <div class="data-tables">
        <!-- 物料消耗表 -->
        <div class="table-section">
          <div class="section-header">
            <h2 class="section-title">
              <Icon icon="ep:box" />
              物料消耗明细
            </h2>
            <div class="section-actions">
              <el-button size="small" @click="exportMaterialData">
                <Icon icon="ep:download" />
                导出
              </el-button>
            </div>
          </div>
          <el-table
            :data="reportData.materialConsumption || []"
            class="data-table"
            stripe
            border
            empty-text="暂无物料消耗数据"
          >
            <el-table-column prop="materialCode" label="物料编码" width="120" />
            <el-table-column prop="materialName" label="物料名称" min-width="150" />
            <el-table-column prop="consumedQuantity" label="消耗数量" width="120" align="right">
              <template #default="{ row }">
                <span
                  class="quantity-value"
                  :class="{ 'zero-consumption': row.consumedQuantity === 0 || row.consumedQuantity === '0' }"
                >
                  {{ formatNumber(row.consumedQuantity) }}
                </span>
                <el-tag
                  v-if="row.consumedQuantity === 0 || row.consumedQuantity === '0'"
                  type="info"
                  size="small"
                  class="zero-tag"
                >
                  未消耗
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="unit" label="单位" width="80" align="center" />
          </el-table>
        </div>

        <!-- 产量统计表 -->
        <div class="table-section">
          <div class="section-header">
            <h2 class="section-title">
              <Icon icon="ep:goods" />
              产量统计明细
            </h2>
            <div class="section-actions">
              <el-button size="small" @click="exportProductionData">
                <Icon icon="ep:download" />
                导出
              </el-button>
            </div>
          </div>
          <el-table
            :data="reportData.productionOutput || []"
            class="data-table"
            stripe
            border
            empty-text="暂无产量数据"
          >
            <el-table-column prop="productCode" label="产品编码" width="120" />
            <el-table-column prop="productName" label="产品名称" min-width="150" />
            <el-table-column prop="outputQuantity" label="总产量" width="100" align="right">
              <template #default="{ row }">
                <span class="quantity-value">{{ formatNumber(row.outputQuantity) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="qualifiedQuantity" label="合格数量" width="100" align="right">
              <template #default="{ row }">
                <span class="quantity-value qualified">{{ formatNumber(row.qualifiedQuantity) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="unqualifiedQuantity" label="不合格数量" width="110" align="right">
              <template #default="{ row }">
                <span class="quantity-value unqualified">{{ formatNumber(row.unqualifiedQuantity) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="合格率" width="100" align="center">
              <template #default="{ row }">
                <el-tag
                  :type="getQualityTagType(calculateQualityRate(row))"
                  size="small"
                >
                  {{ calculateQualityRate(row) }}%
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 水电消耗详情 -->
        <div class="table-section">
          <div class="section-header">
            <h2 class="section-title">
              <Icon icon="ep:lightning" />
              水电消耗详情
            </h2>
          </div>
          <div class="utility-grid">
            <div class="utility-card water-card">
              <div class="utility-icon">
                <Icon icon="ep:coffee-cup" />
              </div>
              <div class="utility-info">
                <div class="utility-value">{{ reportData.utilityConsumption?.waterConsumption || 0 }}</div>
                <div class="utility-unit">{{ reportData.utilityConsumption?.waterUnit || '吨' }}</div>
                <div class="utility-label">用水量</div>
              </div>
            </div>
            <div class="utility-card electricity-card">
              <div class="utility-icon">
                <Icon icon="ep:lightning" />
              </div>
              <div class="utility-info">
                <div class="utility-value">{{ reportData.utilityConsumption?.electricityConsumption || 0 }}</div>
                <div class="utility-unit">{{ reportData.utilityConsumption?.electricityUnit || 'kWh' }}</div>
                <div class="utility-label">用电量</div>
              </div>
            </div>
            <!-- 环境数据 -->
            <div v-if="reportData.utilityConsumption?.avgAirTemp" class="utility-card env-card">
              <div class="utility-icon">
                <Icon icon="ep:sunny" />
              </div>
              <div class="utility-info">
                <div class="utility-value">{{ reportData.utilityConsumption.avgAirTemp }}°C</div>
                <div class="utility-unit">{{ reportData.utilityConsumption.avgAirHumidity }}%</div>
                <div class="utility-label">温湿度</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 报表生成时间 -->
    <div class="report-footer">
      <div class="footer-info">
        <Icon icon="ep:clock" />
        报表生成时间: {{ formatDateTime(reportData.summary?.reportTime) }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh as RefreshIcon } from '@element-plus/icons-vue'
import * as MesHomeApi from '@/api/mes/home/index'

// 响应式数据
const loading = ref(false)
const reportData = ref<any>({})
const queryDate = ref<string>(formatDateToString(new Date()))

// 格式化日期为字符串 YYYY-MM-DD
function formatDateToString(date: Date): string {
  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}`
}

// 禁用未来日期
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}

// 日期变化处理
const handleDateChange = () => {
  loadReportData()
}

// 必须显示的物料列表（即使消耗数量为0）
const requiredMaterials = [
  { materialCode: 'HCL001', materialName: '盐酸', unit: '千克' },
  { materialCode: 'ALC001', materialName: '醇', unit: '千克' },
  { materialCode: 'FES001', materialName: '硫酸亚铁', unit: '千克' },
  { materialCode: 'NAOH001', materialName: '片碱', unit: '千克' },
  { materialCode: 'CAO001', materialName: '氧化钙', unit: '千克' },
  { materialCode: 'BACT001', materialName: '杀菌剂', unit: '千克' },
  { materialCode: 'COAL001', materialName: '煤', unit: '千克' }
]

// 处理物料消耗数据，确保必需物料都显示
const processMaterialConsumption = (materialConsumption: any[]) => {
  const materialMap = new Map()

  // 先添加实际消耗的物料
  materialConsumption.forEach(item => {
    const key = item.materialName // 使用物料名称作为唯一标识
    materialMap.set(key, item)
  })

  // 添加必须显示的物料（如果不存在同名物料）
  requiredMaterials.forEach(material => {
    const key = material.materialName
    if (!materialMap.has(key)) {
      // 只有当不存在同名物料时才添加
      materialMap.set(key, {
        materialCode: material.materialCode,
        materialName: material.materialName,
        unit: material.unit,
        consumedQuantity: 0
      })
    }
  })

  return Array.from(materialMap.values()).sort((a, b) => {
    // 优先显示必需物料，按名称排序
    const aIsRequired = requiredMaterials.some(m => m.materialName === a.materialName)
    const bIsRequired = requiredMaterials.some(m => m.materialName === b.materialName)

    if (aIsRequired && !bIsRequired) return -1
    if (!aIsRequired && bIsRequired) return 1

    return a.materialName.localeCompare(b.materialName, 'zh-CN')
  })
}

// 加载报表数据
const loadReportData = async () => {
  try {
    loading.value = true
    const data = await MesHomeApi.getDailyReport({ date: queryDate.value })

    // 处理物料消耗数据
    if (data.materialConsumption) {
      data.materialConsumption = processMaterialConsumption(data.materialConsumption)
    }

    reportData.value = data
  } catch (error) {
    console.error('加载报表数据失败:', error)
    ElMessage.error('加载报表数据失败')
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  return date.toLocaleString('zh-CN')
}

// 格式化数字
const formatNumber = (value: any) => {
  if (value === null || value === undefined) return '0'
  return Number(value).toLocaleString()
}

// 计算合格率
const calculateQualityRate = (row: any) => {
  const total = (row.qualifiedQuantity || 0) + (row.unqualifiedQuantity || 0)
  if (total === 0) return 0
  return Math.round((row.qualifiedQuantity || 0) * 100 / total)
}

// 获取质量标签类型
const getQualityTagType = (rate: number) => {
  if (rate >= 95) return 'success'
  if (rate >= 85) return 'warning'
  return 'danger'
}

// 导出物料数据
const exportMaterialData = () => {
  ElMessage.info('导出功能开发中...')
}

// 导出产量数据
const exportProductionData = () => {
  ElMessage.info('导出功能开发中...')
}

// 页面挂载时加载数据
onMounted(() => {
  loadReportData()
})
</script>

<style scoped lang="scss">
.daily-report-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 84px);

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding: 20px 24px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .header-content {
      display: flex;
      align-items: center;
      gap: 24px;

      .page-title {
        display: flex;
        align-items: center;
        gap: 8px;
        margin: 0;
        font-size: 24px;
        font-weight: 600;
        color: #1f2937;

        .title-icon {
          font-size: 28px;
          color: #3b82f6;
        }
      }

      .report-date {
        display: flex;
        align-items: center;
        gap: 6px;
        padding: 6px 12px;
        background: #f3f4f6;
        border-radius: 6px;
        color: #6b7280;
        font-size: 14px;
      }
    }

    .query-actions {
      display: flex;
      align-items: center;
      gap: 12px;
    }
  }

  .loading-container {
    background: white;
    padding: 24px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .overview-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
    gap: 20px;
    margin-bottom: 24px;

    .card-item {
      display: flex;
      align-items: center;
      padding: 24px;
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      transition: transform 0.2s, box-shadow 0.2s;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
      }

      .card-icon {
        width: 48px;
        height: 48px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;
        font-size: 24px;
        color: white;

        &.material {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        &.product {
          background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }

        &.water {
          background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }

        &.electricity {
          background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
        }
      }

      .card-content {
        flex: 1;

        .card-value {
          font-size: 28px;
          font-weight: 700;
          color: #1f2937;
          line-height: 1;
          margin-bottom: 4px;
        }

        .card-label {
          font-size: 14px;
          color: #6b7280;
        }
      }
    }
  }

  .data-tables {
    display: flex;
    flex-direction: column;
    gap: 24px;

    .table-section {
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      overflow: hidden;

      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20px 24px;
        border-bottom: 1px solid #e5e7eb;
        background: #f9fafb;

        .section-title {
          display: flex;
          align-items: center;
          gap: 8px;
          margin: 0;
          font-size: 18px;
          font-weight: 600;
          color: #1f2937;
        }
      }

      .data-table {
        .quantity-value {
          font-weight: 600;

          &.qualified {
            color: #059669;
          }

          &.unqualified {
            color: #dc2626;
          }

          &.zero-consumption {
            color: #9ca3af;
            font-style: italic;
          }
        }

        .zero-tag {
          margin-left: 8px;
        }
      }

      .utility-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 20px;
        padding: 24px;

        .utility-card {
          display: flex;
          align-items: center;
          padding: 20px;
          border-radius: 8px;
          border: 1px solid #e5e7eb;
          transition: transform 0.2s, box-shadow 0.2s;

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
          }

          .utility-icon {
            width: 40px;
            height: 40px;
            border-radius: 6px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 16px;
            font-size: 20px;
            color: white;
          }

          .utility-info {
            flex: 1;

            .utility-value {
              font-size: 24px;
              font-weight: 700;
              color: #1f2937;
              line-height: 1;
            }

            .utility-unit {
              font-size: 12px;
              color: #6b7280;
              margin-bottom: 4px;
            }

            .utility-label {
              font-size: 14px;
              color: #6b7280;
            }
          }

          &.water-card .utility-icon {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
          }

          &.electricity-card .utility-icon {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
          }

          &.env-card .utility-icon {
            background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
          }
        }
      }
    }
  }

  .report-footer {
    margin-top: 24px;
    padding: 16px 24px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    text-align: center;

    .footer-info {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 6px;
      color: #6b7280;
      font-size: 14px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .daily-report-container {
    padding: 16px;

    .page-header {
      flex-direction: column;
      gap: 16px;
      align-items: flex-start;

      .header-content {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
      }

      .query-actions {
        width: 100%;
        flex-direction: column;
        align-items: stretch;

        .el-date-picker {
          width: 100%;
        }

        .el-button {
          width: 100%;
        }
      }
    }

    .overview-cards {
      grid-template-columns: 1fr;
    }
  }
}
</style>
