<template>
  <div class="stevia-report-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">
          <Icon icon="ep:document" class="title-icon" />
          甜叶菊生产报表
        </h1>
        <span class="report-date">{{ formatDate(queryDate) }}</span>
      </div>
      <div class="header-actions">
        <span class="filter-label">查询日期：</span>
        <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"
          style="width: 140px"
        />
        <el-divider direction="vertical" />
        <span class="filter-label">本期累计：</span>
        <el-date-picker
          v-model="periodDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :clearable="false"
          @change="handleDateChange"
          style="width: 240px"
        />
        <el-button type="primary" :loading="loading" @click="loadReportData">
          <Icon icon="ep:refresh" class="mr-1" />
          刷新
        </el-button>
        <el-button type="success" @click="handleExport">
          <Icon icon="ep:download" class="mr-1" />
          导出Excel
        </el-button>
      </div>
    </div>

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

    <!-- 报表内容 -->
    <div v-else class="report-content">
      <div class="report-table-wrapper">
        <table class="stevia-report-table">
          <thead>
            <tr>
              <th class="col-category">项 目</th>
              <th class="col-item"></th>
              <th class="col-unit">单位</th>
              <th class="col-value">日 计</th>
              <th class="col-value">月 计</th>
              <th class="col-value">本期累计</th>
              <th class="col-value">年累计</th>
            </tr>
          </thead>
          <tbody>
            <template v-for="(group, groupIndex) in groupedReportData" :key="groupIndex">
              <tr v-for="(row, rowIndex) in group.rows" :key="`${groupIndex}-${rowIndex}`">
                <!-- 分类列（合并单元格） -->
                <td
                  v-if="rowIndex === 0"
                  :rowspan="group.rows.length"
                  class="col-category category-cell"
                >
                  {{ group.category }}
                </td>
                <!-- 项目名称 -->
                <td class="col-item">{{ row.item }}</td>
                <!-- 单位 -->
                <td class="col-unit">{{ row.unit }}</td>
                <!-- 日计 -->
                <td class="col-value">{{ formatValue(row.daily) }}</td>
                <!-- 月计 -->
                <td class="col-value">{{ formatValue(row.monthly) }}</td>
                <!-- 本期累计 -->
                <td class="col-value">{{ formatValue(row.periodTotal) }}</td>
                <!-- 年累计 -->
                <td class="col-value">{{ formatValue(row.yearly) }}</td>
              </tr>
            </template>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 报表底部 -->
    <div class="report-footer">
      <span>报表生成时间：{{ currentTime }}</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getSteviaReport } from '@/api/mes/home'
import { Icon } from '@/components/Icon'
import download from '@/utils/download'

defineOptions({ name: 'MESSteviaReport' })

// 响应式数据
const loading = ref(false)
const queryDate = ref<string>(formatDateToString(new Date()))
const periodDateRange = ref<[string, string]>([getYearStart(), formatDateToString(new Date())])
const reportData = ref<any[]>([])
const currentTime = ref<string>('')

// 获取年初日期
function getYearStart(): string {
  const now = new Date()
  return `${now.getFullYear()}-01-01`
}

// 格式化日期为字符串 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 formatDate = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

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

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

// 格式化数值
const formatValue = (value: any) => {
  if (value === null || value === undefined || value === '') return ''
  if (typeof value === 'number') {
    // 保留合适的小数位
    if (Number.isInteger(value)) {
      return value.toLocaleString()
    }
    return value.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 3 })
  }
  return value
}

// 将报表数据按分类分组
const groupedReportData = computed(() => {
  const groups: { category: string; rows: any[] }[] = []
  let currentCategory = ''
  let currentGroup: { category: string; rows: any[] } | null = null

  for (const row of reportData.value) {
    const category = row.category || ''
    
    if (category && category !== currentCategory) {
      // 开始新分组
      currentCategory = category
      currentGroup = { category, rows: [] }
      groups.push(currentGroup)
    }
    
    if (currentGroup) {
      currentGroup.rows.push(row)
    } else {
      // 如果没有分类，创建一个默认分组
      currentGroup = { category: '', rows: [row] }
      groups.push(currentGroup)
    }
  }

  return groups
})

// 加载报表数据
const loadReportData = async () => {
  try {
    loading.value = true
    const res = await getSteviaReport({ 
      date: queryDate.value,
      periodStartDate: periodDateRange.value[0],
      periodEndDate: periodDateRange.value[1]
    })
    const data = res.data || res
    reportData.value = data.reportRows || []
    currentTime.value = new Date().toLocaleString('zh-CN')
  } catch (error) {
    console.error('加载报表数据失败:', error)
    ElMessage.error('加载报表数据失败')
  } finally {
    loading.value = false
  }
}

// 导出Excel (CSV格式，兼容Excel打开)
const handleExport = () => {
  if (reportData.value.length === 0) {
    ElMessage.warning('暂无数据可导出')
    return
  }

  try {
    // 构建CSV数据
    const csvRows: string[] = []
    
    // 添加BOM头，确保Excel正确识别UTF-8编码
    const BOM = '\uFEFF'
    
    // 添加标题行
    csvRows.push('甜叶菊生产报表')
    csvRows.push('报表日期：' + formatDate(queryDate.value))
    csvRows.push('') // 空行
    
    // 表头
    csvRows.push(['项目', '子项', '单位', '日计', '月计', '本期累计', '年累计'].join(','))

    // 数据行
    for (const group of groupedReportData.value) {
      for (let i = 0; i < group.rows.length; i++) {
        const row = group.rows[i]
        const rowData = [
          i === 0 ? group.category : '',
          row.item || '',
          row.unit || '',
          row.daily ?? '',
          row.monthly ?? '',
          row.periodTotal ?? '',
          row.yearly ?? ''
        ]
        // 处理可能包含逗号的字段
        csvRows.push(rowData.map(cell => `"${cell}"`).join(','))
      }
    }

    // 创建Blob并下载
    const csvContent = BOM + csvRows.join('\n')
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
    const fileName = `甜叶菊生产报表_${queryDate.value}.csv`
    download.excel(blob, fileName)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

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

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

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

    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;

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

        .title-icon {
          font-size: 26px;
          color: #10b981;
        }
      }

      .report-date {
        padding: 4px 12px;
        background: #f0fdf4;
        border-radius: 4px;
        color: #059669;
        font-size: 14px;
      }
    }

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

      .filter-label {
        font-size: 14px;
        color: #374151;
        white-space: nowrap;
      }
    }
  }

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

  .report-content {
    flex: 1;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    overflow: hidden;

    .report-table-wrapper {
      padding: 20px;
      overflow-x: auto;
    }

    .stevia-report-table {
      width: 100%;
      border-collapse: collapse;
      font-size: 14px;

      th, td {
        border: 1px solid #e5e7eb;
        padding: 12px 16px;
        text-align: center;
      }

      thead {
        th {
          background: linear-gradient(135deg, #059669 0%, #10b981 100%);
          color: white;
          font-weight: 600;
          white-space: nowrap;
        }
      }

      tbody {
        tr {
          &:nth-child(even) {
            background: #f9fafb;
          }

          &:hover {
            background: #f0fdf4;
          }
        }

        td {
          color: #374151;

          &.category-cell {
            background: #f0fdf4;
            font-weight: 600;
            color: #059669;
            text-align: center;
            vertical-align: middle;
            white-space: nowrap;
          }
        }

        .col-category {
          width: 100px;
          min-width: 100px;
        }

        .col-item {
          width: 120px;
          min-width: 120px;
          text-align: left;
          padding-left: 20px;
        }

        .col-unit {
          width: 60px;
          min-width: 60px;
        }

        .col-value {
          width: 100px;
          min-width: 100px;
          text-align: right;
          font-family: 'Consolas', 'Monaco', monospace;
        }
      }
    }
  }

  .report-footer {
    margin-top: 16px;
    padding: 12px 24px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    text-align: center;
    color: #6b7280;
    font-size: 13px;
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .stevia-report-container {
    .page-header {
      .header-actions {
        flex-wrap: wrap;
        gap: 8px;
        
        .filter-label {
          font-size: 13px;
        }
        
        .el-date-picker {
          width: 120px !important;
        }
        
        .el-date-picker--daterange {
          width: 200px !important;
        }
      }
    }
  }
}

@media (max-width: 992px) {
  .stevia-report-container {
    padding: 16px;

    .page-header {
      flex-direction: column;
      gap: 16px;
      align-items: stretch;
      padding: 16px 20px;

      .header-left {
        justify-content: center;
        text-align: center;
        
        .page-title {
          font-size: 20px;
          
          .title-icon {
            font-size: 24px;
          }
        }
        
        .report-date {
          font-size: 13px;
        }
      }

      .header-actions {
        width: 100%;
        justify-content: center;
        flex-wrap: wrap;
        gap: 12px;
        
        .el-date-picker {
          width: 140px !important;
        }
        
        .el-date-picker--daterange {
          width: 240px !important;
        }
        
        .el-button {
          min-width: 80px;
        }
      }
    }

    .report-content {
      .report-table-wrapper {
        padding: 16px;
        
        .stevia-report-table {
          font-size: 13px;
          
          th, td {
            padding: 10px 12px;
          }
          
          .col-category {
            width: 80px;
            min-width: 80px;
          }
          
          .col-item {
            width: 100px;
            min-width: 100px;
            padding-left: 16px;
          }
          
          .col-unit {
            width: 50px;
            min-width: 50px;
          }
          
          .col-value {
            width: 85px;
            min-width: 85px;
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .stevia-report-container {
    padding: 12px;
    min-height: calc(100vh - 60px);

    .page-header {
      padding: 12px 16px;
      margin-bottom: 16px;

      .header-left {
        gap: 12px;
        
        .page-title {
          font-size: 18px;
          
          .title-icon {
            font-size: 22px;
          }
        }
      }

      .header-actions {
        gap: 8px;
        
        .filter-label {
          font-size: 12px;
          min-width: fit-content;
        }
        
        .el-date-picker {
          width: 120px !important;
          font-size: 12px;
        }
        
        .el-date-picker--daterange {
          width: 200px !important;
          font-size: 12px;
        }
        
        .el-button {
          padding: 8px 12px;
          font-size: 12px;
          min-width: 70px;
          
          .mr-1 {
            margin-right: 4px;
          }
        }
        
        .el-divider--vertical {
          display: none;
        }
      }
    }

    .report-content {
      .report-table-wrapper {
        padding: 12px;
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
        
        .stevia-report-table {
          min-width: 600px;
          font-size: 12px;
          
          th, td {
            padding: 8px 10px;
            white-space: nowrap;
          }
          
          thead th {
            font-size: 12px;
            position: sticky;
            top: 0;
            z-index: 10;
          }
          
          .col-category {
            width: 70px;
            min-width: 70px;
            font-size: 11px;
          }
          
          .col-item {
            width: 90px;
            min-width: 90px;
            padding-left: 12px;
            font-size: 11px;
          }
          
          .col-unit {
            width: 40px;
            min-width: 40px;
            font-size: 11px;
          }
          
          .col-value {
            width: 75px;
            min-width: 75px;
            font-size: 11px;
          }
        }
      }
    }

    .report-footer {
      margin-top: 12px;
      padding: 10px 16px;
      font-size: 12px;
    }
  }
}

@media (max-width: 480px) {
  .stevia-report-container {
    padding: 8px;

    .page-header {
      padding: 10px 12px;
      margin-bottom: 12px;

      .header-left {
        .page-title {
          font-size: 16px;
          
          .title-icon {
            font-size: 20px;
          }
        }
        
        .report-date {
          font-size: 11px;
          padding: 3px 8px;
        }
      }

      .header-actions {
        .filter-label {
          font-size: 11px;
        }
        
        .el-date-picker {
          width: 110px !important;
        }
        
        .el-date-picker--daterange {
          width: 180px !important;
        }
        
        .el-button {
          padding: 6px 10px;
          font-size: 11px;
          min-width: 60px;
        }
      }
    }

    .report-content {
      .report-table-wrapper {
        padding: 8px;
        
        .stevia-report-table {
          min-width: 550px;
          font-size: 11px;
          
          th, td {
            padding: 6px 8px;
          }
          
          .col-category {
            width: 60px;
            min-width: 60px;
            font-size: 10px;
          }
          
          .col-item {
            width: 80px;
            min-width: 80px;
            padding-left: 10px;
            font-size: 10px;
          }
          
          .col-unit {
            width: 35px;
            min-width: 35px;
            font-size: 10px;
          }
          
          .col-value {
            width: 65px;
            min-width: 65px;
            font-size: 10px;
          }
        }
      }
    }

    .report-footer {
      margin-top: 10px;
      padding: 8px 12px;
      font-size: 11px;
    }
  }
}

// 横屏优化
@media (max-width: 768px) and (orientation: landscape) {
  .stevia-report-container {
    .page-header {
      .header-left {
        flex-direction: row;
        
        .page-title {
          font-size: 16px;
        }
      }
      
      .header-actions {
        flex-direction: row;
        justify-content: flex-start;
      }
    }
  }
}

// 触摸设备优化
@media (hover: none) and (pointer: coarse) {
  .stevia-report-container {
    .page-header {
      .header-actions {
        .el-button {
          min-height: 44px;
          touch-action: manipulation;
        }
        
        .el-date-picker {
          min-height: 44px;
        }
      }
    }
    
    .report-content {
      .stevia-report-table {
        tbody tr:hover {
          background: inherit;
        }
        
        tbody tr:active {
          background: #f0fdf4;
        }
      }
    }
  }
}
</style>
