<template>
  <div class="platform-detail-page">
    <!-- 调试信息 -->
    <div v-if="false" style="display: none;">
      {{ console.log('[PlatformDetail] 模板渲染') }}
    </div>
    <!-- 顶部筛选栏 -->
    <div class="filter-bar">
      <div class="filter-left">
        <span class="filter-label">开始时间</span>
        <el-date-picker
          v-model="startDate"
          type="date"
          placeholder="选择日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 140px"
        />
        <span class="filter-label">结束时间</span>
        <el-date-picker
          v-model="endDate"
          type="date"
          placeholder="选择日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 140px"
        />
        <div class="quick-btns">
          <el-button 
            v-for="btn in quickDateBtns" 
            :key="btn.value"
            :type="activeQuickBtn === btn.value ? 'primary' : 'default'"
            size="small"
            @click="handleQuickDate(btn.value)"
          >
            {{ btn.label }}
          </el-button>
        </div>
        <el-select v-model="selectedPlatform" placeholder="全部平台" clearable style="width: 120px">
          <el-option label="全部平台" value="" />
          <el-option 
            v-for="platform in availablePlatforms" 
            :key="platform.value" 
            :label="platform.label" 
            :value="platform.value"
          />
        </el-select>
        <el-button type="primary" @click="handleQuery">查询</el-button>
      </div>
      <div class="filter-right">
        <!-- <el-button @click="handleViewReport">查看报表</el-button>
        <el-button @click="handleExport">导出数据</el-button> -->
      </div>
    </div>

    <!-- 汇总统计卡片 -->
    <div class="summary-cards">
      <div class="stat-card">
        <div class="stat-icon">👤</div>
        <div class="stat-content">
          <div class="stat-label">账号总数</div>
          <div class="stat-value">{{ summaryData.totalAccounts || 0 }}</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">▶️</div>
        <div class="stat-content">
          <div class="stat-label">播放(阅读)量</div>
          <div class="stat-value">{{ formatNumber(summaryData.viewsCount || 0) }}</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">💬</div>
        <div class="stat-content">
          <div class="stat-label">评论量</div>
          <div class="stat-value">{{ formatNumber(summaryData.commentsCount || 0) }}</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">👍</div>
        <div class="stat-content">
          <div class="stat-label">点赞量</div>
          <div class="stat-value">{{ formatNumber(summaryData.likesCount || 0) }}</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">👥</div>
        <div class="stat-content">
          <div class="stat-label">涨粉量</div>
          <div class="stat-value">{{ formatNumber(summaryData.fansIncrease || 0) }}</div>
        </div>
      </div>
    </div>

    <!-- 每日汇总数据表格 -->
    <div class="data-section">
      <h3 class="section-title">每日汇总数据</h3>
      <el-table :data="dailyData" v-loading="loading" stripe>
        <el-table-column prop="date" label="时间" width="120" align="center" />
        <el-table-column prop="viewsCount" label="播放(阅读)量" width="140" align="center">
          <template #default="{ row }">{{ formatNumber(row.viewsCount || 0) }}</template>
        </el-table-column>
        <el-table-column prop="commentsCount" label="评论量" width="100" align="center">
          <template #default="{ row }">{{ formatNumber(row.commentsCount || 0) }}</template>
        </el-table-column>
        <el-table-column prop="likesCount" label="点赞量" width="100" align="center">
          <template #default="{ row }">{{ formatNumber(row.likesCount || 0) }}</template>
        </el-table-column>
        <el-table-column prop="fansIncrease" label="涨粉量" width="100" align="center">
          <template #default="{ row }">{{ formatNumber(row.fansIncrease || 0) }}</template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 账号详细数据表格 -->
    <div class="data-section">
      <h3 class="section-title">账号详细数据</h3>
      <el-table :data="accountList" v-loading="loading" stripe>
        <el-table-column label="账号" min-width="180">
          <template #default="{ row }">
            <div class="account-cell">
              <el-avatar :size="32" :src="row.avatarUrl">
                {{ row.nickname?.[0] || '?' }}
              </el-avatar>
              <span class="account-name">{{ row.nickname || row.username }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="platform" label="平台" width="100" align="center">
          <template #default="{ row }">
            <span>{{ getPlatformName(row.platform) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="viewsCount" label="播放(阅读)量" width="140" align="center">
          <template #default="{ row }">
            <span :class="{ 'error-text': row.viewsCount === null }">
              {{ row.viewsCount === null ? '获取失败' : formatNumber(row.viewsCount) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="commentsCount" label="评论量" width="100" align="center">
          <template #default="{ row }">{{ formatNumber(row.commentsCount || 0) }}</template>
        </el-table-column>
        <el-table-column prop="likesCount" label="点赞量" width="100" align="center">
          <template #default="{ row }">{{ formatNumber(row.likesCount || 0) }}</template>
        </el-table-column>
        <el-table-column prop="fansIncrease" label="涨粉量" width="100" align="center">
          <template #default="{ row }">{{ formatNumber(row.fansIncrease || 0) }}</template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="140" align="center">
          <template #default="{ row }">
            <span class="update-time">{{ row.updateTime || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleAccountDetail(row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
// 立即输出日志，确认组件脚本执行（在任何导入之前）
console.log('[PlatformDetail] ========== 组件脚本开始执行 ==========');

import { ref, computed, onMounted, nextTick, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { PLATFORMS } from '@media-manager/shared';
import type { PlatformType } from '@media-manager/shared';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import request from '@/api/request';

const route = useRoute();
const router = useRouter();

// 立即输出日志，确认组件脚本执行
console.log('[PlatformDetail] 组件脚本执行中, route:', route.path, route.params, route.query);
console.log('[PlatformDetail] router:', router);

const loading = ref(false);
const startDate = ref(dayjs().subtract(1, 'day').format('YYYY-MM-DD'));
const endDate = ref(dayjs().subtract(1, 'day').format('YYYY-MM-DD'));
const activeQuickBtn = ref('yesterday');
const selectedPlatform = ref<string>('');

// 从路由参数获取平台
const platformFromRoute = computed(() => {
  const platform = route.params.platform as string;
  console.log('[PlatformDetail] platformFromRoute computed:', platform, 'route.params:', route.params);
  return platform;
});

// 快捷日期按钮
const quickDateBtns = [
  { label: '昨天', value: 'yesterday' },
  { label: '前天', value: 'beforeYesterday' },
  { label: '近三天', value: 'last3days' },
  { label: '近七天', value: 'last7days' },
  { label: '近一个月', value: 'lastMonth' },
];

// 可用平台
const availablePlatforms = computed(() => {
  return Object.entries(PLATFORMS).map(([key, value]) => ({
    value: key,
    label: value.name,
  }));
});

// 汇总数据
const summaryData = ref({
  totalAccounts: 0,
  viewsCount: 0,
  commentsCount: 0,
  likesCount: 0,
  fansIncrease: 0,
});

// 每日汇总数据
const dailyData = ref<Array<{
  date: string;
  viewsCount: number;
  commentsCount: number;
  likesCount: number;
  fansIncrease: number;
}>>([]);

// 账号列表
const accountList = ref<Array<{
  id: number;
  nickname: string;
  username: string;
  avatarUrl: string | null;
  platform: string;
  viewsCount: number | null;
  commentsCount: number;
  likesCount: number;
  fansIncrease: number;
  updateTime: string;
}>>([]);

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

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

// 快捷日期选择
function handleQuickDate(type: string) {
  activeQuickBtn.value = type;
  const today = dayjs();
  
  switch (type) {
    case 'yesterday':
      startDate.value = today.subtract(1, 'day').format('YYYY-MM-DD');
      endDate.value = today.subtract(1, 'day').format('YYYY-MM-DD');
      break;
    case 'beforeYesterday':
      startDate.value = today.subtract(2, 'day').format('YYYY-MM-DD');
      endDate.value = today.subtract(2, 'day').format('YYYY-MM-DD');
      break;
    case 'last3days':
      startDate.value = today.subtract(2, 'day').format('YYYY-MM-DD');
      endDate.value = today.format('YYYY-MM-DD');
      break;
    case 'last7days':
      startDate.value = today.subtract(6, 'day').format('YYYY-MM-DD');
      endDate.value = today.format('YYYY-MM-DD');
      break;
    case 'lastMonth':
      startDate.value = today.subtract(29, 'day').format('YYYY-MM-DD');
      endDate.value = today.format('YYYY-MM-DD');
      break;
  }
}

// 查询
function handleQuery() {
  loadData();
}

// 加载数据
async function loadData() {
  // 优先使用 selectedPlatform，如果没有则从路由参数获取
  const platform = selectedPlatform.value || (route.params.platform as string) || (route.query.platform as string);
  
  console.log('[PlatformDetail] loadData 开始, platform:', platform, 'selectedPlatform.value:', selectedPlatform.value, 'route.params:', route.params);
  
  if (!platform) {
    console.error('[PlatformDetail] loadData: 缺少平台参数');
    ElMessage.error('请选择平台');
    return;
  }

  loading.value = true;
  
  try {
    console.log('[PlatformDetail] 开始调用接口:', { 
      platform, 
      startDate: startDate.value, 
      endDate: endDate.value,
      url: '/api/work-day-statistics/platform-detail'
    });

    const data = await request.get('/api/work-day-statistics/platform-detail', {
      params: {
        platform,
        startDate: startDate.value,
        endDate: endDate.value,
      },
    });

    console.log('[PlatformDetail] 接口响应:', data);

    // request 拦截器已经解包了响应，直接使用返回的数据
    if (data && typeof data === 'object') {
      console.log('[PlatformDetail] 数据解析成功:', data);
      
      // 更新汇总数据（使用 ?? 避免 0 值被误判）
      if (data.summary) {
        summaryData.value = {
          totalAccounts: data.summary.totalAccounts ?? 0,
          viewsCount: data.summary.viewsCount ?? 0,
          commentsCount: data.summary.commentsCount ?? 0,
          likesCount: data.summary.likesCount ?? 0,
          fansIncrease: data.summary.fansIncrease ?? 0,
        };
      }
      
      // 更新每日数据
      dailyData.value = Array.isArray(data.dailyData) ? data.dailyData : [];
      
      // 更新账号列表
      accountList.value = Array.isArray(data.accounts) ? data.accounts : [];
      
      console.log('[PlatformDetail] 数据已更新到界面:', {
        summary: summaryData.value,
        dailyDataCount: dailyData.value.length,
        accountCount: accountList.value.length,
      });
    } else {
      console.error('[PlatformDetail] 响应格式错误:', data);
      ElMessage.error('数据格式错误');
    }
  } catch (error: any) {
    console.error('[PlatformDetail] 加载平台详情失败:', error);
    console.error('[PlatformDetail] 错误详情:', {
      message: error?.message,
      response: error?.response,
      stack: error?.stack,
    });
    ElMessage.error(error?.response?.data?.message || error?.message || '加载数据失败');
  } finally {
    loading.value = false;
  }
}

// 查看报表
function handleViewReport() {
  ElMessage.info('查看报表功能开发中');
}

// 导出数据
function handleExport() {
  ElMessage.info('导出数据功能开发中');
}

// 账号详情
function handleAccountDetail(row: any) {
  router.push({
    name: 'AnalyticsAccount',
    query: {
      accountId: row.id,
      startDate: startDate.value,
      endDate: endDate.value,
    },
  });
}

// 初始化数据加载
function initDataLoad() {
  console.log('[PlatformDetail] initDataLoad, route:', route.path, route.params, route.query);
  
  // 直接从 route.params 获取平台参数（不依赖 computed）
  const platformParam = (route.params.platform as string) || (route.query.platform as string);
  console.log('[PlatformDetail] initDataLoad, platformParam:', platformParam);
  
  if (platformParam) {
    selectedPlatform.value = platformParam;
    // 如果 query 中有日期参数，使用它们
    if (route.query.startDate) {
      startDate.value = route.query.startDate as string;
    }
    if (route.query.endDate) {
      endDate.value = route.query.endDate as string;
    }
    
    console.log('[PlatformDetail] 准备加载数据, selectedPlatform:', selectedPlatform.value, 'startDate:', startDate.value, 'endDate:', endDate.value);
    
    // 使用 nextTick 确保响应式更新完成
    nextTick(() => {
      console.log('[PlatformDetail] nextTick 后, selectedPlatform:', selectedPlatform.value);
      loadData();
    });
  } else {
    console.error('[PlatformDetail] 缺少平台参数, route.params:', route.params, 'route.query:', route.query);
    ElMessage.warning('缺少平台参数，请从平台列表页进入');
  }
}

// 监听路由变化
watch(() => route.params.platform, (newPlatform) => {
  console.log('[PlatformDetail] 路由参数变化, newPlatform:', newPlatform);
  if (newPlatform) {
    selectedPlatform.value = newPlatform as string;
    nextTick(() => {
      loadData();
    });
  }
}, { immediate: false });

onMounted(() => {
  console.log('[PlatformDetail] ========== onMounted 执行 ==========');
  console.log('[PlatformDetail] route.path:', route.path);
  console.log('[PlatformDetail] route.params:', route.params);
  console.log('[PlatformDetail] route.query:', route.query);
  console.log('[PlatformDetail] route.name:', route.name);
  initDataLoad();
});
</script>

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

.platform-detail-page {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;

  .filter-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
    padding: 16px 20px;
    background: #fff;
    border-radius: $radius-lg;
    box-shadow: $shadow-sm;
    
    .filter-left {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .filter-label {
        font-size: 14px;
        color: $text-regular;
      }
      
      .quick-btns {
        display: flex;
        gap: 8px;
        margin-left: 8px;
      }
    }
  }

  .summary-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
    margin-bottom: 20px;

    .stat-card {
      display: flex;
      align-items: center;
      gap: 16px;
      padding: 20px;
      background: #fff;
      border-radius: $radius-lg;
      box-shadow: $shadow-sm;

      .stat-icon {
        font-size: 32px;
        width: 48px;
        height: 48px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f0f0f0;
        border-radius: 8px;
      }

      .stat-content {
        flex: 1;

        .stat-label {
          font-size: 13px;
          color: $text-secondary;
          margin-bottom: 4px;
        }

        .stat-value {
          font-size: 24px;
          font-weight: 600;
          color: $text-primary;
        }
      }
    }
  }

  .data-section {
    background: #fff;
    border-radius: $radius-lg;
    box-shadow: $shadow-sm;
    padding: 20px;
    margin-bottom: 20px;

    .section-title {
      margin: 0 0 16px 0;
      font-size: 16px;
      font-weight: 600;
      color: $text-primary;
    }

    .account-cell {
      display: flex;
      align-items: center;
      gap: 12px;

      .account-name {
        font-weight: 500;
        color: $text-primary;
      }
    }

    .error-text {
      color: #ef4444;
    }

    .update-time {
      font-size: 12px;
      color: $text-secondary;
    }
  }
}
</style>