<template>
  <div class="statistics-page">
    <a-page-header
      title="数据统计"
      sub-title="系统数据分析与统计报表"
    >
      <template #extra>
        <a-space>
          <a-range-picker
            v-model:value="dateRange"
            @change="handleDateRangeChange"
          />
          <a-button @click="handleExport" :loading="exportLoading">
            <template #icon>
              <DownloadOutlined />
            </template>
            导出报表
          </a-button>
          <a-button @click="handleRefreshAll" :loading="refreshLoading">
            <template #icon>
              <ReloadOutlined />
            </template>
            刷新全部
          </a-button>
        </a-space>
      </template>
    </a-page-header>

    <!-- 概览统计卡片 -->
    <a-row :gutter="16" class="overview-cards">
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="总用户数"
            :value="overviewData.totalUsers"
            :precision="0"
            suffix="人"
          >
            <template #prefix>
              <UserOutlined style="color: #1890ff" />
            </template>
          </a-statistic>
          <div class="statistic-trend">
            <span :class="['trend', overviewData.userGrowth >= 0 ? 'up' : 'down']">
              <CaretUpOutlined v-if="overviewData.userGrowth >= 0" />
              <CaretDownOutlined v-else />
              {{ Math.abs(overviewData.userGrowth) }}%
            </span>
            <span class="trend-text">较昨日</span>
          </div>
        </a-card>
      </a-col>
      
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="活跃用户"
            :value="overviewData.activeUsers"
            :precision="0"
            suffix="人"
          >
            <template #prefix>
              <CheckCircleOutlined style="color: #52c41a" />
            </template>
          </a-statistic>
          <div class="statistic-trend">
            <span :class="['trend', overviewData.activeGrowth >= 0 ? 'up' : 'down']">
              <CaretUpOutlined v-if="overviewData.activeGrowth >= 0" />
              <CaretDownOutlined v-else />
              {{ Math.abs(overviewData.activeGrowth) }}%
            </span>
            <span class="trend-text">较昨日</span>
          </div>
        </a-card>
      </a-col>
      
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="动物认领"
            :value="overviewData.totalAnimals"
            :precision="0"
            suffix="只"
          >
            <template #prefix>
              <HeartOutlined style="color: #eb2f96" />
            </template>
          </a-statistic>
          <div class="statistic-trend">
            <span :class="['trend', overviewData.animalGrowth >= 0 ? 'up' : 'down']">
              <CaretUpOutlined v-if="overviewData.animalGrowth >= 0" />
              <CaretDownOutlined v-else />
              {{ Math.abs(overviewData.animalGrowth) }}%
            </span>
            <span class="trend-text">较昨日</span>
          </div>
        </a-card>
      </a-col>
      
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="总收入"
            :value="overviewData.totalRevenue"
            :precision="2"
            prefix="¥"
          >
            <template #prefix>
              <DollarOutlined style="color: #faad14" />
            </template>
          </a-statistic>
          <div class="statistic-trend">
            <span :class="['trend', overviewData.revenueGrowth >= 0 ? 'up' : 'down']">
              <CaretUpOutlined v-if="overviewData.revenueGrowth >= 0" />
              <CaretDownOutlined v-else />
              {{ Math.abs(overviewData.revenueGrowth) }}%
            </span>
            <span class="trend-text">较昨日</span>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 图表区域 -->
    <a-row :gutter="16" class="chart-section">
      <a-col :span="12">
        <DataStatisticsChart
          ref="userGrowthChart"
          title="用户增长趋势"
          chart-type="area"
          data-source="/api/v1/admin/statistics/user-growth"
          :series-config="[
            { name: '新增用户', dataKey: 'new_users', color: '#1890ff' },
            { name: '累计用户', dataKey: 'cumulative_users', color: '#52c41a' }
          ]"
          @data-loaded="handleUserGrowthLoaded"
        />
      </a-col>
      
      <a-col :span="12">
        <DataStatisticsChart
          ref="businessChart"
          title="业务数据统计"
          chart-type="line"
          data-source="/api/v1/admin/statistics/business"
          :series-config="[
            { name: '动物认领', dataKey: 'animals', color: '#eb2f96' },
            { name: '旅行计划', dataKey: 'travels', color: '#722ed1' },
            { name: '订单数量', dataKey: 'orders', color: '#fa8c16' }
          ]"
          @data-loaded="handleBusinessDataLoaded"
        />
      </a-col>
    </a-row>

    <a-row :gutter="16" class="chart-section">
      <a-col :span="8">
        <DataStatisticsChart
          ref="userTypeChart"
          title="用户类型分布"
          chart-type="pie"
          data-source="/api/v1/admin/statistics/user-types"
          @data-loaded="handleUserTypeLoaded"
        />
      </a-col>
      
      <a-col :span="8">
        <DataStatisticsChart
          ref="animalSpeciesChart"
          title="动物种类分布"
          chart-type="pie"
          data-source="/api/v1/admin/statistics/animal-species"
          @data-loaded="handleAnimalSpeciesLoaded"
        />
      </a-col>
      
      <a-col :span="8">
        <DataStatisticsChart
          ref="revenueChart"
          title="收入统计"
          chart-type="bar"
          data-source="/api/v1/admin/statistics/revenue"
          :series-config="[
            { name: '认领费用', dataKey: 'adoption_fee', color: '#1890ff' },
            { name: '推广佣金', dataKey: 'commission', color: '#52c41a' }
          ]"
          @data-loaded="handleRevenueLoaded"
        />
      </a-col>
    </a-row>

    <!-- 地理分布图 -->
    <a-row :gutter="16" class="chart-section">
      <a-col :span="24">
        <a-card title="用户地理分布" :loading="geoLoading">
          <template #extra>
            <a-radio-group v-model:value="geoViewType" @change="handleGeoViewChange">
              <a-radio-button value="users">用户分布</a-radio-button>
              <a-radio-button value="animals">动物分布</a-radio-button>
              <a-radio-button value="orders">订单分布</a-radio-button>
            </a-radio-group>
          </template>
          
          <div ref="geoChartContainer" style="height: 400px;"></div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 数据表格 -->
    <a-row :gutter="16" class="table-section">
      <a-col :span="12">
        <a-card title="热门动物排行" size="small">
          <a-table
            :columns="animalRankingColumns"
            :data-source="animalRankingData"
            :pagination="false"
            size="small"
          >
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.key === 'rank'">
                <a-tag :color="index < 3 ? ['gold', 'silver', '#cd7f32'][index] : 'default'">
                  {{ index + 1 }}
                </a-tag>
              </template>
              <template v-if="column.key === 'adoption_rate'">
                <a-progress
                  :percent="record.adoption_rate"
                  size="small"
                  :show-info="false"
                />
                {{ record.adoption_rate }}%
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>
      
      <a-col :span="12">
        <a-card title="活跃用户排行" size="small">
          <a-table
            :columns="userRankingColumns"
            :data-source="userRankingData"
            :pagination="false"
            size="small"
          >
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.key === 'rank'">
                <a-tag :color="index < 3 ? ['gold', 'silver', '#cd7f32'][index] : 'default'">
                  {{ index + 1 }}
                </a-tag>
              </template>
              <template v-if="column.key === 'avatar'">
                <a-avatar :src="record.avatar" size="small">
                  {{ record.nickname?.charAt(0) }}
                </a-avatar>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { 
  UserOutlined, 
  CheckCircleOutlined, 
  HeartOutlined, 
  DollarOutlined,
  CaretUpOutlined,
  CaretDownOutlined,
  DownloadOutlined,
  ReloadOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import type { Dayjs } from 'dayjs'
import * as echarts from 'echarts'
import DataStatisticsChart from '@/components/charts/DataStatisticsChart.vue'

// 概览数据
const overviewData = ref({
  totalUsers: 12580,
  activeUsers: 8960,
  totalAnimals: 1250,
  totalRevenue: 156780.50,
  userGrowth: 12.5,
  activeGrowth: 8.3,
  animalGrowth: 15.2,
  revenueGrowth: 22.1
})

// 日期范围
const dateRange = ref<[Dayjs, Dayjs] | null>(null)

// 加载状态
const exportLoading = ref(false)
const refreshLoading = ref(false)
const geoLoading = ref(false)

// 地理分布图
const geoViewType = ref('users')
const geoChartContainer = ref<HTMLDivElement>()
let geoChartInstance: echarts.ECharts | null = null

// 图表引用
const userGrowthChart = ref()
const businessChart = ref()
const userTypeChart = ref()
const animalSpeciesChart = ref()
const revenueChart = ref()

// 动物排行数据
const animalRankingColumns = [
  { title: '排名', dataIndex: 'rank', key: 'rank', width: 80 },
  { title: '动物名称', dataIndex: 'name', key: 'name' },
  { title: '种类', dataIndex: 'species', key: 'species' },
  { title: '认领次数', dataIndex: 'adoption_count', key: 'adoption_count' },
  { title: '认领率', dataIndex: 'adoption_rate', key: 'adoption_rate' }
]

const animalRankingData = ref([
  { id: 1, name: '小白', species: '狗', adoption_count: 25, adoption_rate: 85 },
  { id: 2, name: '咪咪', species: '猫', adoption_count: 22, adoption_rate: 78 },
  { id: 3, name: '小黑', species: '狗', adoption_count: 20, adoption_rate: 72 },
  { id: 4, name: '花花', species: '猫', adoption_count: 18, adoption_rate: 65 },
  { id: 5, name: '豆豆', species: '兔子', adoption_count: 15, adoption_rate: 58 }
])

// 用户排行数据
const userRankingColumns = [
  { title: '排名', dataIndex: 'rank', key: 'rank', width: 80 },
  { title: '头像', dataIndex: 'avatar', key: 'avatar', width: 60 },
  { title: '用户名', dataIndex: 'nickname', key: 'nickname' },
  { title: '认领数量', dataIndex: 'adoption_count', key: 'adoption_count' },
  { title: '活跃度', dataIndex: 'activity_score', key: 'activity_score' }
]

const userRankingData = ref([
  { id: 1, nickname: '爱心天使', avatar: '', adoption_count: 8, activity_score: 95 },
  { id: 2, nickname: '动物守护者', avatar: '', adoption_count: 6, activity_score: 88 },
  { id: 3, nickname: '温暖之家', avatar: '', adoption_count: 5, activity_score: 82 },
  { id: 4, nickname: '小动物之友', avatar: '', adoption_count: 4, activity_score: 76 },
  { id: 5, nickname: '爱宠人士', avatar: '', adoption_count: 3, activity_score: 70 }
])

/**
 * 处理日期范围变化
 */
const handleDateRangeChange = (dates: [Dayjs, Dayjs] | null) => {
  if (dates) {
    // 刷新所有图表数据
    handleRefreshAll()
  }
}

/**
 * 导出报表
 */
const handleExport = async () => {
  exportLoading.value = true
  
  try {
    // 模拟导出过程
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 这里应该调用实际的导出API
    message.success('报表导出成功')
  } catch (error) {
    message.error('报表导出失败')
  } finally {
    exportLoading.value = false
  }
}

/**
 * 刷新所有数据
 */
const handleRefreshAll = async () => {
  refreshLoading.value = true
  
  try {
    // 刷新概览数据
    await loadOverviewData()
    
    // 刷新所有图表
    userGrowthChart.value?.refresh()
    businessChart.value?.refresh()
    userTypeChart.value?.refresh()
    animalSpeciesChart.value?.refresh()
    revenueChart.value?.refresh()
    
    // 刷新地理分布图
    await loadGeoData()
    
    message.success('数据刷新成功')
  } catch (error) {
    message.error('数据刷新失败')
  } finally {
    refreshLoading.value = false
  }
}

/**
 * 加载概览数据
 */
const loadOverviewData = async () => {
  // 这里应该调用实际的API接口
  // const response = await getOverviewStatistics()
  // overviewData.value = response.data
  
  // 模拟数据更新
  overviewData.value = {
    ...overviewData.value,
    totalUsers: overviewData.value.totalUsers + Math.floor(Math.random() * 100),
    activeUsers: overviewData.value.activeUsers + Math.floor(Math.random() * 50)
  }
}

/**
 * 初始化地理分布图
 */
const initGeoChart = () => {
  if (!geoChartContainer.value) return
  
  geoChartInstance = echarts.init(geoChartContainer.value)
  loadGeoData()
}

/**
 * 加载地理分布数据
 */
const loadGeoData = async () => {
  if (!geoChartInstance) return
  
  geoLoading.value = true
  
  try {
    // 模拟地理数据
    const geoData = [
      { name: '北京', value: 1200 },
      { name: '上海', value: 980 },
      { name: '广东', value: 850 },
      { name: '浙江', value: 720 },
      { name: '江苏', value: 680 },
      { name: '四川', value: 520 },
      { name: '湖北', value: 450 },
      { name: '河南', value: 380 }
    ]
    
    const option = {
      title: {
        text: `${geoViewType.value === 'users' ? '用户' : geoViewType.value === 'animals' ? '动物' : '订单'}分布`,
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}'
      },
      visualMap: {
        min: 0,
        max: 1200,
        left: 'left',
        top: 'bottom',
        text: ['高', '低'],
        calculable: true,
        inRange: {
          color: ['#e0f3ff', '#006edd']
        }
      },
      series: [{
        name: geoViewType.value,
        type: 'map',
        map: 'china',
        roam: false,
        data: geoData
      }]
    }
    
    geoChartInstance.setOption(option)
  } catch (error) {
    console.error('加载地理数据失败:', error)
  } finally {
    geoLoading.value = false
  }
}

/**
 * 处理地理视图类型变化
 */
const handleGeoViewChange = () => {
  loadGeoData()
}

/**
 * 图表数据加载回调
 */
const handleUserGrowthLoaded = (data: any[]) => {
  console.log('用户增长数据加载完成:', data)
}

const handleBusinessDataLoaded = (data: any[]) => {
  console.log('业务数据加载完成:', data)
}

const handleUserTypeLoaded = (data: any[]) => {
  console.log('用户类型数据加载完成:', data)
}

const handleAnimalSpeciesLoaded = (data: any[]) => {
  console.log('动物种类数据加载完成:', data)
}

const handleRevenueLoaded = (data: any[]) => {
  console.log('收入数据加载完成:', data)
}

/**
 * 组件挂载
 */
onMounted(() => {
  loadOverviewData()
  
  nextTick(() => {
    initGeoChart()
  })
})
</script>

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

.overview-cards {
  margin-bottom: 24px;
}

.statistic-trend {
  margin-top: 8px;
  font-size: 12px;
}

.trend {
  margin-right: 8px;
}

.trend.up {
  color: #52c41a;
}

.trend.down {
  color: #ff4d4f;
}

.trend-text {
  color: #666;
}

.chart-section {
  margin-bottom: 24px;
}

.table-section {
  margin-bottom: 24px;
}

.chart-section :deep(.ant-card),
.table-section :deep(.ant-card) {
  height: 100%;
}

.chart-section :deep(.ant-card-body) {
  padding: 16px;
}
</style>