<template>
  <div class="error-statistics-page admin-theme">
    <AdminSidebar active="errorStats" />

    <!-- 主内容区域 -->
    <main class="main-content">
      <AdminHeader :title="$t('errorStats.title')" />

      <!-- 内容包装器 -->
      <div class="content-wrapper">
        <!-- 统计卡片 -->
        <div class="stats-cards" :spinning="loading">
        <div class="stat-card">
          <div class="stat-icon error">
            <WarningOutlined />
          </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">
            <ClockCircleOutlined />
          </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">
            <CalendarOutlined />
          </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>
            <a-select v-model:value="selectedDays" @change="loadStatistics" class="days-select">
              <a-select-option :label="$t('errorStats.last7Days')" :value="7"></a-select-option>
              <a-select-option :label="$t('errorStats.last30Days')" :value="30"></a-select-option>
              <a-select-option :label="$t('errorStats.last90Days')" :value="90"></a-select-option>
            </a-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>
            <a-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>
          <a-button type="primary" size="small" @click="loadRecentErrors">{{ $t('errorStats.refresh') }}</a-button>
        </div>
        <a-table :data="recentErrors" :spinning="tableLoading" stripe>
          <a-table-column prop="createdAt" :label="$t('errorStats.time')" width="180">
            <template #default="{ row }">
              {{ formatDate(row.createdAt) }}
            </template>
          </a-table-column>
          <a-table-column prop="errorType" :label="$t('errorStats.errorType')" width="150">
            <template #default="{ row }">
              <a-tag :type="getTagType(row.errorType)">{{ row.errorType }}</a-tag>
            </template>
          </a-table-column>
          <a-table-column prop="username" :label="$t('errorStats.user')" width="120" />
          <a-table-column prop="taskId" :label="$t('errorStats.taskId')" width="200" />
          <a-table-column prop="errorMessage" :label="$t('errorStats.errorMessage')" show-overflow-tooltip />
        </a-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <a-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 { message } from 'ant-design-vue'
import { useI18n } from 'vue-i18n'
import {
  WarningOutlined,
  ClockCircleOutlined,
  CalendarOutlined
} from '@ant-design/icons-vue'
import request from '@/api/request'
import AdminSidebar from '@/components/AdminSidebar.vue'
import AdminHeader from '@/components/AdminHeader.vue'

const { t } = useI18n()

// 状态
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 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)
    message.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)
    message.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 = ['var(--error-400)', 'var(--warning-500)', 'var(--primary-500)', 'var(--accent-400)', 'var(--text-disabled)', 'var(--warning-600)', 'var(--secondary-500)', 'var(--accent-600)']
  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'
}

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

<style scoped>
.error-statistics-page {
  display: flex;
  height: 100vh;
  background: var(--bg-base);
  font-family: var(--font-sans);
}

/* 主内容区域 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: var(--bg-base);
  overflow-y: auto;
  padding: 0;
}

/* 内容包装器 */
.content-wrapper {
  padding: var(--space-6);
  flex: 1;
  overflow-y: auto;
}

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

.stat-card {
  background: var(--bg-surface);
  border-radius: var(--radius-lg);
  padding: var(--space-5);
  display: flex;
  align-items: center;
  gap: var(--space-4);
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: var(--radius-md);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: var(--text-2xl);
}

.stat-icon.error {
  background: var(--error-glow);
  color: var(--error-400);
}

.stat-icon.today {
  background: var(--warning-glow);
  color: var(--warning-500);
}

.stat-icon.week {
  background: var(--primary-glow-light);
  color: var(--primary-500);
}

.stat-icon.users {
  background: var(--accent-glow);
  color: var(--accent-400);
}

.stat-content {
  flex: 1;
}

.stat-title {
  font-size: var(--text-sm);
  color: var(--text-disabled);
  margin-bottom: var(--space-1);
}

.stat-number {
  font-size: var(--text-3xl);
  font-weight: var(--font-semibold);
  color: var(--text-primary);
}

/* 图表区域 */
.charts-section {
  margin-bottom: var(--space-8);
}

.chart-card {
  background: var(--bg-surface);
  border-radius: var(--radius-lg);
  padding: var(--space-5);
}

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

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--space-5);
}

.chart-header h3 {
  margin: 0;
  font-size: var(--text-lg);
  color: var(--text-primary);
}

.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: var(--text-primary);
  font-size: var(--text-sm);
}

.type-count {
  color: var(--text-disabled);
  font-size: var(--text-xs);
}

.type-bar {
  flex: 1;
  height: 8px;
  background: var(--bg-active);
  border-radius: var(--radius-sm);
  overflow: hidden;
}

.type-bar-fill {
  height: 100%;
  border-radius: var(--radius-sm);
  transition: width var(--duration-slow) var(--ease-default);
}

.type-percentage {
  width: 60px;
  text-align: right;
  color: var(--text-disabled);
  font-size: var(--text-xs);
}

/* 最近错误区域 */
.recent-errors-section {
  background: var(--bg-surface);
  border-radius: var(--radius-lg);
  padding: var(--space-5);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--space-5);
}

.section-header h3 {
  margin: 0;
  font-size: var(--text-lg);
  color: var(--text-primary);
}

.pagination-wrapper {
  margin-top: var(--space-5);
  display: flex;
  justify-content: flex-end;
}

/* ========================================
   Ant Design 暗底白字覆盖
   ======================================== */

/* 表格 */
:deep(.ant-table) {
  background: transparent !important;
  color: var(--text-primary, #E2E8F0) !important;
}

:deep(.ant-table-thead > tr > th),
:deep(.ant-table-thead > tr > td) {
  background: var(--bg-elevated, #1A1D2E) !important;
  color: var(--text-secondary, #94A3B8) !important;
  border-bottom-color: var(--border-subtle, rgba(255, 255, 255, 0.08)) !important;
}

:deep(.ant-table-tbody > tr > td) {
  background: var(--bg-surface, #111427) !important;
  color: var(--text-primary, #E2E8F0) !important;
  border-bottom-color: var(--border-subtle, rgba(255, 255, 255, 0.08)) !important;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background: var(--bg-hover, rgba(255, 255, 255, 0.04)) !important;
}

:deep(.ant-table-wrapper .ant-table-container),
:deep(.ant-table-content) {
  background: transparent !important;
}

:deep(.ant-table-cell) {
  color: var(--text-primary, #E2E8F0) !important;
}

:deep(.ant-table-placeholder) {
  background: var(--bg-surface, #111427) !important;
  color: var(--text-tertiary, #64748B) !important;
}

:deep(.ant-table-placeholder .ant-empty-description) {
  color: var(--text-tertiary, #64748B) !important;
}

/* 分页器 */
:deep(.ant-pagination) {
  color: var(--text-secondary, #94A3B8);
}

:deep(.ant-pagination-item) {
  background: var(--bg-elevated, #1A1D2E) !important;
  border-color: var(--border-subtle, rgba(255, 255, 255, 0.08)) !important;
}

:deep(.ant-pagination-item a) {
  color: var(--text-secondary, #94A3B8) !important;
}

:deep(.ant-pagination-item-active) {
  background: var(--primary-500, #3B82F6) !important;
  border-color: var(--primary-500, #3B82F6) !important;
}

:deep(.ant-pagination-item-active a) {
  color: #fff !important;
}

:deep(.ant-pagination-prev .ant-pagination-item-link),
:deep(.ant-pagination-next .ant-pagination-item-link) {
  background: var(--bg-elevated, #1A1D2E) !important;
  border-color: var(--border-subtle, rgba(255, 255, 255, 0.08)) !important;
  color: var(--text-secondary, #94A3B8) !important;
}

:deep(.ant-pagination-disabled .ant-pagination-item-link) {
  color: var(--text-disabled, #475569) !important;
}

/* 下拉选择器 */
:deep(.ant-select-selector) {
  background: var(--bg-elevated, #1A1D2E) !important;
  border-color: var(--border-default, rgba(255, 255, 255, 0.12)) !important;
  color: var(--text-primary, #E2E8F0) !important;
}

:deep(.ant-select-selection-item) {
  color: var(--text-primary, #E2E8F0) !important;
}

:deep(.ant-select-arrow) {
  color: var(--text-tertiary, #64748B) !important;
}

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

@media (max-width: 768px) {
  .error-statistics-page {
    flex-direction: column;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
  }
}
</style>
