<template>
  <div class="art-page-view">
    <!-- 1. 订阅概览卡片 -->
    <div class="overview-cards">
      <ElCard class="stat-card">
        <ElStatistic
          :title="$t('dashboard.overview.totalActive')"
          :value="overview.activeSubscriptions"
        >
          <template #prefix>
            <ArtSvgIcon icon="ri:checkbox-circle-line" class="text-green-500" />
          </template>
        </ElStatistic>
      </ElCard>

      <ElCard class="stat-card">
        <ElStatistic
          :title="$t('dashboard.overview.expiringIn7Days')"
          :value="overview.expiringIn7Days"
        >
          <template #prefix>
            <ArtSvgIcon icon="ri:alarm-warning-line" class="text-orange-500" />
          </template>
        </ElStatistic>
      </ElCard>

      <ElCard class="stat-card">
        <ElStatistic
          :title="$t('dashboard.overview.expiringIn3Days')"
          :value="overview.expiringIn3Days"
        >
          <template #prefix>
            <ArtSvgIcon icon="ri:error-warning-line" class="text-red-500" />
          </template>
        </ElStatistic>
      </ElCard>

      <ElCard class="stat-card">
        <ElStatistic
          :title="$t('dashboard.overview.expired')"
          :value="overview.expiredSubscriptions"
        >
          <template #prefix>
            <ArtSvgIcon icon="ri:close-circle-line" class="text-red-600" />
          </template>
        </ElStatistic>
      </ElCard>
    </div>

    <!-- 2. 中间区域：即将到期 & 收入统计 -->
    <div class="middle-section">
      <!-- 2.1 即将到期订阅 -->
      <ElCard class="expiring-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">{{ $t('dashboard.expiring.title') }}</span>
            <ElButton link type="primary" @click="viewAllExpiring">
              {{ $t('dashboard.expiring.viewAll') }}
            </ElButton>
          </div>
        </template>

        <div v-loading="expiringLoading">
          <ElTable
            v-if="expiringSubscriptions.length > 0"
            :data="expiringSubscriptions"
            style="width: 100%"
          >
            <ElTableColumn
              prop="tenantName"
              :label="$t('subscription.table.tenantName')"
              min-width="150"
            />
            <ElTableColumn
              prop="packageName"
              :label="$t('subscription.table.currentPackage')"
              min-width="120"
            />
            <ElTableColumn
              prop="expireDate"
              :label="$t('subscription.table.expireDate')"
              width="120"
            >
              <template #default="{ row }">
                {{ formatDate(row.expireDate) }}
              </template>
            </ElTableColumn>
            <ElTableColumn
              prop="daysUntilExpiry"
              :label="$t('dashboard.expiring.daysLeft')"
              width="100"
            >
              <template #default="{ row }">
                <ElTag :type="getDaysLeftType(row.daysUntilExpiry)">
                  {{ row.daysUntilExpiry }} {{ $t('common.days') }}
                </ElTag>
              </template>
            </ElTableColumn>
          </ElTable>
          <div v-else class="no-data">
            {{ $t('dashboard.expiring.noData') }}
          </div>
        </div>
      </ElCard>

      <!-- 2.2 收入统计图表 -->
      <ElCard class="revenue-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">{{ $t('dashboard.revenue.title') }}</span>
          </div>
        </template>

        <div v-loading="revenueLoading">
          <div class="revenue-summary">
            <div class="revenue-item">
              <span class="revenue-label">{{ $t('dashboard.revenue.total') }}</span>
              <span class="revenue-value">{{ formatCurrency(revenueData.totalRevenue) }}</span>
            </div>
            <div class="revenue-item">
              <span class="revenue-label">{{ $t('dashboard.revenue.monthly') }}</span>
              <span class="revenue-value">{{
                formatCurrency(revenueData.currentMonthRevenue)
              }}</span>
            </div>
            <div class="revenue-item">
              <span class="revenue-label">{{ $t('dashboard.revenue.quarterly') }}</span>
              <span class="revenue-value">{{
                formatCurrency(revenueData.currentQuarterRevenue)
              }}</span>
            </div>
          </div>
          <div ref="revenueChartRef" class="revenue-chart"></div>
        </div>
      </ElCard>
    </div>

    <!-- 3. 配额使用率排行 -->
    <ElCard class="ranking-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="card-title">{{ $t('dashboard.quotaRanking.title') }}</span>
          <ElSelect
            v-model="quotaTypeFilter"
            :placeholder="$t('dashboard.quotaRanking.selectType')"
            clearable
            style="width: 200px"
            @change="loadQuotaRanking"
          >
            <ElOption
              v-for="type in quotaTypeOptions"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </ElSelect>
        </div>
      </template>

      <div v-loading="rankingLoading">
        <ElTable :data="quotaRanking" style="width: 100%">
          <ElTableColumn type="index" :label="$t('dashboard.quotaRanking.rank')" width="60" />
          <ElTableColumn
            prop="tenantName"
            :label="$t('dashboard.quotaRanking.tenant')"
            min-width="150"
          />
          <ElTableColumn
            prop="quotaName"
            :label="$t('dashboard.quotaRanking.quotaType')"
            min-width="120"
          />
          <ElTableColumn
            prop="currentUsage"
            :label="$t('dashboard.quotaRanking.usage')"
            width="100"
          />
          <ElTableColumn
            prop="quotaLimit"
            :label="$t('dashboard.quotaRanking.limit')"
            width="100"
          />
          <ElTableColumn
            prop="usagePercentage"
            :label="$t('dashboard.quotaRanking.percentage')"
            width="120"
          >
            <template #default="{ row }">
              <ElProgress
                :percentage="row.usagePercentage"
                :color="getProgressColor(row.usagePercentage)"
                :stroke-width="12"
              />
            </template>
          </ElTableColumn>
        </ElTable>
      </div>
    </ElCard>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, onBeforeUnmount } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { useRouter } from 'vue-router'
  import * as echarts from 'echarts/core'
  import { BarChart } from 'echarts/charts'
  import { GridComponent, TooltipComponent, TitleComponent } from 'echarts/components'
  import { CanvasRenderer } from 'echarts/renderers'
  import ArtSvgIcon from '@/components/core/base/art-svg-icon/index.vue'
  import {
    fetchSubscriptionOverview,
    fetchExpiringSubscriptions,
    fetchRevenueStatistics,
    fetchQuotaUsageRanking
  } from '@/api/statistics'
  import {
    ElButton,
    ElCard,
    ElProgress,
    ElSelect,
    ElOption,
    ElStatistic,
    ElTable,
    ElTableColumn,
    ElTag
  } from 'element-plus'

  defineOptions({ name: 'TenantDashboard' })

  // 注册 ECharts 组件
  echarts.use([BarChart, GridComponent, TooltipComponent, TitleComponent, CanvasRenderer])

  const { t } = useI18n()
  const router = useRouter()

  // 1. 响应式变量
  const overview = ref<Api.Statistics.SubscriptionOverview>({
    totalSubscriptions: 0,
    activeSubscriptions: 0,
    expiringIn7Days: 0,
    expiringIn3Days: 0,
    expiringIn1Day: 0,
    expiredSubscriptions: 0,
    pendingSubscriptions: 0,
    suspendedSubscriptions: 0
  })

  const expiringSubscriptions = ref<Api.Statistics.ExpiringSubscriptionItem[]>([])
  const expiringLoading = ref(false)

  const revenueData = ref<Api.Statistics.RevenueStatisticsResponse>({
    totalRevenue: 0,
    currentMonthRevenue: 0,
    currentQuarterRevenue: 0,
    monthlyRevenues: []
  })
  const revenueLoading = ref(false)
  const revenueChartRef = ref<HTMLElement>()
  let revenueChart: echarts.ECharts | null = null

  const quotaRanking = ref<Api.Statistics.QuotaUsageRankingItem[]>([])
  const rankingLoading = ref(false)
  const quotaTypeFilter = ref<number | undefined>(undefined)

  const quotaTypeOptions = [
    { value: 1, label: t('dashboard.quotaRanking.type.orders') },
    { value: 2, label: t('dashboard.quotaRanking.type.storage') },
    { value: 3, label: t('dashboard.quotaRanking.type.users') }
  ]

  // 2. 加载订阅概览
  const loadOverview = async () => {
    try {
      overview.value = await fetchSubscriptionOverview()
    } catch (error) {
      console.error('Failed to load subscription overview:', error)
    }
  }

  // 3. 加载即将到期订阅
  const loadExpiringSubscriptions = async () => {
    expiringLoading.value = true
    try {
      const response = await fetchExpiringSubscriptions({ days: 7, page: 1, pageSize: 5 })
      expiringSubscriptions.value = response.items
    } catch (error) {
      console.error('Failed to load expiring subscriptions:', error)
    } finally {
      expiringLoading.value = false
    }
  }

  // 4. 加载收入统计
  const loadRevenueStatistics = async () => {
    revenueLoading.value = true
    try {
      revenueData.value = await fetchRevenueStatistics()
      renderRevenueChart()
    } catch (error) {
      console.error('Failed to load revenue statistics:', error)
    } finally {
      revenueLoading.value = false
    }
  }

  // 5. 渲染收入图表
  const renderRevenueChart = () => {
    if (!revenueChartRef.value) return

    if (!revenueChart) {
      revenueChart = echarts.init(revenueChartRef.value)
    }

    const months = revenueData.value.monthlyRevenues.map(
      (item) => `${item.year}-${String(item.month).padStart(2, '0')}`
    )
    const revenues = revenueData.value.monthlyRevenues.map((item) => item.revenue)

    const option: echarts.EChartsCoreOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: months
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: t('dashboard.revenue.title'),
          type: 'bar',
          data: revenues,
          itemStyle: {
            color: '#409eff'
          }
        }
      ]
    }

    revenueChart.setOption(option)
  }

  // 6. 加载配额使用排行
  const loadQuotaRanking = async () => {
    rankingLoading.value = true
    try {
      const response = await fetchQuotaUsageRanking({
        quotaType: quotaTypeFilter.value,
        limit: 10
      })
      quotaRanking.value = response.items
    } catch (error) {
      console.error('Failed to load quota ranking:', error)
    } finally {
      rankingLoading.value = false
    }
  }

  // 7. 工具函数
  const formatDate = (date: string) => {
    return new Date(date).toLocaleDateString()
  }

  const formatCurrency = (value: number) => {
    return `¥${value.toLocaleString()}`
  }

  const getDaysLeftType = (days: number) => {
    if (days <= 1) return 'danger'
    if (days <= 3) return 'warning'
    return 'info'
  }

  const getProgressColor = (percentage: number) => {
    if (percentage >= 90) return '#f56c6c'
    if (percentage >= 70) return '#e6a23c'
    return '#67c23a'
  }

  const viewAllExpiring = () => {
    router.push('/tenant/subscription')
  }

  // 8. 生命周期
  onMounted(() => {
    loadOverview()
    loadExpiringSubscriptions()
    loadRevenueStatistics()
    loadQuotaRanking()

    // 监听窗口大小变化
    window.addEventListener('resize', handleResize)
  })

  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize)
    if (revenueChart) {
      revenueChart.dispose()
      revenueChart = null
    }
  })

  const handleResize = () => {
    if (revenueChart) {
      revenueChart.resize()
    }
  }
</script>

<style scoped>
  .art-page-view {
    display: flex;
    flex-direction: column;
    gap: 16px;
    padding: 16px;
  }

  /* 概览卡片 */
  .overview-cards {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
  }

  .stat-card {
    transition: all 0.3s ease;
  }

  .stat-card:hover {
    box-shadow: 0 4px 12px rgb(0 0 0 / 10%);
    transform: translateY(-4px);
  }

  .stat-card :deep(.el-statistic__head) {
    font-size: 14px;
    color: var(--el-text-color-secondary);
  }

  .stat-card :deep(.el-statistic__number) {
    font-size: 28px;
    font-weight: 600;
  }

  /* 中间区域 */
  .middle-section {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
  }

  .expiring-card,
  .revenue-card {
    min-height: 400px;
  }

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

  .card-title {
    font-size: 16px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }

  .no-data {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 300px;
    color: var(--el-text-color-secondary);
  }

  /* 收入统计 */
  .revenue-summary {
    display: flex;
    gap: 24px;
    margin-bottom: 16px;
  }

  .revenue-item {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .revenue-label {
    font-size: 14px;
    color: var(--el-text-color-secondary);
  }

  .revenue-value {
    font-size: 24px;
    font-weight: 600;
    color: var(--el-color-primary);
  }

  .revenue-chart {
    width: 100%;
    height: 280px;
  }

  /* 排行榜卡片 */
  .ranking-card {
    min-height: 400px;
  }

  /* 响应式 */
  @media (width <= 1400px) {
    .overview-cards {
      grid-template-columns: repeat(2, 1fr);
    }

    .middle-section {
      grid-template-columns: 1fr;
    }
  }

  @media (width <= 768px) {
    .overview-cards {
      grid-template-columns: 1fr;
    }
  }
</style>
