<template>
  <div class="dashboard">
    <el-row :gutter="16">
      <el-col :span="6">
        <el-card
          v-loading="loading"
          class="stat-card user-card"
        >
          <el-statistic
            title="用户总数"
            :value="stats.userCount"
          >
            <template #prefix>
              <el-icon class="stat-icon user-icon">
                <User />
              </el-icon>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card
          v-loading="loading"
          class="stat-card role-card"
        >
          <el-statistic
            title="角色总数"
            :value="stats.roleCount"
          >
            <template #prefix>
              <el-icon class="stat-icon role-icon">
                <UserFilled />
              </el-icon>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card
          v-loading="loading"
          class="stat-card login-card"
        >
          <el-statistic
            title="今日登录"
            :value="stats.todayLogin"
          >
            <template #prefix>
              <el-icon class="stat-icon login-icon">
                <ArrowRight />
              </el-icon>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card
          v-loading="loading"
          class="stat-card log-card"
        >
          <el-statistic
            title="操作日志"
            :value="stats.operationLog"
          >
            <template #prefix>
              <el-icon class="stat-icon log-icon">
                <Document />
              </el-icon>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
    </el-row>
    <el-row
      :gutter="16"
      style="margin-top: 16px"
    >
      <el-col :span="12">
        <el-card
          v-loading="loading"
          title="最近登录"
          class="recent-login-card"
        >
          <template #header>
            <div class="card-header">
              <span class="card-title">最近登录</span>
              <el-icon class="header-icon">
                <Clock />
              </el-icon>
            </div>
          </template>
          <el-timeline>
            <el-timeline-item
              v-for="item in recentLogins"
              :key="item.id"
              :type="item.status === '0' ? 'success' : 'danger'"
              :timestamp="formatDateTime(item.loginTime)"
              placement="top"
            >
              <div class="login-item">
                <div class="login-user">
                  <el-icon><User /></el-icon>
                  <span>{{ item.username }}</span>
                </div>
                <div class="login-ip">
                  <el-icon><Location /></el-icon>
                  <span>{{ item.ip }}</span>
                </div>
              </div>
            </el-timeline-item>
            <el-timeline-item
              v-if="recentLogins.length === 0"
              placement="top"
            >
              <div class="empty-tip">
                暂无登录记录
              </div>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card
          v-loading="loading"
          title="系统信息"
          class="system-info-card"
        >
          <template #header>
            <div class="card-header">
              <span class="card-title">系统信息</span>
              <el-icon class="header-icon">
                <Setting />
              </el-icon>
            </div>
          </template>
          <el-descriptions
            :column="1"
            border
          >
            <el-descriptions-item label="系统版本">
              <div class="info-item">
                <el-icon><Star /></el-icon>
                <span>{{ systemInfo.version }}</span>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="Java版本">
              <div class="info-item">
                <el-icon><Cpu /></el-icon>
                <span>{{ systemInfo.javaVersion }}</span>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="前端框架">
              <div class="info-item">
                <el-icon><Monitor /></el-icon>
                <span>{{ systemInfo.frontendFramework }}</span>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="数据库">
              <div class="info-item">
                <el-icon><Coin /></el-icon>
                <span>{{ systemInfo.database }}</span>
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { User, UserFilled, ArrowRight, Document, Clock, Location, Setting, Star, Cpu, Monitor, Coin } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { formatDateTime } from '@/utils/dateFormat'

const loading = ref(false)
const stats = reactive({
  userCount: 0,
  roleCount: 0,
  todayLogin: 0,
  operationLog: 0
})

const recentLogins = ref<any[]>([])
const systemInfo = reactive({
  version: '1.0.0',
  javaVersion: '21',
  frontendFramework: 'Vue 3 + Element Plus',
  database: 'PostgreSQL'
})

const fetchStats = async () => {
  loading.value = true
  try {
    const [userCountRes, roleCountRes, todayLoginRes, operationLogRes] = await Promise.allSettled([
      request.get('/users/count'),
      request.get('/roles/count'),
      request.get('/logs/login/today/count'),
      request.get('/logs/operation/count')
    ])
    
    stats.userCount = userCountRes.status === 'fulfilled' ? Number(userCountRes.value || 0) : 0
    stats.roleCount = roleCountRes.status === 'fulfilled' ? Number(roleCountRes.value || 0) : 0
    stats.todayLogin = todayLoginRes.status === 'fulfilled' ? Number(todayLoginRes.value || 0) : 0
    stats.operationLog = operationLogRes.status === 'fulfilled' ? Number(operationLogRes.value || 0) : 0
  } catch (error) {
    console.error('Failed to fetch stats:', error)
  } finally {
    loading.value = false
  }
}

const fetchRecentLogins = async () => {
  try {
    const res: any = await request.get('/logs/login/recent?limit=10')
    recentLogins.value = res || []
  } catch (error) {
    console.error('Failed to fetch recent logins:', error)
    recentLogins.value = []
  }
}

onMounted(() => {
  fetchStats()
  fetchRecentLogins()
})
</script>

<style scoped lang="css">
.dashboard {
  padding: 16px;

  .stat-card {
    transition: all 0.3s ease;
    border-radius: 8px;

    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
    }

    .stat-icon {
      font-size: 24px;
      margin-right: 8px;
    }

    &.user-card {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;

      :deep(.el-statistic__head) {
        color: rgba(255, 255, 255, 0.9);
      }

      :deep(.el-statistic__content) {
        color: white;
      }
    }

    &.role-card {
      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      color: white;

      :deep(.el-statistic__head) {
        color: rgba(255, 255, 255, 0.9);
      }

      :deep(.el-statistic__content) {
        color: white;
      }
    }

    &.login-card {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      color: white;

      :deep(.el-statistic__head) {
        color: rgba(255, 255, 255, 0.9);
      }

      :deep(.el-statistic__content) {
        color: white;
      }
    }

    &.log-card {
      background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
      color: white;

      :deep(.el-statistic__head) {
        color: rgba(255, 255, 255, 0.9);
      }

      :deep(.el-statistic__content) {
        color: white;
      }
    }
  }

  .recent-login-card,
  .system-info-card {
    border-radius: 8px;
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-weight: 600;

      .card-title {
        font-size: 16px;
        color: #303133;
      }

      .header-icon {
        color: #409eff;
        font-size: 18px;
      }
    }

    .login-item {
      .login-user,
      .login-ip {
        display: flex;
        align-items: center;
        gap: 6px;
        margin: 4px 0;
        font-size: 14px;

        .el-icon {
          color: #409eff;
        }
      }

      .login-user {
        font-weight: 500;
        color: #303133;
      }

      .login-ip {
        color: #909399;
        font-size: 13px;
      }
    }

    .empty-tip {
      color: #909399;
      font-size: 14px;
      padding: 8px 0;
    }

    .info-item {
      display: flex;
      align-items: center;
      gap: 8px;

      .el-icon {
        color: #409eff;
        font-size: 16px;
      }

      span {
        color: #303133;
      }
    }
  }
}
</style>
