<template>
  <div class="dashboard">
    <div class="dashboard-header">
      <h2 class="page-title">仪表盘</h2>
      <div class="dashboard-actions">
        <el-text type="info" size="small" v-if="dashboardStats.updateTime">
          最后更新: {{ new Date(dashboardStats.updateTime).toLocaleString() }}
        </el-text>
        <el-text type="success" size="small" v-if="dashboardStats.systemStats.uptime">
          系统运行: {{ dashboardStats.systemStats.uptime }}
        </el-text>
        <el-button 
          type="primary" 
          size="small" 
          :loading="loading"
          @click="fetchDashboardData"
        >
          刷新数据
        </el-button>
      </div>
    </div>
    
    <el-row :gutter="20" class="stats-row" v-loading="loading">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #409eff;">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ dashboardStats.userStats.totalUsers.toLocaleString() }}</div>
              <div class="stat-label">用户总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #67c23a;">
              <el-icon><UserFilled /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ dashboardStats.systemStats.adminCount }}</div>
              <div class="stat-label">管理员总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #e6a23c;">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ dashboardStats.userStats.activeUsers.toLocaleString() }}</div>
              <div class="stat-label">活跃用户</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #f56c6c;">
              <el-icon><ChatDotRound /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ dashboardStats.contentStats.totalConversations.toLocaleString() }}</div>
              <div class="stat-label">对话总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 内容统计行 -->
    <el-row :gutter="20" class="stats-row" v-loading="loading">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #909399;">
              <el-icon><ChatDotRound /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ dashboardStats.contentStats.totalMessages.toLocaleString() }}</div>
              <div class="stat-label">消息总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #67c23a;">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ dashboardStats.userStats.guestUsers.toLocaleString() }}</div>
              <div class="stat-label">访客用户</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #e6a23c;">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ dashboardStats.contentStats.emotionRecords.toLocaleString() }}</div>
              <div class="stat-label">情绪记录</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #f56c6c;">
              <el-icon><Setting /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ dashboardStats.aiServiceStats.totalApiCalls.toLocaleString() }}</div>
              <div class="stat-label">API调用总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- AI配置统计 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #909399;">
              <el-icon><Setting /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ aiStats.total }}</div>
              <div class="stat-label">AI配置总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #67c23a;">
              <el-icon><CircleCheck /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ aiStats.enabled }}</div>
              <div class="stat-label">已启用配置</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #f56c6c;">
              <el-icon><CircleClose /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ aiStats.disabled }}</div>
              <div class="stat-label">已禁用配置</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="background-color: #e6a23c;">
              <el-icon><Star /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ aiStats.default }}</div>
              <div class="stat-label">默认配置</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>用户增长趋势</span>
          </template>
          <div class="chart-container" ref="userChartRef"></div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card>
          <template #header>
            <span>最近登录</span>
          </template>
          <el-table :data="recentLogins" style="width: 100%" size="small">
            <el-table-column label="用户" min-width="120">
              <template #default="{ row }">
                <div class="user-info">
                  <el-avatar 
                    :size="32" 
                    :src="row.avatar" 
                    :alt="row.nickname || row.username"
                  >
                    {{ (row.nickname || row.username)?.charAt(0) }}
                  </el-avatar>
                  <div class="user-name">
                    <div class="nickname">{{ row.nickname || row.username }}</div>
                    <div class="username" v-if="row.nickname">@{{ row.username }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="timeDescription" label="时间" width="80" />
          </el-table>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card>
          <template #header>
            <span>AI配置调用排行</span>
          </template>
          <el-table
            :data="aiConfigCallStats"
            style="width: 100%"
            size="small"
            height="300"
            :default-sort="{ prop: 'callCount', order: 'descending' }"
          >
            <el-table-column prop="configName" label="配置" min-width="140" show-overflow-tooltip />
            <el-table-column prop="callCount" label="调用次数" width="100" sortable />
            <el-table-column label="状态" width="90">
              <template #default="{ row }">
                <el-tag v-if="row.isEnabled === 1" type="success" size="small">启用</el-tag>
                <el-tag v-else type="info" size="small">禁用</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { User, UserFilled, TrendCharts, ChatDotRound, Setting, CircleCheck, CircleClose, Star } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { countEnabledConfigs, countDisabledConfigs, countDefaultConfigs } from '@/api/aiconfig'
import { getDashboardStats, getUserGrowthTrends, getRecentLogins, getAiConfigCallStats, type DashboardStats, type UserGrowthTrend, type RecentLogin, type AiConfigCallStatsItem } from '@/api/dashboard'
import { ElMessage } from 'element-plus'

const userChartRef = ref<HTMLElement>()

// 仪表盘统计数据
const dashboardStats = reactive<DashboardStats>({
  userStats: {
    totalUsers: 0,
    todayNewUsers: 0,
    activeUsers: 0,
    guestUsers: 0
  },
  contentStats: {
    totalConversations: 0,
    totalMessages: 0,
    diaryPosts: 0,
    communityPosts: 0,
    emotionRecords: 0
  },
  aiServiceStats: {
    totalApiCalls: 0,
    todayApiCalls: 0,
    successfulCalls: 0,
    failedCalls: 0,
    avgResponseTime: 0,
    aiConfigCount: 0
  },
  systemStats: {
    adminCount: 0,
    achievementCount: 0,
    rewardCount: 0,
    uptime: ''
  },
  recentActivities: [],
  userGrowthTrends: [],
  recentLogins: [],
  updateTime: ''
})

const aiStats = reactive({
  total: 0,
  enabled: 0,
  disabled: 0,
  default: 0
})

const recentLogins = ref<RecentLogin[]>([])
const userGrowthTrends = ref<UserGrowthTrend[]>([])
const aiConfigCallStats = ref<AiConfigCallStatsItem[]>([])

const loading = ref(false)

onMounted(() => {
  initUserChart()
  fetchDashboardData()
})

// 获取仪表盘数据
const fetchDashboardData = async () => {
  loading.value = true
  try {
    // 获取仪表盘统计数据
    const statsRes = await getDashboardStats()
    if (statsRes.data) {
      Object.assign(dashboardStats, statsRes.data)
      // 如果响应中包含增长趋势和最近登录数据，直接使用
      if (statsRes.data.userGrowthTrends) {
        userGrowthTrends.value = statsRes.data.userGrowthTrends
      }
      if (statsRes.data.recentLogins) {
        recentLogins.value = statsRes.data.recentLogins
      }
    }

    // 如果主接口没有返回这些数据，单独获取
    if (!userGrowthTrends.value.length) {
      const trendsRes = await getUserGrowthTrends(7)
      if (trendsRes.data) {
        userGrowthTrends.value = trendsRes.data
      }
    }

    if (!recentLogins.value.length) {
      const loginsRes = await getRecentLogins(10)
      if (loginsRes.data) {
        recentLogins.value = loginsRes.data
      }
    }

    // 获取AI配置统计（保持原有逻辑）
    await fetchAiStats()

    // 获取AI配置调用排行
    await fetchAiConfigCallStats()
    
    // 更新图表数据
    updateUserChart()
    
    ElMessage.success('数据加载成功')
  } catch (error) {
    console.error('获取仪表盘数据失败:', error)
    ElMessage.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

// 获取AI配置统计
const fetchAiStats = async () => {
  try {
    const [enabledRes, disabledRes, defaultRes] = await Promise.all([
      countEnabledConfigs(),
      countDisabledConfigs(),
      countDefaultConfigs()
    ])
    aiStats.enabled = enabledRes.data
    aiStats.disabled = disabledRes.data
    aiStats.default = defaultRes.data
    aiStats.total = aiStats.enabled + aiStats.disabled
  } catch (error) {
    console.error('获取AI配置统计失败:', error)
  }
}

/**
 * 获取AI配置调用次数统计（按调用次数倒序）
 */
const fetchAiConfigCallStats = async () => {
  try {
    const res = await getAiConfigCallStats(10)
    aiConfigCallStats.value = res.data?.items || []
  } catch (error) {
    console.error('获取AI配置调用统计失败:', error)
  }
}

let userChart: any = null

const initUserChart = () => {
  if (!userChartRef.value) return
  
  userChart = echarts.init(userChartRef.value)
  
  // 初始化空图表
  updateUserChart()
  
  window.addEventListener('resize', () => {
    userChart?.resize()
  })
}

const updateUserChart = () => {
  if (!userChart || !userGrowthTrends.value.length) return
  
  // 处理日期标签，显示月-日格式
  const dates = userGrowthTrends.value.map(trend => {
    const date = new Date(trend.date)
    return `${date.getMonth() + 1}-${date.getDate()}`
  })
  
  const newUsersData = userGrowthTrends.value.map(trend => trend.newUsers)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const dataIndex = params[0].dataIndex
        const trend = userGrowthTrends.value[dataIndex]
        return `
          <div>
            <div>日期: ${trend.date}</div>
            <div>新增用户: ${trend.newUsers}</div>
            <div>累计用户: ${trend.totalUsers}</div>
          </div>
        `
      }
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        fontSize: 12
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        fontSize: 12
      }
    },
    series: [
      {
        name: '新增用户',
        type: 'line',
        data: newUsersData,
        smooth: true,
        itemStyle: {
          color: '#409eff'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ]
          }
        }
      }
    ]
  }
  
  userChart.setOption(option)
}
</script>

<style scoped lang="scss">
.dashboard {
  .dashboard-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .page-title {
      margin: 0;
      font-size: 24px;
      color: var(--ls-text);
    }
    
    .dashboard-actions {
      display: flex;
      align-items: center;
      gap: 15px;
    }
  }
  
  .stats-row {
    margin-bottom: 20px;
  }
  
  .stat-card {
    .stat-content {
      display: flex;
      align-items: center;
      gap: 20px;
      
      .stat-icon {
        width: 60px;
        height: 60px;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        font-size: 28px;
      }
      
      .stat-info {
        flex: 1;
        
        .stat-value {
          font-size: 28px;
          font-weight: bold;
          color: var(--ls-text);
          margin-bottom: 5px;
        }
        
        .stat-label {
          font-size: 14px;
          color: rgba(226, 232, 240, 0.65);
        }
      }
    }
  }
  
  .chart-container {
    height: 300px;
  }
  
  .user-info {
    display: flex;
    align-items: center;
    gap: 10px;
    
    .user-name {
      flex: 1;
      min-width: 0;
      
      .nickname {
        font-size: 14px;
        font-weight: 500;
        color: rgba(226, 232, 240, 0.9);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      
      .username {
        font-size: 12px;
        color: rgba(226, 232, 240, 0.6);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }
}
</style>
