<template>
  <div class="report-summary">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>数据汇总</span>
          <el-button type="primary" @click="loadSummary">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>
      
      <div v-loading="loading">
        <!-- Summary Cards -->
        <el-row :gutter="20" class="summary-cards">
          <el-col :span="8">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-value">{{ summary?.totalQuota ?? 0 }}</div>
              <div class="stat-label">总配额</div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-value">{{ summary?.totalCompletion ?? 0 }}</div>
              <div class="stat-label">总完成</div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-value" :class="getCompletionClass(summary?.overallCompletionRate ?? 0)">
                {{ ((summary?.overallCompletionRate ?? 0) * 100).toFixed(1) }}%
              </div>
              <div class="stat-label">总完成率</div>
            </el-card>
          </el-col>
        </el-row>
        
        <!-- Subordinate Units Table -->
        <el-table 
          v-if="summary?.subordinateReports?.length" 
          :data="summary.subordinateReports" 
          style="width: 100%; margin-top: 20px"
          row-key="organizationalUnitId"
          default-expand-all
        >
          <el-table-column prop="organizationalUnitName" label="单位名称" />
          <el-table-column prop="level" label="层级" width="100">
            <template #default="{ row }">
              <el-tag :type="getLevelTagType(row.level)">{{ getLevelName(row.level) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="totalQuota" label="配额" width="120" />
          <el-table-column prop="totalCompletion" label="完成" width="120" />
          <el-table-column prop="overallCompletionRate" label="完成率" width="180">
            <template #default="{ row }">
              <el-progress 
                :percentage="Math.round(row.overallCompletionRate * 100)" 
                :status="getProgressStatus(row.overallCompletionRate)" 
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button type="primary" text size="small" @click="handleDrillDown(row)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <el-empty v-else-if="!loading" description="暂无数据" />
      </div>
    </el-card>
    
    <!-- Drill-down Dialog -->
    <el-dialog v-model="showDetailDialog" :title="detailTitle" width="800px">
      <el-table :data="detailData?.subordinateReports ?? []" style="width: 100%">
        <el-table-column prop="organizationalUnitName" label="单位名称" />
        <el-table-column prop="totalQuota" label="配额" width="120" />
        <el-table-column prop="totalCompletion" label="完成" width="120" />
        <el-table-column prop="overallCompletionRate" label="完成率" width="180">
          <template #default="{ row }">
            <el-progress 
              :percentage="Math.round(row.overallCompletionRate * 100)" 
              :status="getProgressStatus(row.overallCompletionRate)" 
            />
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { reportsApi } from '@/api'
import type { AggregatedReport } from '@/types'
import { OrganizationalLevel } from '@/types'

const summary = ref<AggregatedReport | null>(null)
const detailData = ref<AggregatedReport | null>(null)
const loading = ref(false)
const showDetailDialog = ref(false)
const detailTitle = ref('')

function getLevelName(level: OrganizationalLevel): string {
  switch (level) {
    case OrganizationalLevel.Division: return '师团'
    case OrganizationalLevel.Regiment: return '团'
    case OrganizationalLevel.Battalion: return '营'
    case OrganizationalLevel.Company: return '连'
    default: return ''
  }
}

function getLevelTagType(level: OrganizationalLevel): string {
  switch (level) {
    case OrganizationalLevel.Division: return 'danger'
    case OrganizationalLevel.Regiment: return 'warning'
    case OrganizationalLevel.Battalion: return 'success'
    case OrganizationalLevel.Company: return 'info'
    default: return 'info'
  }
}

function getProgressStatus(rate: number): string {
  if (rate >= 1) return 'success'
  if (rate >= 0.6) return ''
  return 'warning'
}

function getCompletionClass(rate: number): string {
  if (rate >= 1) return 'completion-success'
  if (rate >= 0.6) return 'completion-normal'
  return 'completion-warning'
}

async function loadSummary() {
  loading.value = true
  try {
    summary.value = await reportsApi.getAggregated()
  } catch {
    ElMessage.error('加载汇总数据失败')
  } finally {
    loading.value = false
  }
}

async function handleDrillDown(report: AggregatedReport) {
  try {
    detailData.value = await reportsApi.getAggregatedByUnit(report.organizationalUnitId)
    detailTitle.value = `${report.organizationalUnitName} - 详细数据`
    showDetailDialog.value = true
  } catch {
    ElMessage.error('加载详细数据失败')
  }
}

onMounted(() => {
  loadSummary()
})
</script>

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

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

.stat-card {
  text-align: center;
  padding: 20px;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
}

.stat-label {
  color: #909399;
  margin-top: 8px;
}

.completion-success {
  color: #67C23A;
}

.completion-normal {
  color: #409EFF;
}

.completion-warning {
  color: #E6A23C;
}
</style>
