<template>
  <div class="dashboard-container">
    <a-page-header
      title="仪表板"
      sub-title="系统概览和统计数据"
    >
      <template #extra>
        <a-space>
          <a-button @click="loadDashboardData">刷新</a-button>
          <a-button type="primary">导出数据</a-button>
        </a-space>
      </template>
    </a-page-header>

    <a-divider />

    <!-- 统计卡片 -->
    <a-row :gutter="16" class="stats-row">
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="总用户数"
            :value="dashboardData.stats.userCount"
            :precision="0"
            suffix="人"
          >
            <template #prefix>
              <UserOutlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="商家数量"
            :value="dashboardData.stats.merchantCount"
            :precision="0"
            suffix="家"
          >
            <template #prefix>
              <ShopOutlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="旅行计划"
            :value="dashboardData.stats.travelCount"
            :precision="0"
            suffix="个"
          >
            <template #prefix>
              <CompassOutlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="动物认领"
            :value="dashboardData.stats.animalCount"
            :precision="0"
            suffix="只"
          >
            <template #prefix>
              <HeartOutlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>

    <a-row :gutter="16" class="chart-row">
      <a-col :span="12">
        <a-card title="用户增长趋势" class="chart-card">
          <div ref="userGrowthChart" style="height: 300px;"></div>
        </a-card>
      </a-col>
      <a-col :span="12">
        <a-card title="订单统计" class="chart-card">
          <div ref="orderStatsChart" style="height: 300px;"></div>
        </a-card>
      </a-col>
    </a-row>

    <a-row :gutter="16" class="activity-row">
      <a-col :span="16">
        <a-card title="最近活动" class="activity-card">
          <a-list item-layout="horizontal" :data-source="dashboardData.activities">
            <template #renderItem="{ item }">
              <a-list-item>
                <a-list-item-meta
                  :description="item.description"
                >
                  <template #title>
                    <a>{{ item.title }}</a>
                  </template>
                  <template #avatar>
                    <a-avatar :src="item.avatar" />
                  </template>
                </a-list-item-meta>
                <div>{{ item.time }}</div>
              </a-list-item>
            </template>
          </a-list>
        </a-card>
      </a-col>
      <a-col :span="8">
        <a-card title="系统信息" class="info-card">
          <a-descriptions :column="1" bordered size="small">
            <a-descriptions-item label="系统版本">
              {{ appVersion }}
            </a-descriptions-item>
            <a-descriptions-item label="运行环境">
              {{ environment }}
            </a-descriptions-item>
            <a-descriptions-item label="启动时间">
              {{ startupTime }}
            </a-descriptions-item>
            <a-descriptions-item label="内存使用">
              256MB / 2GB
            </a-descriptions-item>
          </a-descriptions>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { UserOutlined, ShopOutlined, CompassOutlined, HeartOutlined } from '@ant-design/icons-vue'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useAppStore } from '@/stores/app'
import * as echarts from 'echarts'
import { 
  getDashboardData, 
  getUserGrowthData, 
  getOrderStatsData 
} from '@/api/dashboard'

// 定义仪表板数据结构
interface DashboardData {
  stats: {
    userCount: number
    newUserCount: number
    activeUserCount: number
    merchantCount: number
    newMerchantCount: number
    activeMerchantCount: number
    travelCount: number
    newTravelCount: number
    animalCount: number
    newAnimalCount: number
    orderCount: number
    newOrderCount: number
    orderAmount: number
    onlineUserCount: number
    systemLoad: number
  }
  activities: Array<{
    id: number
    title: string
    description: string
    avatar: string
    time: string
  }>
}

const appStore = useAppStore()

const appVersion = import.meta.env.VITE_APP_VERSION || '1.0.0'
const environment = import.meta.env.MODE || 'development'
const startupTime = new Date().toLocaleString()

// 仪表板数据
const dashboardData = ref<DashboardData>({
  stats: {
    userCount: 0,
    newUserCount: 0,
    activeUserCount: 0,
    merchantCount: 0,
    newMerchantCount: 0,
    activeMerchantCount: 0,
    travelCount: 0,
    newTravelCount: 0,
    animalCount: 0,
    newAnimalCount: 0,
    orderCount: 0,
    newOrderCount: 0,
    orderAmount: 0,
    onlineUserCount: 0,
    systemLoad: 0
  },
  activities: []
})

// 图表实例
const userGrowthChart = ref<HTMLDivElement | null>(null)
const orderStatsChart = ref<HTMLDivElement | null>(null)
let userGrowthChartInstance: echarts.ECharts | null = null
let orderStatsChartInstance: echarts.ECharts | null = null

// 加载仪表板数据
const loadDashboardData = async () => {
  try {
    // 检查用户是否已登录
    if (!appStore.state.user) {
      // 尝试重新初始化应用状态
      await appStore.initialize()
      
      // 如果仍然没有用户信息，则跳转到登录页
      if (!appStore.state.user) {
        window.location.href = '/login'
        return
      }
    }

    // 获取仪表板数据
    const response = await getDashboardData()
    if (response.success) {
      dashboardData.value = response.data
    }

    // 获取图表数据并更新图表
    await updateUserGrowthChart()
    await updateOrderStatsChart()
  } catch (error) {
    console.error('加载仪表板数据失败:', error)
  }
}

// 更新用户增长图表
const updateUserGrowthChart = async () => {
  try {
    const response = await getUserGrowthData(7)
    if (response.success && userGrowthChart.value) {
      // 初始化图表实例
      if (!userGrowthChartInstance) {
        userGrowthChartInstance = echarts.init(userGrowthChart.value)
      }
      
      // 配置图表选项
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: response.data.map((item: any) => item.date)
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: response.data.map((item: any) => item.count),
          type: 'line',
          smooth: true,
          areaStyle: {}
        }]
      }
      
      // 设置图表选项
      userGrowthChartInstance.setOption(option)
    }
  } catch (error) {
    console.error('加载用户增长数据失败:', error)
  }
}

// 更新订单统计图表
const updateOrderStatsChart = async () => {
  try {
    const response = await getOrderStatsData(7)
    if (response.success && orderStatsChart.value) {
      // 初始化图表实例
      if (!orderStatsChartInstance) {
        orderStatsChartInstance = echarts.init(orderStatsChart.value)
      }
      
      // 配置图表选项
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['订单数量', '订单金额']
        },
        xAxis: {
          type: 'category',
          data: response.data.map((item: any) => item.date)
        },
        yAxis: [
          {
            type: 'value',
            name: '订单数量'
          },
          {
            type: 'value',
            name: '订单金额',
            position: 'right'
          }
        ],
        series: [
          {
            name: '订单数量',
            data: response.data.map((item: any) => item.count),
            type: 'bar'
          },
          {
            name: '订单金额',
            data: response.data.map((item: any) => item.amount),
            type: 'line',
            yAxisIndex: 1
          }
        ]
      }
      
      // 设置图表选项
      orderStatsChartInstance.setOption(option)
    }
  } catch (error) {
    console.error('加载订单统计数据失败:', error)
  }
}

// 窗口大小改变时重置图表大小
const handleResize = () => {
  if (userGrowthChartInstance) {
    userGrowthChartInstance.resize()
  }
  if (orderStatsChartInstance) {
    orderStatsChartInstance.resize()
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadDashboardData()
  window.addEventListener('resize', handleResize)
})

// 组件卸载前清理资源
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  if (userGrowthChartInstance) {
    userGrowthChartInstance.dispose()
  }
  if (orderStatsChartInstance) {
    orderStatsChartInstance.dispose()
  }
})
</script>

<style scoped>
.dashboard-container {
  padding: 24px;
  background: #f5f5f5;
  min-height: calc(100vh - 64px);
}

.stats-row {
  margin-bottom: 24px;
}

.chart-row {
  margin-bottom: 24px;
}

.activity-row {
  margin-bottom: 24px;
}

.chart-card,
.info-card {
  height: 100%;
}

.chart-placeholder {
  text-align: center;
  padding: 40px 0;
  color: #ccc;
}

.chart-placeholder .anticon {
  font-size: 48px;
  margin-bottom: 16px;
}
</style>