<template>
  <div>
    <h1>仪表板</h1>
    <a-row gutter={24}>
      <!-- 数据卡片区域 -->
      <a-col :span="6">
        <a-card class="stat-card" :body-style="{ padding: '20px' }">
          <div class="stat-content">
            <div class="stat-number">{{ stats.totalEntities }}</div>
            <div class="stat-label">总实体数</div>
          </div>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="stat-card" :body-style="{ padding: '20px' }">
          <div class="stat-content">
            <div class="stat-number">{{ stats.inspectionCount }}</div>
            <div class="stat-label">检查次数</div>
          </div>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="stat-card" :body-style="{ padding: '20px' }">
          <div class="stat-content">
            <div class="stat-number">{{ stats.vaccinated }}</div>
            <div class="stat-label">疫苗接种数</div>
          </div>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="stat-card" :body-style="{ padding: '20px' }">
          <div class="stat-content">
            <div class="stat-number">{{ stats.tested }}</div>
            <div class="stat-label">检测人数</div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 图表区域 -->
    <a-row gutter={24} style="margin-top: 24px;">
      <a-col :span="12">
        <a-card title="监管趋势图" :body-style="{ padding: 0 }">
          <div style="height: 300px; padding: 10px;">
            <!-- 这里将放置图表 -->
            <div id="trend-chart" style="width: 100%; height: 100%;"></div>
          </div>
        </a-card>
      </a-col>
      <a-col :span="12">
        <a-card title="饼图数据" :body-style="{ padding: 0 }">
          <div style="height: 300px; padding: 10px;">
            <!-- 这里将放置饼图 -->
            <div id="pie-chart" style="width: 100%; height: 100%;"></div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 最近活动区域 -->
    <a-card title="最近活动" style="margin-top: 24px;">
      <a-table :columns="activityColumns" :data-source="recentActivities" pagination={false}>
        <template #bodyCell:time="{ record }">
          <span>{{ formatTime(record.time) }}</span>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useUserStore } from '@/stores/user'
import dayjs from 'dayjs'
import axios from 'axios'
import * as echarts from 'echarts'

const userStore = useUserStore()
const stats = ref({
  totalEntities: 0,
  inspectionCount: 0,
  vaccinated: 0,
  tested: 0
})
const recentActivities = ref([])
let trendChart = null
let pieChart = null

// 活动表格列定义
const activityColumns = [
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type'
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description'
  },
  {
    title: '时间',
    dataIndex: 'time',
    key: 'time',
    slots: { customRender: 'time' }
  }
]

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

import api from '@/utils/api-redesigned'

// 获取统计数据（统一封装）
const fetchStats = async () => {
  try {
    // 获取监管统计数据
    const supervisionResp = await api.supervision.getStats()
    if (supervisionResp?.code === 200) {
      const supervisionData = supervisionResp.data
      stats.value.totalEntities = supervisionData?.entityCount || 0
      stats.value.inspectionCount = supervisionData?.inspectionCount || 0
    }

    // 获取疫情统计数据
    const epidemicResp = await api.epidemic.getStats()
    if (epidemicResp?.code === 200) {
      const epidemicData = epidemicResp.data
      stats.value.vaccinated = epidemicData?.vaccinated || 0
      stats.value.tested = epidemicData?.tested || 0
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    // 使用模拟数据
    stats.value = {
      totalEntities: 150,
      inspectionCount: 78,
      vaccinated: 12500,
      tested: 89000
    }
  }
}

// 获取最近活动数据
const fetchRecentActivities = async () => {
  try {
    // 这里应该从API获取数据
    // 由于没有实际API，使用模拟数据
    recentActivities.value = [
      {
        key: '1',
        type: '登录',
        description: `${userStore.userInfo.real_name || '管理员'} 登录系统`,
        time: new Date().toISOString()
      },
      {
        key: '2',
        type: '操作',
        description: '系统配置已更新',
        time: new Date(Date.now() - 3600000).toISOString()
      },
      {
        key: '3',
        type: '提醒',
        description: '有5个待审批的申请',
        time: new Date(Date.now() - 7200000).toISOString()
      },
      {
        key: '4',
        type: '警告',
        description: '检测到2个异常数据',
        time: new Date(Date.now() - 10800000).toISOString()
      }
    ]
  } catch (error) {
    console.error('获取活动数据失败:', error)
  }
}

// 初始化图表
const initCharts = () => {
  // 趋势图
  const trendChartDom = document.getElementById('trend-chart')
  if (trendChartDom) {
    trendChart = echarts.init(trendChartDom)
    const trendOption = {
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '检查次数',
          data: [12, 19, 3, 5, 2, 3],
          type: 'line'
        }
      ]
    }
    trendChart.setOption(trendOption)
  }

  // 饼图
  const pieChartDom = document.getElementById('pie-chart')
  if (pieChartDom) {
    pieChart = echarts.init(pieChartDom)
    const pieOption = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        top: '5%',
        left: 'center'
      },
      series: [
        {
          name: '数据分布',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            {
              value: 30,
              name: '类型A'
            },
            {
              value: 25,
              name: '类型B'
            },
            {
              value: 20,
              name: '类型C'
            },
            {
              value: 15,
              name: '类型D'
            },
            {
              value: 10,
              name: '其他'
            }
          ]
        }
      ]
    }
    pieChart.setOption(pieOption)
  }
}

// 响应窗口大小变化
const handleResize = () => {
  if (trendChart) {
    trendChart.resize()
  }
  if (pieChart) {
    pieChart.resize()
  }
}

// 组件挂载
onMounted(() => {
  fetchStats()
  fetchRecentActivities()
  setTimeout(() => {
    initCharts()
  }, 100)
  window.addEventListener('resize', handleResize)
})

// 组件卸载
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (trendChart) {
    trendChart.dispose()
  }
  if (pieChart) {
    pieChart.dispose()
  }
})
</script>

<style scoped>
.stat-card {
  height: 100%;
  transition: all 0.3s ease;
}

.stat-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.stat-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #1890ff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}
</style>