<template>
  <div class="error-statistics-page">
    <!-- 左侧导航栏 -->
    <aside class="sidebar">
      <div class="logo">
        <img src="/images/backgrounds/logo-admin.svg" alt="Logo" />
      </div>
      
      <nav class="nav-menu">
        <div class="nav-item" @click="goToDashboard">
          <el-icon><Grid /></el-icon>
          <span>{{ $t('nav.dashboard') }}</span>
        </div>
        <div class="nav-item" @click="goToMembers">
          <el-icon><User /></el-icon>
          <span>{{ $t('nav.members') }}</span>
        </div>
        <div class="nav-item" @click="goToOrders">
          <el-icon><ShoppingCart /></el-icon>
          <span>{{ $t('nav.orders') }}</span>
        </div>
        <div class="nav-item" @click="goToAPI">
          <el-icon><Document /></el-icon>
          <span>{{ $t('nav.apiManagement') }}</span>
        </div>
        <div class="nav-item" @click="goToTasks">
          <el-icon><Document /></el-icon>
          <span>{{ $t('nav.tasks') }}</span>
        </div>
        <div class="nav-item active">
          <el-icon><Warning /></el-icon>
          <span>{{ $t('nav.errorStats') }}</span>
        </div>
        <div class="nav-item" @click="goToSettings">
          <el-icon><Setting /></el-icon>
          <span>{{ $t('nav.systemSettings') }}</span>
        </div>
      </nav>

      <div class="sidebar-footer">
        <div class="online-users">
          {{ $t('nav.todayVisitors') }}: <span class="highlight">{{ onlineUsers }}</span>
        </div>
        <div class="system-uptime">
          {{ $t('nav.systemUptime') }}: <span class="highlight">{{ systemUptime }}</span>
        </div>
      </div>
    </aside>

    <!-- 主内容区域 -->
    <main class="main-content">
      <!-- 顶部搜索栏 -->
      <header class="top-header">
        <div class="page-title">
          <h2>{{ $t('errorStats.title') }}</h2>
        </div>
        <div class="header-actions">
          <LanguageSwitcher />
          <el-dropdown @command="handleUserCommand">
            <div class="user-avatar">
              <img src="/images/backgrounds/avatar-default.svg" :alt="$t('errorStats.userAvatar')" />
              <el-icon class="arrow-down"><ArrowDown /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="exitAdmin">
                  {{ $t('admin.exitAdmin') }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </header>

      <!-- 内容包装器 -->
      <div class="content-wrapper">
        <!-- 统计卡片 -->
        <div class="stats-cards" v-loading="loading">
        <div class="stat-card">
          <div class="stat-icon error">
            <el-icon><Warning /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-title">{{ $t('errorStats.totalErrors') }}</div>
            <div class="stat-number">{{ statistics.totalErrors || 0 }}</div>
          </div>
        </div>

        <div class="stat-card">
          <div class="stat-icon today">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-title">{{ $t('errorStats.todayErrors') }}</div>
            <div class="stat-number">{{ statistics.todayErrors || 0 }}</div>
          </div>
        </div>

        <div class="stat-card">
          <div class="stat-icon week">
            <el-icon><Calendar /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-title">{{ $t('errorStats.weekErrors') }}</div>
            <div class="stat-number">{{ statistics.weekErrors || 0 }}</div>
          </div>
        </div>

      </div>

      <!-- 错误类型分布 -->
      <div class="charts-section">
        <div class="chart-card full-width">
          <div class="chart-header">
            <h3>{{ $t('errorStats.errorTypeDistribution') }}</h3>
            <el-select v-model="selectedDays" @change="loadStatistics" class="days-select">
              <el-option :label="$t('errorStats.last7Days')" :value="7"></el-option>
              <el-option :label="$t('errorStats.last30Days')" :value="30"></el-option>
              <el-option :label="$t('errorStats.last90Days')" :value="90"></el-option>
            </el-select>
          </div>
          <div class="error-type-list">
            <div 
              v-for="(item, index) in errorTypeStats" 
              :key="item.type" 
              class="error-type-item"
            >
              <div class="type-info">
                <span class="type-name">{{ item.description || item.type }}</span>
                <span class="type-count">{{ item.count }} {{ $t('errorStats.times') }}</span>
              </div>
              <div class="type-bar">
                <div 
                  class="type-bar-fill" 
                  :style="{ width: getBarWidth(item.count) + '%', backgroundColor: getBarColor(index) }"
                ></div>
              </div>
              <div class="type-percentage">{{ getPercentage(item.count) }}%</div>
            </div>
            <el-empty v-if="errorTypeStats.length === 0" :description="$t('errorStats.noErrorData')" />
          </div>
        </div>
      </div>

      <!-- 最近错误列表 -->
      <div class="recent-errors-section">
        <div class="section-header">
          <h3>{{ $t('errorStats.recentErrors') }}</h3>
          <el-button type="primary" size="small" @click="loadRecentErrors">{{ $t('errorStats.refresh') }}</el-button>
        </div>
        <el-table :data="recentErrors" v-loading="tableLoading" stripe>
          <el-table-column prop="createdAt" :label="$t('errorStats.time')" width="180">
            <template #default="{ row }">
              {{ formatDate(row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column prop="errorType" :label="$t('errorStats.errorType')" width="150">
            <template #default="{ row }">
              <el-tag :type="getTagType(row.errorType)">{{ row.errorType }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="username" :label="$t('errorStats.user')" width="120" />
          <el-table-column prop="taskId" :label="$t('errorStats.taskId')" width="200" />
          <el-table-column prop="errorMessage" :label="$t('errorStats.errorMessage')" show-overflow-tooltip />
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="totalErrors"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next"
            @size-change="loadErrorLogs"
            @current-change="loadErrorLogs"
          />
        </div>
      </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
import {
  Grid,
  User,
  ShoppingCart,
  Document,
  Setting,
  ArrowDown,
  Warning,
  Clock,
  Calendar
} from '@element-plus/icons-vue'
import request from '@/api/request'
import LanguageSwitcher from '@/components/LanguageSwitcher.vue'

const { t } = useI18n()
const router = useRouter()

// 状态
const loading = ref(false)
const tableLoading = ref(false)
const selectedDays = ref(7)
const currentPage = ref(1)
const pageSize = ref(20)
const totalErrors = ref(0)
const onlineUsers = ref('0')
const systemUptime = ref('--')

// 数据
const statistics = ref({})
const errorTypeStats = ref([])
const recentErrors = ref([])
const errorTypes = ref({})

// 计算总数
const totalCount = computed(() => {
  return errorTypeStats.value.reduce((sum, item) => sum + item.count, 0)
})

// 加载统计数据
const loadStatistics = async () => {
  loading.value = true
  try {
    const res = await request.get('/admin/error-logs/statistics', {
      params: { days: selectedDays.value }
    })
    if (res.data.success) {
      const data = res.data.data || {}
      statistics.value = {
        totalErrors: data.totalErrors || 0,
        todayErrors: data.todayErrors || 0,
        weekErrors: data.weekErrors || 0
      }
      // 处理错误类型统计 - 后端返回的是 errorsByType
      if (data.errorsByType) {
        errorTypeStats.value = Object.entries(data.errorsByType).map(([type, count]) => ({
          type,
          description: errorTypes.value[type] || type,
          count
        })).sort((a, b) => b.count - a.count)
      }
    }
  } catch (error) {
    console.error('加载统计失败:', error)
    ElMessage.error(t('common.loadStatsFailed'))
  } finally {
    loading.value = false
  }
}

// 加载错误类型定义
const loadErrorTypes = async () => {
  try {
    const res = await request.get('/admin/error-logs/types')
    if (res.data.success) {
      errorTypes.value = res.data.data || {}
    }
  } catch (error) {
    console.error('加载错误类型失败:', error)
  }
}

// 加载错误日志列表
const loadErrorLogs = async () => {
  tableLoading.value = true
  try {
    const res = await request.get('/admin/error-logs', {
      params: {
        page: currentPage.value - 1,
        size: pageSize.value
      }
    })
    if (res.data.success) {
      recentErrors.value = res.data.data || []
      totalErrors.value = res.data.totalElements || 0
    }
  } catch (error) {
    console.error('加载错误日志失败:', error)
    ElMessage.error(t('common.loadErrorLogsFailed'))
  } finally {
    tableLoading.value = false
  }
}

// 加载最近错误
const loadRecentErrors = async () => {
  tableLoading.value = true
  try {
    const res = await request.get('/admin/error-logs/recent', {
      params: { limit: 20 }
    })
    if (res.data.success) {
      recentErrors.value = res.data.data || []
    }
  } catch (error) {
    console.error('加载最近错误失败:', error)
  } finally {
    tableLoading.value = false
  }
}

// 获取进度条宽度
const getBarWidth = (count) => {
  if (totalCount.value === 0) return 0
  return Math.min((count / totalCount.value) * 100, 100)
}

// 获取百分比
const getPercentage = (count) => {
  if (totalCount.value === 0) return 0
  return ((count / totalCount.value) * 100).toFixed(1)
}

// 获取进度条颜色
const getBarColor = (index) => {
  const colors = ['#f56c6c', '#e6a23c', '#409eff', '#67c23a', '#909399', '#b88230', '#8e44ad', '#16a085']
  return colors[index % colors.length]
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

// 获取标签类型
const getTagType = (errorType) => {
  const typeMap = {
    'API_ERROR': 'danger',
    'TASK_FAILED': 'warning',
    'PAYMENT_ERROR': 'danger',
    'AUTH_ERROR': 'info',
    'SYSTEM_ERROR': 'danger'
  }
  return typeMap[errorType] || 'info'
}

// 导航函数
const goToDashboard = () => router.push('/admin/dashboard')
const goToMembers = () => router.push('/member-management')
const goToOrders = () => router.push('/admin/orders')
const goToAPI = () => router.push('/api-management')
const goToTasks = () => router.push('/generate-task-record')
const goToSettings = () => router.push('/system-settings')

const handleUserCommand = (command) => {
  if (command === 'exitAdmin') {
    router.push('/profile')
  }
}

// 获取系统统计数据
const fetchSystemStats = async () => {
  try {
    const response = await fetch('/api/admin/online-stats', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    const data = await response.json()
    if (data.success) {
      onlineUsers.value = data.todayVisitors || 0
      systemUptime.value = data.uptime || '--'
    }
  } catch (error) {
    console.error('获取系统统计失败:', error)
  }
}

onMounted(async () => {
  fetchSystemStats()
  await loadErrorTypes()
  await loadStatistics()
  await loadErrorLogs()
})
</script>

<style scoped>
.error-statistics-page {
  display: flex;
  height: 100vh;
  background: #f8f9fa;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 左侧导航栏 */
.sidebar {
  width: 240px;
  background: #ffffff;
  border-right: 1px solid #e5e7eb;
  display: flex;
  flex-direction: column;
  padding: 24px 0;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.05);
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 24px;
  margin-bottom: 32px;
}

.logo img {
  width: 100%;
  height: auto;
  max-width: 180px;
  object-fit: contain;
}

.nav-menu {
  flex: 1;
  padding: 0 16px;
}

.nav-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  margin-bottom: 4px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  color: #4b5563;
  font-size: 14px;
  font-weight: 500;
}

.nav-item:hover {
  background: #f3f4f6;
  color: #1f2937;
}

.nav-item.active {
  background: rgba(64, 158, 255, 0.15);
  color: #409EFF;
}

.nav-item .el-icon {
  margin-right: 12px;
  font-size: 18px;
}

.nav-item span {
  font-size: 14px;
  font-weight: 500;
}

.sidebar-footer {
  padding: 20px;
  border-top: 1px solid #e5e7eb;
  background: #f9fafb;
  margin-top: auto;
  color: #4b5563;
}

.sidebar-footer .highlight {
  color: #409EFF;
  font-weight: 600;
}

.online-users,
.system-uptime {
  font-size: 14px;
  color: #64748b;
  margin-bottom: 5px;
  line-height: 1.5;
}

/* 主内容区域 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #f8f9fa;
  overflow-y: auto;
  padding: 0;
}

/* 顶部搜索栏 */
.top-header {
  background: #ffffff;
  padding: 16px 24px;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.page-title h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-avatar {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 6px;
  transition: background 0.2s ease;
}

.user-avatar:hover {
  background: #f3f4f6;
}

.user-avatar img {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
}

.arrow-down {
  color: #6b7280;
  font-size: 12px;
}

/* 内容包装器 */
.content-wrapper {
  padding: 24px;
  flex: 1;
  overflow-y: auto;
}

/* 统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.stat-icon.error {
  background: rgba(245, 108, 108, 0.2);
  color: #f56c6c;
}

.stat-icon.today {
  background: rgba(230, 162, 60, 0.2);
  color: #e6a23c;
}

.stat-icon.week {
  background: rgba(64, 158, 255, 0.2);
  color: #409eff;
}

.stat-icon.users {
  background: rgba(103, 194, 58, 0.2);
  color: #67c23a;
}

.stat-content {
  flex: 1;
}

.stat-title {
  font-size: 14px;
  color: #9ca3af;
  margin-bottom: 4px;
}

.stat-number {
  font-size: 28px;
  font-weight: 600;
}

/* 图表区域 */
.charts-section {
  margin-bottom: 30px;
}

.chart-card {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
}

.chart-card.full-width {
  width: 100%;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-header h3 {
  margin: 0;
  font-size: 18px;
}

.days-select {
  width: 120px;
}

/* 错误类型列表 */
.error-type-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.error-type-item {
  display: flex;
  align-items: center;
  gap: 16px;
}

.type-info {
  width: 200px;
  display: flex;
  justify-content: space-between;
}

.type-name {
  color: #333;
  font-size: 14px;
}

.type-count {
  color: #9ca3af;
  font-size: 13px;
}

.type-bar {
  flex: 1;
  height: 8px;
  background: #e5e7eb;
  border-radius: 4px;
  overflow: hidden;
}

.type-bar-fill {
  height: 100%;
  border-radius: 4px;
  transition: width 0.3s;
}

.type-percentage {
  width: 60px;
  text-align: right;
  color: #9ca3af;
  font-size: 13px;
}

/* 最近错误区域 */
.recent-errors-section {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  font-size: 18px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* Element Plus 样式覆盖 */
:deep(.el-table) {
  background: transparent;
  --el-table-bg-color: transparent;
  --el-table-tr-bg-color: transparent;
  --el-table-header-bg-color: #f5f5f5;
  --el-table-row-hover-bg-color: #f5f5f5;
  --el-table-border-color: #e5e7eb;
  color: #333;
}

:deep(.el-table th) {
  background: #f5f5f5 !important;
  color: #666;
}

:deep(.el-select) {
  --el-select-input-focus-border-color: #3b82f6;
}

:deep(.el-pagination) {
  --el-pagination-bg-color: transparent;
  --el-pagination-text-color: #9ca3af;
  --el-pagination-button-disabled-bg-color: transparent;
}

@media (max-width: 1200px) {
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .sidebar {
    display: none;
  }
}
</style>
