<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户登录统计</span>
        </div>
      </template>

      <!-- 筛选条件 -->
      <el-form :model="queryParams" inline class="search-form">
        <el-form-item label="统计类型">
          <el-radio-group v-model="queryParams.type" @change="handleTypeChange">
            <el-radio-button value="day">按日</el-radio-button>
            <el-radio-button value="week">按周</el-radio-button>
            <el-radio-button value="month">按月</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年份" v-if="queryParams.type === 'month'">
          <el-date-picker
            v-model="selectedYear"
            type="year"
            placeholder="选择年份"
            value-format="YYYY"
            style="width: 120px"
            @change="handleYearChange"
          />
        </el-form-item>
        <el-form-item label="时间范围" v-if="queryParams.type !== 'month'">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 240px"
            @change="handleDateRangeChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchData">
            <el-icon><Search /></el-icon>查询
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 统计概览 -->
      <el-row :gutter="20" class="stats-overview">
        <el-col :span="12">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-icon stat-icon-primary">
              <el-icon size="32"><User /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statsData.totalLogins?.toLocaleString() || 0 }}</div>
              <div class="stat-label">总登录次数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-icon stat-icon-success">
              <el-icon size="32"><UserFilled /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statsData.activeUsers?.toLocaleString() || '-' }}</div>
              <div class="stat-label">活跃用户数</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表区域 - 使用简单的CSS柱状图 -->
      <div class="chart-container" v-loading="loading">
        <div class="simple-chart" v-if="statsData.labels && statsData.labels.length > 0">
          <div class="chart-bars">
            <div
              v-for="(value, index) in statsData.values"
              :key="index"
              class="bar-item"
            >
              <div class="bar-wrapper">
                <div
                  class="bar"
                  :style="{ height: getBarHeight(value) + '%' }"
                  :title="`${statsData.labels[index]}: ${value?.toLocaleString() || 0} 次`"
                >
                  <span class="bar-value" v-if="value > 0">{{ formatValue(value) }}</span>
                </div>
              </div>
              <div class="bar-label">{{ formatLabel(statsData.labels[index]) }}</div>
            </div>
          </div>
        </div>
        <el-empty v-if="!loading && (!statsData.labels || statsData.labels.length === 0)" description="暂无数据" />
      </div>

      <!-- 数据表格 -->
      <el-table :data="tableData" border stripe style="margin-top: 20px" v-if="statsData.labels && statsData.labels.length > 0">
        <el-table-column label="时间" prop="label" min-width="120" />
        <el-table-column label="登录次数" align="right" width="150">
          <template #default="{ row }">
            <span class="number-text">{{ row.value?.toLocaleString() || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="占比" align="center" width="200">
          <template #default="{ row }">
            <el-progress
              :percentage="getPercentage(row.value)"
              :stroke-width="10"
              :show-text="true"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { Search, User, UserFilled } from '@element-plus/icons-vue'
import { getLoginStats, type LoginStatsQuery, type LoginStatsResponse } from '@/api/business/user'

// 数据
const loading = ref(false)
const statsData = ref<LoginStatsResponse>({
  labels: [],
  values: [],
  totalLogins: 0,
  activeUsers: null
})

// 日期范围
const dateRange = ref<[string, string] | null>(null)
const selectedYear = ref<string>(new Date().getFullYear().toString())

// 查询参数
const queryParams = reactive<LoginStatsQuery>({
  type: 'day',
  year: undefined,
  startDate: undefined,
  endDate: undefined
})

// 计算最大值
const maxValue = computed(() => {
  if (!statsData.value.values || statsData.value.values.length === 0) return 1
  return Math.max(...statsData.value.values, 1)
})

// 表格数据
const tableData = computed(() => {
  if (!statsData.value.labels) return []
  return statsData.value.labels.map((label, index) => ({
    label,
    value: statsData.value.values[index] || 0
  }))
})

// 获取柱状图高度百分比
const getBarHeight = (value: number) => {
  return Math.max((value / maxValue.value) * 100, 2)
}

// 获取百分比
const getPercentage = (value: number) => {
  if (statsData.value.totalLogins === 0) return 0
  return Math.round((value / statsData.value.totalLogins) * 100)
}

// 格式化数值
const formatValue = (value: number) => {
  if (value >= 10000) return (value / 10000).toFixed(1) + 'w'
  if (value >= 1000) return (value / 1000).toFixed(1) + 'k'
  return value.toString()
}

// 格式化标签
const formatLabel = (label: string) => {
  if (!label) return ''
  // 如果是日期格式，只显示月-日
  if (label.includes('-') && label.length === 10) {
    return label.slice(5)
  }
  return label
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    // 处理查询参数
    if (queryParams.type === 'month') {
      queryParams.year = selectedYear.value ? parseInt(selectedYear.value) : new Date().getFullYear()
      queryParams.startDate = undefined
      queryParams.endDate = undefined
    } else {
      queryParams.year = undefined
      if (dateRange.value && dateRange.value.length === 2) {
        queryParams.startDate = dateRange.value[0]
        queryParams.endDate = dateRange.value[1]
      } else {
        // 默认最近30天
        const endDate = new Date()
        const startDate = new Date()
        startDate.setDate(startDate.getDate() - 30)
        queryParams.startDate = startDate.toISOString().slice(0, 10)
        queryParams.endDate = endDate.toISOString().slice(0, 10)
      }
    }

    const res = await getLoginStats(queryParams)
    statsData.value = res.data
  } catch (error) {
    console.error('获取登录统计失败:', error)
  } finally {
    loading.value = false
  }
}

// 统计类型变化
const handleTypeChange = () => {
  // 重置日期选择
  if (queryParams.type === 'month') {
    dateRange.value = null
    selectedYear.value = new Date().getFullYear().toString()
  } else {
    // 默认最近30天
    const endDate = new Date()
    const startDate = new Date()
    if (queryParams.type === 'day') {
      startDate.setDate(startDate.getDate() - 30)
    } else {
      startDate.setDate(startDate.getDate() - 84) // 12周
    }
    dateRange.value = [
      startDate.toISOString().slice(0, 10),
      endDate.toISOString().slice(0, 10)
    ]
  }
  fetchData()
}

// 年份变化
const handleYearChange = () => {
  fetchData()
}

// 日期范围变化
const handleDateRangeChange = () => {
  fetchData()
}

onMounted(() => {
  // 设置默认日期范围（最近30天）
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(startDate.getDate() - 30)
  dateRange.value = [
    startDate.toISOString().slice(0, 10),
    endDate.toISOString().slice(0, 10)
  ]

  fetchData()
})
</script>

<style scoped>
.page-container {
  padding: 0;
}

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

.search-form {
  margin-bottom: 16px;
}

.stats-overview {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  transition: all 0.3s;
}

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

.stat-card :deep(.el-card__body) {
  display: flex;
  align-items: center;
  width: 100%;
}

.stat-icon {
  width: 64px;
  height: 64px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  margin-right: 16px;
}

.stat-icon-primary {
  background: linear-gradient(135deg, #79bbff 0%, #409EFF 100%);
}

.stat-icon-success {
  background: linear-gradient(135deg, #95d475 0%, #67c23a 100%);
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: var(--text-primary);
}

.stat-label {
  font-size: 14px;
  color: var(--text-secondary);
  margin-top: 4px;
}

.chart-container {
  min-height: 300px;
  position: relative;
}

.simple-chart {
  padding: 20px 0;
}

.chart-bars {
  display: flex;
  align-items: flex-end;
  justify-content: space-around;
  height: 250px;
  padding: 0 10px;
  gap: 4px;
  overflow-x: auto;
}

.bar-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 30px;
  flex: 1;
  max-width: 60px;
}

.bar-wrapper {
  height: 200px;
  width: 100%;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}

.bar {
  width: 80%;
  max-width: 40px;
  background: linear-gradient(180deg, #409EFF 0%, #79bbff 100%);
  border-radius: 4px 4px 0 0;
  transition: all 0.3s;
  cursor: pointer;
  position: relative;
  min-height: 4px;
}

.bar:hover {
  background: linear-gradient(180deg, #337ecc 0%, #409EFF 100%);
  transform: scaleX(1.1);
}

.bar-value {
  position: absolute;
  top: -20px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 11px;
  color: var(--text-secondary);
  white-space: nowrap;
}

.bar-label {
  margin-top: 8px;
  font-size: 11px;
  color: var(--text-secondary);
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
}

.number-text {
  font-family: 'Roboto Mono', monospace;
  font-weight: 500;
}
</style>
