<template>
  <div class="analytics-page">
    <div class="page-header">
      <h2>数据分析</h2>
      <div class="header-actions">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="loadData"
        />
        <el-button 
          type="primary" 
          :icon="Refresh" 
          :loading="refreshing"
          @click="handleRefresh"
        >
          刷新数据
        </el-button>
      </div>
    </div>
    
    <!-- 统计摘要 -->
    <div class="stats-grid">
      <div class="stat-card" v-for="(item, index) in summaryItems" :key="index">
        <div class="stat-value">{{ formatNumber(item.value) }}</div>
        <div class="stat-label">{{ item.label }}</div>
      </div>
    </div>
    
    <!-- 趋势图 -->
    <div class="page-card" style="margin-top: 20px">
      <div class="card-header">
        <h3>数据趋势</h3>
        <el-radio-group v-model="trendMetric" size="small" @change="updateTrendChart">
          <el-radio-button label="fans">粉丝</el-radio-button>
          <el-radio-button label="views">播放</el-radio-button>
          <el-radio-button label="likes">点赞</el-radio-button>
          <el-radio-button label="comments">评论</el-radio-button>
        </el-radio-group>
      </div>
      <div ref="trendChartRef" style="height: 350px" v-loading="loading"></div>
    </div>
    
    <!-- 平台对比 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="12">
        <div class="page-card">
          <h3>平台粉丝分布</h3>
          <div ref="platformChartRef" style="height: 300px"></div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="page-card">
          <h3>平台数据对比</h3>
          <el-table :data="platformComparison" size="small">
            <el-table-column prop="platform" label="平台" width="100">
              <template #default="{ row }">
                {{ getPlatformName(row.platform) }}
              </template>
            </el-table-column>
            <el-table-column prop="fansCount" label="粉丝" />
            <el-table-column prop="fansIncrease" label="粉丝增量" />
            <el-table-column prop="viewsCount" label="播放量" />
            <el-table-column prop="likesCount" label="点赞数" />
          </el-table>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import * as echarts from 'echarts';
import { Refresh } from '@element-plus/icons-vue';
import { PLATFORMS } from '@media-manager/shared';
import type { PlatformComparison, PlatformType } from '@media-manager/shared';
import { useAuthStore } from '@/stores/auth';
import dayjs from 'dayjs';
import request from '@/api/request';

// 趋势数据类型
interface TrendData {
  dates: string[];
  fans: number[];
  views: number[];
  likes: number[];
  comments: number[];
  shares: number[];
  collects: number[];
}

const authStore = useAuthStore();
const loading = ref(false);
const refreshing = ref(false);
const trendChartRef = ref<HTMLElement>();
const platformChartRef = ref<HTMLElement>();

let trendChart: echarts.ECharts | null = null;
let platformChart: echarts.ECharts | null = null;

// 刷新数据
async function handleRefresh() {
  refreshing.value = true;
  try {
    await loadData();
  } finally {
    refreshing.value = false;
  }
}

const dateRange = ref<[Date, Date]>([
  dayjs().subtract(30, 'day').toDate(),
  dayjs().toDate(),
]);

const trendMetric = ref<'fans' | 'views' | 'likes' | 'comments'>('fans');
const trendData = ref<TrendData | null>(null);
const platformComparison = ref<PlatformComparison[]>([]);

// 从趋势数据计算统计摘要
// 注意：数据库存储的是累积值，所以区间增量 = 最后一天 - 第一天
const summaryItems = computed(() => {
  const data = trendData.value;
  if (!data || data.dates.length === 0) {
    return [
      { label: '总粉丝', value: 0 },
      { label: '粉丝增量', value: 0 },
      { label: '播放增量', value: 0 },
      { label: '点赞增量', value: 0 },
      { label: '评论增量', value: 0 },
      { label: '收藏增量', value: 0 },
    ];
  }
  
  const len = data.fans.length;
  
  // 取最后一天的粉丝数作为当前粉丝数
  const latestFans = data.fans[len - 1] || 0;
  // 取第一天的值
  const firstFans = data.fans[0] || 0;
  const firstViews = data.views[0] || 0;
  const firstLikes = data.likes[0] || 0;
  const firstComments = data.comments[0] || 0;
  const firstCollects = data.collects[0] || 0;
  
  // 取最后一天的值
  const lastViews = data.views[len - 1] || 0;
  const lastLikes = data.likes[len - 1] || 0;
  const lastComments = data.comments[len - 1] || 0;
  const lastCollects = data.collects[len - 1] || 0;
  
  // 计算区间增量（累积值：最后一天 - 第一天）
  const fansIncrease = latestFans - firstFans;
  const viewsIncrease = lastViews - firstViews;
  const likesIncrease = lastLikes - firstLikes;
  const commentsIncrease = lastComments - firstComments;
  const collectsIncrease = lastCollects - firstCollects;
  
  return [
    { label: '总粉丝', value: latestFans },
    { label: '粉丝增量', value: fansIncrease },
    { label: '播放增量', value: viewsIncrease },
    { label: '点赞增量', value: likesIncrease },
    { label: '评论增量', value: commentsIncrease },
    { label: '收藏增量', value: collectsIncrease },
  ];
});

function getPlatformName(platform: PlatformType) {
  return PLATFORMS[platform]?.name || platform;
}

function formatNumber(num: number) {
  if (num >= 10000) return (num / 10000).toFixed(1) + 'w';
  return num.toString();
}

// 获取趋势数据（通过 Node 转发调用 Python 接口）
async function loadTrendData() {
  if (!dateRange.value) return;

  const [start, end] = dateRange.value;
  const startDate = dayjs(start).format('YYYY-MM-DD');
  const endDate = dayjs(end).format('YYYY-MM-DD');

  const data = await request.get('/api/analytics/trend-from-python', {
    params: {
      startDate,
      endDate,
    },
  });

  return data as TrendData;
}

// 平台统计数据类型
interface PlatformStats {
  platform: string;
  fansCount: number;
  fansIncrease: number;
  viewsCount: number;
  likesCount: number;
  commentsCount: number;
  collectsCount: number;
}

// 获取平台统计数据（通过 Node 转发调用 Python 接口）
async function loadPlatformData() {
  if (!dateRange.value) return;

  const [start, end] = dateRange.value;
  const startDate = dayjs(start).format('YYYY-MM-DD');
  const endDate = dayjs(end).format('YYYY-MM-DD');

  const data = await request.get('/api/analytics/platforms-from-python', {
    params: {
      startDate,
      endDate,
    },
  });

  return data as PlatformStats[];
}

async function loadData() {
  if (!dateRange.value) return;
  
  loading.value = true;
  
  try {
    // 并行加载数据（全部从 Python API 获取）
    const [pythonTrendData, pythonPlatformData] = await Promise.all([
      loadTrendData().catch(() => null),
      loadPlatformData().catch(() => null),
    ]);
    
    if (pythonTrendData) {
      trendData.value = pythonTrendData;
    }
    
    if (pythonPlatformData) {
      // 转换为 PlatformComparison 格式
      platformComparison.value = pythonPlatformData.map(p => ({
        platform: p.platform as PlatformType,
        fansCount: p.fansCount,
        fansIncrease: p.fansIncrease,
        viewsCount: p.viewsCount,
        likesCount: p.likesCount,
      }));
    }
    
    updateTrendChart();
    updatePlatformChart();
  } catch {
    // 错误已处理
  } finally {
    loading.value = false;
  }
}

// 获取图表颜色配置
function getChartColor(type: 'fans' | 'views' | 'likes' | 'comments') {
  const colors: Record<string, { main: string; gradient: string[] }> = {
    fans: { main: '#4facfe', gradient: ['#4facfe', 'rgba(79, 172, 254, 0)'] },
    views: { main: '#11998e', gradient: ['#11998e', 'rgba(17, 153, 142, 0)'] },
    likes: { main: '#f5576c', gradient: ['#f5576c', 'rgba(245, 87, 108, 0)'] },
    comments: { main: '#fa709a', gradient: ['#fa709a', 'rgba(250, 112, 154, 0)'] },
  };
  return colors[type] || colors.fans;
}

// 获取图表标题
function getChartTitle(type: 'fans' | 'views' | 'likes' | 'comments') {
  const titles: Record<string, string> = {
    fans: '粉丝数',
    views: '播放量',
    likes: '点赞数',
    comments: '评论数',
  };
  return titles[type] || '';
}

function updateTrendChart() {
  if (!trendChartRef.value) return;
  
  if (!trendChart) {
    trendChart = echarts.init(trendChartRef.value);
  }
  
  // 使用 Python API 返回的数据
  const dates = trendData.value?.dates || [];
  const data = trendData.value?.[trendMetric.value] || [];
  const colorConfig = getChartColor(trendMetric.value);
  
  trendChart.setOption({
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#e5e7eb',
      borderWidth: 1,
      textStyle: { color: '#374151' },
      formatter: (params: unknown) => {
        const p = params as { name: string; value: number }[];
        if (Array.isArray(p) && p.length > 0) {
          return `${p[0].name}<br/>${getChartTitle(trendMetric.value)}: <b>${p[0].value.toLocaleString()}</b>`;
        }
        return '';
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLine: { lineStyle: { color: '#e5e7eb' } },
      axisLabel: { color: '#6b7280' },
    },
    yAxis: {
      type: 'value',
      axisLine: { show: false },
      axisTick: { show: false },
      splitLine: { lineStyle: { color: '#f3f4f6' } },
      axisLabel: {
        color: '#6b7280',
        formatter: (value: number) => {
          if (value >= 10000) return (value / 10000).toFixed(1) + '万';
          return value.toString();
        },
      },
    },
    series: [{
      data: data,
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      lineStyle: { width: 3 },
      areaStyle: {
        opacity: 0.1,
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: colorConfig.gradient[0] },
          { offset: 1, color: colorConfig.gradient[1] },
        ]),
      },
    }],
    color: [colorConfig.main],
  }, true);
}

function updatePlatformChart() {
  if (!platformChartRef.value) return;
  
  if (!platformChart) {
    platformChart = echarts.init(platformChartRef.value);
  }
  
  platformChart.setOption({
    tooltip: { trigger: 'item' },
    series: [{
      type: 'pie',
      radius: ['40%', '70%'],
      data: platformComparison.value.map(p => ({
        name: getPlatformName(p.platform),
        value: p.fansCount,
      })),
    }],
  });
}

onMounted(() => {
  loadData();
  
  window.addEventListener('resize', () => {
    trendChart?.resize();
    platformChart?.resize();
  });
});
</script>

<style lang="scss" scoped>
@use '@/styles/variables.scss' as *;

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  
  h2 { margin: 0; }
  
  .header-actions {
    display: flex;
    align-items: center;
    gap: 12px;
  }
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  
  .stat-value {
    font-size: 24px;
    font-weight: 600;
    color: $primary-color;
  }
  
  .stat-label {
    font-size: 14px;
    color: $text-secondary;
    margin-top: 8px;
  }
}

@media (max-width: 1200px) {
  .stats-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
  
  h3 { margin: 0; }
}
</style>
