<template>
  <div class="dashboard-container">
    <!-- Date Range Filter -->
    <el-card class="filter-card">
      <el-form :inline="true" class="filter-form">
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="dateShortcuts"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchAllData" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- Key Metrics Cards -->
    <el-row :gutter="20" class="metrics-row">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="metric-card users">
          <div class="metric-content">
            <div class="metric-icon">
              <el-icon :size="40"><User /></el-icon>
            </div>
            <div class="metric-info">
              <div class="metric-value">{{ metrics.totalUsers }}</div>
              <div class="metric-label">总用户数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="metric-card appointments">
          <div class="metric-content">
            <div class="metric-icon">
              <el-icon :size="40"><Document /></el-icon>
            </div>
            <div class="metric-info">
              <div class="metric-value">{{ metrics.activeAppointments }}</div>
              <div class="metric-label">活跃预约</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="metric-card withdrawals">
          <div class="metric-content">
            <div class="metric-icon">
              <el-icon :size="40"><Wallet /></el-icon>
            </div>
            <div class="metric-info">
              <div class="metric-value">{{ metrics.pendingWithdrawals }}</div>
              <div class="metric-label">待审核提现</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="metric-card amount">
          <div class="metric-content">
            <div class="metric-icon">
              <el-icon :size="40"><Money /></el-icon>
            </div>
            <div class="metric-info">
              <div class="metric-value">¥{{ formatNumber(metrics.pendingWithdrawalAmount) }}</div>
              <div class="metric-label">待提现金额</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- Charts Row -->
    <el-row :gutter="20" class="charts-row">
      <!-- User Growth Trend Chart -->
      <el-col :xs="24" :lg="16">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>用户增长趋势</span>
              <el-radio-group v-model="growthGroupBy" size="small" @change="fetchUserGrowth">
                <el-radio-button label="day">按天</el-radio-button>
                <el-radio-button label="week">按周</el-radio-button>
                <el-radio-button label="month">按月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="userGrowthChartRef" class="chart-container" v-loading="chartLoading.userGrowth"></div>
        </el-card>
      </el-col>

      <!-- Invitation Conversion Stats -->
      <el-col :xs="24" :lg="8">
        <el-card shadow="hover" class="stats-card">
          <template #header>
            <div class="card-header">
              <span>邀请转化统计</span>
            </div>
          </template>
          <div class="conversion-stats" v-loading="chartLoading.conversion">
            <div class="conversion-rate">
              <div ref="conversionChartRef" class="conversion-chart"></div>
              <div class="rate-text">
                <span class="rate-value">{{ invitationStats.conversionRate }}%</span>
                <span class="rate-label">转化率</span>
              </div>
            </div>
            <div class="conversion-details">
              <div class="detail-item">
                <span class="label">总邀请数</span>
                <span class="value">{{ invitationStats.totalInvitations }}</span>
              </div>
              <div class="detail-item">
                <span class="label">已转化</span>
                <span class="value success">{{ invitationStats.convertedInvitations }}</span>
              </div>
              <div class="detail-item">
                <span class="label">累计奖励</span>
                <span class="value primary">¥{{ formatNumber(invitationStats.totalRewards) }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- Service Rankings and Financial Report -->
    <el-row :gutter="20" class="bottom-row">
      <!-- Service Popularity Rankings -->
      <el-col :xs="24" :lg="12">
        <el-card shadow="hover" class="ranking-card">
          <template #header>
            <div class="card-header">
              <span>服务热度排行榜</span>
              <el-tag type="info" size="small">Top {{ serviceRankings.length }}</el-tag>
            </div>
          </template>
          <div class="ranking-list" v-loading="chartLoading.rankings">
            <div
              v-for="(item, index) in serviceRankings"
              :key="item.serviceId"
              class="ranking-item"
            >
              <div class="rank-badge" :class="getRankClass(index)">
                {{ index + 1 }}
              </div>
              <div class="service-info">
                <div class="service-name">{{ item.serviceName.zh }}</div>
                <div class="service-category">{{ item.category?.name?.zh || '-' }}</div>
              </div>
              <div class="service-stats">
                <div class="stat-value">{{ item.appointmentCount }} 单</div>
                <div class="stat-revenue">¥{{ formatNumber(item.totalRevenue) }}</div>
              </div>
              <div class="progress-bar">
                <div
                  class="progress-fill"
                  :style="{ width: getProgressWidth(item.appointmentCount) }"
                ></div>
              </div>
            </div>
            <el-empty v-if="serviceRankings.length === 0" description="暂无数据" />
          </div>
        </el-card>
      </el-col>

      <!-- Financial Report -->
      <el-col :xs="24" :lg="12">
        <el-card shadow="hover" class="financial-card">
          <template #header>
            <div class="card-header">
              <span>财务报表</span>
            </div>
          </template>
          <div class="financial-report" v-loading="chartLoading.financial">
            <div class="financial-item">
              <div class="financial-icon revenue">
                <el-icon :size="24"><TrendCharts /></el-icon>
              </div>
              <div class="financial-info">
                <div class="financial-label">预约总收入</div>
                <div class="financial-value">¥{{ formatNumber(financialReport.totalAppointmentRevenue) }}</div>
              </div>
            </div>
            <div class="financial-item">
              <div class="financial-icon rewards">
                <el-icon :size="24"><Present /></el-icon>
              </div>
              <div class="financial-info">
                <div class="financial-label">已发放奖励</div>
                <div class="financial-value warning">¥{{ formatNumber(financialReport.totalRewardsPaid) }}</div>
              </div>
            </div>
            <div class="financial-item">
              <div class="financial-icon pending">
                <el-icon :size="24"><Clock /></el-icon>
              </div>
              <div class="financial-info">
                <div class="financial-label">待提现金额</div>
                <div class="financial-value danger">¥{{ formatNumber(financialReport.totalPendingWithdrawals) }}</div>
              </div>
            </div>
            <div class="financial-item">
              <div class="financial-icon completed">
                <el-icon :size="24"><CircleCheck /></el-icon>
              </div>
              <div class="financial-info">
                <div class="financial-label">已完成提现</div>
                <div class="financial-value">¥{{ formatNumber(financialReport.totalCompletedWithdrawals) }}</div>
              </div>
            </div>
            <div class="financial-item highlight">
              <div class="financial-icon platform">
                <el-icon :size="24"><Coin /></el-icon>
              </div>
              <div class="financial-info">
                <div class="financial-label">平台收入</div>
                <div class="financial-value primary">¥{{ formatNumber(financialReport.platformRevenue) }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import api from '@/utils/api'

// Date range state
const dateRange = ref([])
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// Loading states
const loading = ref(false)
const chartLoading = reactive({
  userGrowth: false,
  conversion: false,
  rankings: false,
  financial: false
})

// Data states
const metrics = reactive({
  totalUsers: 0,
  activeAppointments: 0,
  pendingWithdrawals: 0,
  pendingWithdrawalAmount: 0
})

const growthGroupBy = ref('day')
const userGrowthData = ref([])

const invitationStats = reactive({
  totalInvitations: 0,
  convertedInvitations: 0,
  conversionRate: 0,
  totalRewards: 0
})

const serviceRankings = ref([])
const maxAppointmentCount = ref(1)

const financialReport = reactive({
  totalRewardsPaid: 0,
  totalPendingWithdrawals: 0,
  totalCompletedWithdrawals: 0,
  totalAppointmentRevenue: 0,
  platformRevenue: 0
})

// Chart refs
const userGrowthChartRef = ref(null)
const conversionChartRef = ref(null)
let userGrowthChart = null
let conversionChart = null

// Get date params
function getDateParams() {
  const params = {}
  if (dateRange.value && dateRange.value.length === 2) {
    params.startDate = dateRange.value[0]
    params.endDate = dateRange.value[1]
  }
  return params
}

// Fetch dashboard metrics
async function fetchDashboardMetrics() {
  try {
    const params = getDateParams()
    const response = await api.get('/api/v1/admin/statistics/dashboard', { params })
    if (response.data.code === 0) {
      Object.assign(metrics, response.data.data)
    }
  } catch (error) {
    console.error('Failed to fetch dashboard metrics:', error)
  }
}

// Fetch user growth trends
async function fetchUserGrowth() {
  chartLoading.userGrowth = true
  try {
    const params = {
      ...getDateParams(),
      groupBy: growthGroupBy.value
    }
    const response = await api.get('/api/v1/admin/statistics/user-growth', { params })
    if (response.data.code === 0) {
      userGrowthData.value = response.data.data
      await nextTick()
      renderUserGrowthChart()
    }
  } catch (error) {
    console.error('Failed to fetch user growth:', error)
  } finally {
    chartLoading.userGrowth = false
  }
}

// Fetch invitation conversion rate
async function fetchInvitationStats() {
  chartLoading.conversion = true
  try {
    const params = getDateParams()
    const response = await api.get('/api/v1/admin/statistics/invitation-conversion', { params })
    if (response.data.code === 0) {
      Object.assign(invitationStats, response.data.data)
      await nextTick()
      renderConversionChart()
    }
  } catch (error) {
    console.error('Failed to fetch invitation stats:', error)
  } finally {
    chartLoading.conversion = false
  }
}

// Fetch service rankings
async function fetchServiceRankings() {
  chartLoading.rankings = true
  try {
    const params = {
      ...getDateParams(),
      limit: 10
    }
    const response = await api.get('/api/v1/admin/statistics/service-rankings', { params })
    if (response.data.code === 0) {
      serviceRankings.value = response.data.data
      maxAppointmentCount.value = Math.max(
        ...response.data.data.map(item => item.appointmentCount),
        1
      )
    }
  } catch (error) {
    console.error('Failed to fetch service rankings:', error)
  } finally {
    chartLoading.rankings = false
  }
}

// Fetch financial report
async function fetchFinancialReport() {
  chartLoading.financial = true
  try {
    const params = getDateParams()
    const response = await api.get('/api/v1/admin/statistics/financial-report', { params })
    if (response.data.code === 0) {
      Object.assign(financialReport, response.data.data)
    }
  } catch (error) {
    console.error('Failed to fetch financial report:', error)
  } finally {
    chartLoading.financial = false
  }
}

// Fetch all data
async function fetchAllData() {
  loading.value = true
  try {
    await Promise.all([
      fetchDashboardMetrics(),
      fetchUserGrowth(),
      fetchInvitationStats(),
      fetchServiceRankings(),
      fetchFinancialReport()
    ])
  } finally {
    loading.value = false
  }
}

// Handle date change
function handleDateChange() {
  fetchAllData()
}

// Render user growth chart
function renderUserGrowthChart() {
  if (!userGrowthChartRef.value) return

  if (!userGrowthChart) {
    userGrowthChart = echarts.init(userGrowthChartRef.value)
  }

  const xData = userGrowthData.value.map(item => item.period)
  const yData = userGrowthData.value.map(item => item.count)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xData,
      axisLabel: {
        rotate: 45,
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      minInterval: 1
    },
    series: [
      {
        name: '新增用户',
        type: 'bar',
        data: yData,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#409EFF' },
            { offset: 1, color: '#79bbff' }
          ]),
          borderRadius: [4, 4, 0, 0]
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#337ecc' },
              { offset: 1, color: '#409EFF' }
            ])
          }
        }
      }
    ]
  }

  userGrowthChart.setOption(option)
}

// Render conversion chart (gauge)
function renderConversionChart() {
  if (!conversionChartRef.value) return

  if (!conversionChart) {
    conversionChart = echarts.init(conversionChartRef.value)
  }

  const option = {
    series: [
      {
        type: 'gauge',
        startAngle: 180,
        endAngle: 0,
        min: 0,
        max: 100,
        splitNumber: 5,
        radius: '100%',
        center: ['50%', '80%'],
        axisLine: {
          lineStyle: {
            width: 15,
            color: [
              [0.3, '#f56c6c'],
              [0.7, '#e6a23c'],
              [1, '#67c23a']
            ]
          }
        },
        pointer: {
          icon: 'path://M12.8,0.7l12,40.1H0.7L12.8,0.7z',
          length: '60%',
          width: 8,
          offsetCenter: [0, '-30%'],
          itemStyle: {
            color: 'auto'
          }
        },
        axisTick: {
          length: 8,
          lineStyle: {
            color: 'auto',
            width: 1
          }
        },
        splitLine: {
          length: 12,
          lineStyle: {
            color: 'auto',
            width: 2
          }
        },
        axisLabel: {
          color: '#999',
          fontSize: 10,
          distance: -40,
          formatter: function (value) {
            return value + '%'
          }
        },
        title: {
          show: false
        },
        detail: {
          show: false
        },
        data: [
          {
            value: invitationStats.conversionRate
          }
        ]
      }
    ]
  }

  conversionChart.setOption(option)
}

// Helper functions
function formatNumber(num) {
  if (num === null || num === undefined) return '0.00'
  return parseFloat(num).toFixed(2)
}

function getRankClass(index) {
  if (index === 0) return 'gold'
  if (index === 1) return 'silver'
  if (index === 2) return 'bronze'
  return ''
}

function getProgressWidth(count) {
  return `${(count / maxAppointmentCount.value) * 100}%`
}

// Handle window resize
function handleResize() {
  userGrowthChart?.resize()
  conversionChart?.resize()
}

// Initialize
onMounted(() => {
  // Set default date range to last 30 days
  const end = new Date()
  const start = new Date()
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
  dateRange.value = [
    start.toISOString().split('T')[0],
    end.toISOString().split('T')[0]
  ]

  fetchAllData()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  userGrowthChart?.dispose()
  conversionChart?.dispose()
})
</script>


<style lang="scss" scoped>
.dashboard-container {
  .filter-card {
    margin-bottom: 20px;

    .filter-form {
      display: flex;
      align-items: center;
      gap: 16px;
    }
  }

  .metrics-row {
    margin-bottom: 20px;

    .metric-card {
      height: 120px;
      border-radius: 8px;
      overflow: hidden;
      transition: transform 0.3s;

      &:hover {
        transform: translateY(-4px);
      }

      .metric-content {
        display: flex;
        align-items: center;
        height: 100%;
        padding: 0 20px;
      }

      .metric-icon {
        width: 70px;
        height: 70px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 20px;
      }

      .metric-info {
        .metric-value {
          font-size: 28px;
          font-weight: 700;
          color: #303133;
          line-height: 1.2;
        }

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

      &.users {
        .metric-icon {
          background: linear-gradient(135deg, #409eff 0%, #79bbff 100%);
          color: white;
        }
      }

      &.appointments {
        .metric-icon {
          background: linear-gradient(135deg, #67c23a 0%, #95d475 100%);
          color: white;
        }
      }

      &.withdrawals {
        .metric-icon {
          background: linear-gradient(135deg, #e6a23c 0%, #f3d19e 100%);
          color: white;
        }
      }

      &.amount {
        .metric-icon {
          background: linear-gradient(135deg, #f56c6c 0%, #fab6b6 100%);
          color: white;
        }
      }
    }
  }

  .charts-row {
    margin-bottom: 20px;

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

      .chart-container {
        height: 350px;
      }
    }

    .stats-card {
      height: 100%;

      .conversion-stats {
        .conversion-rate {
          position: relative;
          display: flex;
          flex-direction: column;
          align-items: center;

          .conversion-chart {
            width: 100%;
            height: 150px;
          }

          .rate-text {
            position: absolute;
            bottom: 20px;
            text-align: center;

            .rate-value {
              display: block;
              font-size: 32px;
              font-weight: 700;
              color: #303133;
            }

            .rate-label {
              display: block;
              font-size: 14px;
              color: #909399;
            }
          }
        }

        .conversion-details {
          margin-top: 20px;
          padding-top: 20px;
          border-top: 1px solid #ebeef5;

          .detail-item {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px solid #f5f7fa;

            &:last-child {
              border-bottom: none;
            }

            .label {
              color: #909399;
            }

            .value {
              font-weight: 600;
              color: #303133;

              &.success {
                color: #67c23a;
              }

              &.primary {
                color: #409eff;
              }
            }
          }
        }
      }
    }
  }

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

      .ranking-list {
        .ranking-item {
          display: flex;
          align-items: center;
          padding: 12px 0;
          border-bottom: 1px solid #f5f7fa;
          position: relative;

          &:last-child {
            border-bottom: none;
          }

          .rank-badge {
            width: 28px;
            height: 28px;
            border-radius: 50%;
            background: #909399;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: 600;
            margin-right: 12px;
            flex-shrink: 0;

            &.gold {
              background: linear-gradient(135deg, #ffd700 0%, #ffb800 100%);
            }

            &.silver {
              background: linear-gradient(135deg, #c0c0c0 0%, #a8a8a8 100%);
            }

            &.bronze {
              background: linear-gradient(135deg, #cd7f32 0%, #b87333 100%);
            }
          }

          .service-info {
            flex: 1;
            min-width: 0;

            .service-name {
              font-weight: 500;
              color: #303133;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }

            .service-category {
              font-size: 12px;
              color: #909399;
              margin-top: 2px;
            }
          }

          .service-stats {
            text-align: right;
            margin-left: 12px;
            flex-shrink: 0;

            .stat-value {
              font-weight: 600;
              color: #303133;
            }

            .stat-revenue {
              font-size: 12px;
              color: #409eff;
              margin-top: 2px;
            }
          }

          .progress-bar {
            position: absolute;
            bottom: 0;
            left: 40px;
            right: 0;
            height: 3px;
            background: #f5f7fa;
            border-radius: 2px;

            .progress-fill {
              height: 100%;
              background: linear-gradient(90deg, #409eff 0%, #79bbff 100%);
              border-radius: 2px;
              transition: width 0.3s ease;
            }
          }
        }
      }
    }

    .financial-card {
      height: 100%;

      .financial-report {
        .financial-item {
          display: flex;
          align-items: center;
          padding: 16px;
          border-radius: 8px;
          margin-bottom: 12px;
          background: #f5f7fa;
          transition: background 0.3s;

          &:last-child {
            margin-bottom: 0;
          }

          &:hover {
            background: #ebeef5;
          }

          &.highlight {
            background: linear-gradient(135deg, #ecf5ff 0%, #d9ecff 100%);
            border: 1px solid #b3d8ff;
          }

          .financial-icon {
            width: 48px;
            height: 48px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 16px;

            &.revenue {
              background: linear-gradient(135deg, #67c23a 0%, #95d475 100%);
              color: white;
            }

            &.rewards {
              background: linear-gradient(135deg, #e6a23c 0%, #f3d19e 100%);
              color: white;
            }

            &.pending {
              background: linear-gradient(135deg, #f56c6c 0%, #fab6b6 100%);
              color: white;
            }

            &.completed {
              background: linear-gradient(135deg, #909399 0%, #c0c4cc 100%);
              color: white;
            }

            &.platform {
              background: linear-gradient(135deg, #409eff 0%, #79bbff 100%);
              color: white;
            }
          }

          .financial-info {
            .financial-label {
              font-size: 14px;
              color: #909399;
            }

            .financial-value {
              font-size: 20px;
              font-weight: 700;
              color: #303133;
              margin-top: 4px;

              &.primary {
                color: #409eff;
              }

              &.warning {
                color: #e6a23c;
              }

              &.danger {
                color: #f56c6c;
              }
            }
          }
        }
      }
    }
  }
}

// Responsive adjustments
@media (max-width: 768px) {
  .dashboard-container {
    .metrics-row {
      .el-col {
        margin-bottom: 12px;
      }
    }

    .charts-row,
    .bottom-row {
      .el-col {
        margin-bottom: 20px;
      }
    }
  }
}
</style>
