<script setup lang="ts">
import { ReloadOutlined } from '@ant-design/icons-vue'
import { useDashboardStore } from '@/stores/dashboard'
import DashboardOverviewCards from '@/components/DashboardOverviewCards.vue'
import DashboardByTypeCards from '@/components/DashboardByTypeCards.vue'
import DashboardTrendChart from '@/components/DashboardTrendChart.vue'
import DashboardBreakdownTable from '@/components/DashboardBreakdownTable.vue'

const store = useDashboardStore()

function handleRefresh() {
  store.fetchAll()
}

function handleTrendGroupByChange(val: 'day' | 'week' | 'month') {
  store.trendGroupBy = val
  store.fetchTrend()
}

function handleTrendDataTypeChange(val: string | undefined) {
  store.trendDataType = val
  store.fetchTrend()
}

function handleBreakdownDimensionChange(val: 'company' | 'platform' | 'store') {
  store.breakdownDimension = val
  store.fetchBreakdown()
}

function handleBreakdownDataTypeChange(val: string | undefined) {
  store.breakdownDataType = val
  store.fetchBreakdown()
}

function handleBreakdownDateRangeChange(range: [string, string] | null) {
  store.breakdownFrom = range?.[0]
  store.breakdownTo = range?.[1]
  store.fetchBreakdown()
}

onMounted(() => {
  store.fetchAll()
})
</script>

<template>
  <div>
    <!-- 标题行 -->
    <div class="flex items-center justify-between mb-4">
      <h2 class="text-xl font-semibold m-0">Dashboard</h2>
      <a-button type="primary" @click="handleRefresh">
        <template #icon><ReloadOutlined /></template>
        刷新
      </a-button>
    </div>

    <!-- 错误提示 -->
    <a-alert
      v-if="store.overviewError"
      type="error"
      :message="store.overviewError"
      show-icon
      closable
      class="mb-4"
    />

    <!-- 概览统计卡片 -->
    <DashboardOverviewCards :overview="store.overview" :loading="store.overviewLoading" />

    <!-- 按数据类型统计 -->
    <DashboardByTypeCards
      :by-type="store.overview?.by_type ?? []"
      :loading="store.overviewLoading"
    />

    <!-- 趋势折线图 -->
    <DashboardTrendChart
      :data="store.trendData"
      :loading="store.trendLoading"
      :group-by="store.trendGroupBy"
      :data-type="store.trendDataType"
      @update:group-by="handleTrendGroupByChange"
      @update:data-type="handleTrendDataTypeChange"
    />

    <!-- 分维度统计表格 -->
    <DashboardBreakdownTable
      :data="store.breakdownData"
      :loading="store.breakdownLoading"
      :dimension="store.breakdownDimension"
      :data-type="store.breakdownDataType"
      @update:dimension="handleBreakdownDimensionChange"
      @update:data-type="handleBreakdownDataTypeChange"
      @update:date-range="handleBreakdownDateRangeChange"
    />
  </div>
</template>
