<template>
  <div class="dashboard">
    <el-row :gutter="20">
      <!-- 师团级和团级显示物资配额 -->
      <el-col v-if="authStore.organizationalLevelNum <= 2" :span="6">
        <el-card class="stat-card">
          <template #header>
            <div class="card-header">
              <el-icon :size="24" color="#409EFF"><Box /></el-icon>
              <span>物资配额</span>
            </div>
          </template>
          <div class="stat-value">{{ stats.allocations }}</div>
          <div class="stat-label">总配额条数</div>
        </el-card>
      </el-col>
      <!-- 师团级和团级显示完成率 -->
      <el-col v-if="authStore.organizationalLevelNum <= 2" :span="6">
        <el-card class="stat-card">
          <template #header>
            <div class="card-header">
              <el-icon :size="24" color="#67C23A"><DataAnalysis /></el-icon>
              <span>完成率</span>
            </div>
          </template>
          <div class="stat-value">{{ stats.completionRate }}%</div>
          <div class="stat-label">平均完成率</div>
        </el-card>
      </el-col>
      <el-col :span="authStore.organizationalLevelNum <= 2 ? 6 : 12">
        <el-card class="stat-card">
          <template #header>
            <div class="card-header">
              <el-icon :size="24" color="#E6A23C"><User /></el-icon>
              <span>人才管理</span>
            </div>
          </template>
          <div class="stat-value">{{ stats.personnel }}</div>
          <div class="stat-label">人员总数</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 饼状图区域 -->
    <el-row :gutter="20" class="mt-20">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <el-icon :size="24" color="#409EFF"><PieChart /></el-icon>
              <span>各团物资消耗情况</span>
            </div>
          </template>
          <div v-if="regimentStats.length > 0" class="pie-charts-container">
            <div 
              v-for="regiment in regimentStats" 
              :key="regiment.regimentId" 
              class="pie-chart-item"
            >
              <v-chart :option="getPieOption(regiment)" autoresize class="pie-chart" />
              <div class="regiment-name">{{ regiment.regimentName }}</div>
              <div class="regiment-info">
                <span>配额: {{ regiment.totalQuota }}</span>
                <span>消耗: {{ regiment.totalConsumed }}</span>
              </div>
            </div>
          </div>
          <el-empty v-else description="暂无团级物资配额数据" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { statsApi, type RegimentAllocationStats } from '@/api/stats'
import { Box, DataAnalysis, User, PieChart } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { PieChart as EchartsPie } from 'echarts/charts'
import { TitleComponent, TooltipComponent, LegendComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

use([EchartsPie, TitleComponent, TooltipComponent, LegendComponent, CanvasRenderer])

const authStore = useAuthStore()

const stats = ref({
  allocations: 0,
  completionRate: 0,
  personnel: 0,
  pendingApprovals: 0
})

const regimentStats = ref<RegimentAllocationStats[]>([])
const loading = ref(false)

function getPieOption(regiment: RegimentAllocationStats) {
  const consumed = regiment.totalConsumed
  const remaining = regiment.totalQuota - consumed
  
  // 当配额为0时，显示全灰色
  const hasData = regiment.totalQuota > 0
  
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    series: [
      {
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: true,
          position: 'center',
          formatter: `${regiment.percentage}%`,
          fontSize: 18,
          fontWeight: 'bold',
          color: '#303133'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: hasData
          ? [
              { value: consumed, name: '已消耗', itemStyle: { color: '#67C23A' } },
              { value: remaining > 0 ? remaining : 0, name: '剩余', itemStyle: { color: '#E4E7ED' } }
            ]
          : [
              { value: 1, name: '无配额', itemStyle: { color: '#E4E7ED' } }
            ]
      }
    ]
  }
}

async function loadStats() {
  loading.value = true
  try {
    stats.value = await statsApi.getDashboardStats()
  } catch {
    ElMessage.error('加载统计数据失败')
  } finally {
    loading.value = false
  }
}

async function loadRegimentStats() {
  try {
    const data = await statsApi.getRegimentAllocationsStats()
    console.log('Regiment stats loaded:', data)
    regimentStats.value = data
  } catch (error) {
    console.error('加载团级统计数据失败', error)
  }
}

onMounted(() => {
  loadStats()
  loadRegimentStats()
})
</script>

<style scoped>
.dashboard {
  padding: 10px;
}

.stat-card {
  text-align: center;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

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

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

.mt-20 {
  margin-top: 20px;
}

.pie-charts-container {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  gap: 20px;
}

.pie-chart-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
  min-width: 180px;
  max-width: 220px;
}

.pie-chart {
  width: 180px;
  height: 180px;
}

.regiment-name {
  margin-top: 8px;
  font-size: 16px;
  color: #303133;
  font-weight: 600;
  text-align: center;
}

.regiment-info {
  display: flex;
  gap: 16px;
  font-size: 14px;
  color: #606266;
  margin-top: 6px;
}
</style>
