<template>
  <div class="admin-dashboard">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>控制面板</h1>
      <p>欢迎使用后台管理系统</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <el-row :gutter="20">
        <el-col :xs="12" :sm="8" :md="4">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon users">
                <el-icon><User /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.totalUsers }}</div>
                <div class="stat-label">总用户数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="12" :sm="8" :md="4">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon vip">
                <el-icon><Key /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.vipUsers }}</div>
                <div class="stat-label">VIP用户</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="12" :sm="8" :md="4">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon codes">
                <el-icon><Ticket /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.totalCodes }}</div>
                <div class="stat-label">会员码总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="12" :sm="8" :md="4">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon predictions">
                <el-icon><TrendCharts /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.totalPredictions }}</div>
                <div class="stat-label">推测记录</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="12" :sm="8" :md="4">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon pv-total">
                <el-icon><View /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ pvStats.totalPV }}</div>
                <div class="stat-label">总访问量</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="12" :sm="8" :md="4">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon pv-today">
                <el-icon><Sunny /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ pvStats.todayPV }}</div>
                <div class="stat-label">今日访问</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- PV趋势图 -->
    <div class="pv-chart-section">
      <el-card>
        <template #header>
          <div class="card-header">
            <el-icon><DataLine /></el-icon>
            <span>访问量趋势</span>
            <div class="header-actions">
              <el-radio-group v-model="pvDays" size="small" @change="loadPVStats">
                <el-radio-button :value="7">近7天</el-radio-button>
                <el-radio-button :value="30">近30天</el-radio-button>
                <el-radio-button :value="90">近90天</el-radio-button>
              </el-radio-group>
            </div>
          </div>
        </template>
        <div ref="pvChartRef" class="pv-chart" v-loading="pvChartLoading"></div>
      </el-card>
    </div>

    <!-- 快捷操作 -->
    <div class="quick-actions">
      <el-card>
        <template #header>
          <div class="card-header">
            <el-icon><Operation /></el-icon>
            <span>快捷操作</span>
          </div>
        </template>
        
        <div class="actions-grid">
          <div class="action-item" @click="$router.push('/cpzsadmin/vip-code')">
            <div class="action-icon">
              <el-icon><Key /></el-icon>
            </div>
            <div class="action-text">
              <h3>会员码管理</h3>
              <p>生成和管理会员码</p>
            </div>
          </div>
          
          <div class="action-item" @click="$router.push('/cpzsadmin/excel-import')">
            <div class="action-icon">
              <el-icon><Document /></el-icon>
            </div>
            <div class="action-text">
              <h3>数据导入</h3>
              <p>导入Excel数据</p>
            </div>
          </div>
          
          <div class="action-item" @click="$router.push('/cpzsadmin/user-list')">
            <div class="action-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="action-text">
              <h3>用户管理</h3>
              <p>管理用户信息</p>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 系统信息 -->
    <div class="system-info">
      <el-row>
        <el-col :span="24">
          <el-card>
            <template #header>
              <div class="card-header">
                <el-icon><Clock /></el-icon>
                <span>最近操作</span>
                <div class="header-actions">
                  <el-button type="text" @click="$router.push('/cpzsadmin/operation-history')">
                    更多
                    <el-icon class="el-icon--right"><ArrowRight /></el-icon>
                  </el-button>
                </div>
              </div>
            </template>
            
            <div class="recent-actions">
              <el-table
                :data="historyList"
                v-loading="historyLoading"
                stripe
                style="width: 100%"
              >
                <el-table-column prop="operationTime" label="操作时间" width="180">
                  <template #default="{ row }">
                    {{ formatDate(row.operationTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="operationModule" label="操作模块" width="120">
                  <template #default="{ row }">
                    <el-tag>{{ getModuleText(row.operationModule) }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="operationType" label="操作类型" width="150">
                  <template #default="{ row }">
                    <el-tag :type="getOperationType(row.operationType)">
                      {{ row.operationType }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="userName" label="操作人" width="120">
                  <template #default="{ row }">
                    {{ row.userName || '-' }}
                  </template>
                </el-table-column>
                <el-table-column prop="operationResult" label="操作结果" width="100">
                  <template #default="{ row }">
                    <el-tag :type="row.operationResult === '成功' ? 'success' : 'danger'">
                      {{ row.operationResult }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="operationDetail" label="详细信息" min-width="200">
                  <template #default="{ row }">
                    {{ row.operationDetail || row.resultMessage || '-' }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { 
  User, 
  Key, 
  Ticket, 
  TrendCharts, 
  Operation, 
  Document, 
  Setting, 
  InfoFilled, 
  Clock,
  ArrowRight,
  View,
  Sunny,
  DataLine
} from '@element-plus/icons-vue'
import { userStore } from '../../store/user.js'
import { lotteryApi } from '../../api/index.js'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'

export default {
  name: 'AdminDashboard',
  components: {
    User,
    Key,
    Ticket,
    TrendCharts,
    Operation,
    Document,
    Setting,
    InfoFilled,
    Clock,
    ArrowRight,
    View,
    Sunny,
    DataLine
  },
  setup() {
    const router = useRouter()
    
    // 统计数据
    const stats = reactive({
      totalUsers: 0,
      vipUsers: 0,
      totalCodes: 0,
      totalPredictions: 0
    })

    // PV统计数据
    const pvStats = reactive({
      totalPV: 0,
      todayPV: 0
    })

    // PV图表相关
    const pvChartRef = ref(null)
    const pvDays = ref(7)
    const pvChartLoading = ref(false)
    let pvChart = null

    // 管理员信息
    const adminInfo = reactive({
      userName: '管理员'
    })

    // 当前时间
    const currentTime = ref('')
    let timeInterval = null
    let loginCheckInterval = null // 新增登录检查定时器

    // 操作历史
    const historyList = ref([])
    const historyLoading = ref(false)
    
    // 检查登录状态
    const checkLoginStatus = () => {
      if (!userStore.isAdminLoggedIn()) {
        console.log('定期检查发现管理员登录态已过期，正在跳转到登录页...')
        userStore.adminLogout()
        router.push('/cpzsadmin/login')
      }
    }

    // 更新时间
    const updateTime = () => {
      currentTime.value = new Date().toLocaleString('zh-CN')
    }

    // 加载统计数据
    const loadStats = async () => {
      try {
        console.log('开始加载统计数据...')
        
        // 首先检查登录状态
        if (!userStore.isAdminLoggedIn()) {
          console.log('检测到管理员未登录或登录态已过期，正在跳转到登录页...')
          userStore.adminLogout() // 清除可能存在的过期会话
          router.push('/cpzsadmin/login')
          return
        }
        
        // 获取用户统计数据
        const userCountResponse = await lotteryApi.getUserCount()
        if (userCountResponse && userCountResponse.success) {
          stats.totalUsers = userCountResponse.data.totalUserCount || 0
          stats.vipUsers = userCountResponse.data.vipUserCount || 0
        } else {
          console.error('获取用户统计数据失败:', userCountResponse?.message)
          // 使用默认值
          stats.totalUsers = 0
          stats.vipUsers = 0
        }

        // 获取会员码统计数据
        console.log('开始获取会员码统计数据...')
        const vipCodeCountResponse = await lotteryApi.getVipCodeCount()
        if (vipCodeCountResponse && vipCodeCountResponse.success) {
          stats.totalCodes = vipCodeCountResponse.data.totalCount || 0
          console.log('设置会员码总数:', stats.totalCodes)
        } else {
          console.error('获取会员码统计数据失败:', vipCodeCountResponse?.message)
          stats.totalCodes = 0
        }

        // 获取推测记录总数
        console.log('开始获取推测记录总数...')
        const totalPredictResponse = await lotteryApi.getTotalPredictCount()
        console.log('推测记录总数API响应:', totalPredictResponse)
        if (totalPredictResponse && totalPredictResponse.success) {
          stats.totalPredictions = totalPredictResponse.data.totalCount || 0
          console.log('设置推测记录总数:', stats.totalPredictions)
        } else {
          console.error('获取推测记录总数失败:', totalPredictResponse?.message)
          stats.totalPredictions = 0
        }
        console.log('统计数据加载完成:', stats)
      } catch (error) {
        console.error('加载统计数据失败:', error)
        // 发生错误时使用默认值
        stats.totalUsers = 0
        stats.vipUsers = 0
        stats.totalCodes = 0
        stats.totalPredictions = 0
      }
    }

    // 加载PV统计数据
    const loadPVStats = async () => {
      try {
        pvChartLoading.value = true
        
        // 获取总PV
        const totalResponse = await lotteryApi.getTotalPageViews()
        if (totalResponse && totalResponse.success) {
          pvStats.totalPV = totalResponse.data || 0
        }

        // 获取今日PV
        const todayResponse = await lotteryApi.getTodayPageViews()
        if (todayResponse && todayResponse.success) {
          pvStats.todayPV = todayResponse.data || 0
        }

        // 获取近N天PV统计并渲染图表
        const statsResponse = await lotteryApi.getPageViewsByDays(pvDays.value)
        if (statsResponse && statsResponse.success) {
          const data = statsResponse.data || {}
          renderPVChart(data)
        }
      } catch (error) {
        console.error('加载PV统计数据失败:', error)
      } finally {
        pvChartLoading.value = false
      }
    }

    // 渲染PV图表
    const renderPVChart = (data) => {
      if (!pvChartRef.value) return

      // 初始化或获取图表实例
      if (!pvChart) {
        pvChart = echarts.init(pvChartRef.value)
      }

      // 将数据按日期排序
      const sortedDates = Object.keys(data).sort()
      const values = sortedDates.map(date => data[date])

      // 格式化日期显示（只显示月-日）
      const formattedDates = sortedDates.map(date => {
        const parts = date.split('-')
        return `${parts[1]}-${parts[2]}`
      })

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: (params) => {
            const idx = params[0].dataIndex
            return `${sortedDates[idx]}<br/>访问量: ${params[0].value}`
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: formattedDates,
          axisLine: {
            lineStyle: {
              color: '#e0e0e0'
            }
          },
          axisLabel: {
            color: '#666',
            rotate: pvDays.value > 7 ? 45 : 0
          }
        },
        yAxis: {
          type: 'value',
          minInterval: 1,
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: '#f0f0f0'
            }
          },
          axisLabel: {
            color: '#666'
          }
        },
        series: [
          {
            name: '访问量',
            type: 'line',
            data: values,
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            lineStyle: {
              width: 3,
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#409EFF' },
                { offset: 1, color: '#67C23A' }
              ])
            },
            itemStyle: {
              color: '#409EFF',
              borderColor: '#fff',
              borderWidth: 2
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
                { offset: 1, color: 'rgba(103, 194, 58, 0.05)' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: '#409EFF',
                borderColor: '#409EFF',
                borderWidth: 3,
                shadowColor: 'rgba(64, 158, 255, 0.5)',
                shadowBlur: 10
              }
            }
          }
        ]
      }

      pvChart.setOption(option)
    }

    // 窗口大小变化时调整图表大小
    const handleResize = () => {
      if (pvChart) {
        pvChart.resize()
      }
    }

    // 加载操作历史
    const loadOperationHistory = async () => {
      try {
        historyLoading.value = true
        
        // 构建查询参数
        const params = {
          // 不传任何过滤条件，获取全部历史
        }
        
        // 调用统一接口获取操作历史
        const response = await lotteryApi.getOperationHistoryList(params)
        console.log('操作历史接口响应:', response)
        
        if (response && response.success) {
          // 处理响应数据
          const data = response.data || []
          
          // 取前10条记录
          historyList.value = data.slice(0, 10)
        } else {
          historyList.value = []
        }
      } catch (error) {
        console.error('加载操作历史失败:', error)
        historyList.value = []
      } finally {
        historyLoading.value = false
      }
    }

    // 获取操作模块文本
    const getModuleText = (module) => {
      const modules = {
        0: '会员码管理',
        1: 'Excel导入',
        2: '用户管理'
      }
      return modules[module] || '未知模块'
    }

    // 获取操作类型标签样式
    const getOperationType = (type) => {
      const types = {
        '完整数据导入': 'primary',
        '开奖数据覆盖导入': 'warning',
        '开奖数据追加': 'success',
        '生成会员码': 'info',
        '删除会员码': 'danger'
      }
      return types[type] || 'info'
    }

    // 格式化日期
    const formatDate = (dateStr) => {
      if (!dateStr) return '-'
      
      const date = new Date(dateStr)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    }

    // 获取管理员信息
    const loadAdminInfo = () => {
      const user = userStore.getUserInfo()
      if (user) {
        adminInfo.userName = user.userName || user.username || '管理员'
      }
    }

    onMounted(async () => {
      console.log('Dashboard组件已挂载，开始初始化...')
      loadStats()
      loadOperationHistory()
      loadAdminInfo()
      
      // 启动时间更新
      updateTime()
      timeInterval = setInterval(updateTime, 1000)
      
      // 定期检查登录状态（每60秒检查一次）
      loginCheckInterval = setInterval(checkLoginStatus, 60000)
      
      // 加载PV统计数据
      await nextTick()
      loadPVStats()
      
      // 监听窗口大小变化
      window.addEventListener('resize', handleResize)
    })

    onUnmounted(() => {
      if (timeInterval) {
        clearInterval(timeInterval)
      }
      
      if (loginCheckInterval) {
        clearInterval(loginCheckInterval)
      }
      
      // 清理图表实例
      if (pvChart) {
        pvChart.dispose()
        pvChart = null
      }
      
      // 移除窗口大小变化监听
      window.removeEventListener('resize', handleResize)
    })

    return {
      stats,
      pvStats,
      pvChartRef,
      pvDays,
      pvChartLoading,
      loadPVStats,
      adminInfo,
      currentTime,
      historyList,
      historyLoading,
      getModuleText,
      getOperationType,
      formatDate
    }
  }
}
</script>

<style scoped>
.admin-dashboard {
  padding: 20px;
}

/* 页面标题 */
.page-header {
  margin-bottom: 24px;
  background: linear-gradient(135deg, #3a7bd5, #00d2ff);
  padding: 30px;
  border-radius: 8px;
  color: white;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.page-header h1 {
  font-size: 28px;
  font-weight: 600;
  color: white;
  margin-bottom: 8px;
  text-align: center;
}

.page-header p {
  color: rgba(255, 255, 255, 0.9);
  font-size: 16px;
  margin: 0;
  text-align: center;
}

/* 统计卡片 */
.stats-grid {
  margin-bottom: 24px;
}

.stat-card {
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
}

.stat-icon.users {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.stat-icon.vip {
  background: linear-gradient(135deg, #28a745, #20c997);
}

.stat-icon.codes {
  background: linear-gradient(135deg, #fd7e14, #ffc107);
}

.stat-icon.predictions {
  background: linear-gradient(135deg, #17a2b8, #6f42c1);
}

.stat-icon.pv-total {
  background: linear-gradient(135deg, #e74c3c, #c0392b);
}

.stat-icon.pv-today {
  background: linear-gradient(135deg, #f39c12, #e67e22);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

/* PV图表区域 */
.pv-chart-section {
  margin-bottom: 24px;
}

.pv-chart {
  width: 100%;
  height: 300px;
}

/* 快捷操作 */
.quick-actions {
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #333;
}

.card-header .el-icon {
  font-size: 18px;
  color: #409EFF;
}

.header-actions {
  margin-left: auto; /* Push content to the right */
}

.actions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-item:hover {
  border-color: #409EFF;
  background-color: #f0f9ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.action-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  background: linear-gradient(135deg, #409EFF, #67c23a);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.action-text h3 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 4px 0;
}

.action-text p {
  font-size: 14px;
  color: #666;
  margin: 0;
}

/* 系统信息 */
.system-info {
  margin-bottom: 24px;
}

.info-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  font-weight: 600;
  color: #333;
}

.info-value {
  color: #666;
}

/* 最近操作 */
.recent-actions {
  max-height: 200px;
  overflow-y: auto;
}

.empty-actions {
  text-align: center;
  color: #999;
  padding: 40px 20px;
}

.action-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.action-record {
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid #409EFF;
}

.action-time {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.action-desc {
  font-size: 14px;
  color: #333;
  line-height: 1.4;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .admin-dashboard {
    padding: 15px;
  }

  .stats-grid .el-col {
    margin-bottom: 16px;
  }

  .actions-grid {
    grid-template-columns: 1fr;
  }

  .system-info .el-col {
    margin-bottom: 16px;
  }
}
</style> 