<template>
  <div class="analytics-overview">
    <!-- 顶部筛选栏 -->
    <div class="filter-bar">
      <div class="filter-left">
        <el-select v-model="selectedGroup" placeholder="全部分组" clearable style="width: 140px">
          <el-option label="全部分组" value="" />
          <el-option 
            v-for="group in accountGroups" 
            :key="group.id" 
            :label="group.name" 
            :value="group.id" 
          />
        </el-select>
        <el-select v-model="selectedPlatform" placeholder="全部平台" clearable style="width: 140px">
          <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" :loading="refreshing" @click="handleRefreshAll">
          刷新数据
        </el-button>
        <span class="filter-tip">
          提示：昨日数据一般平台会在中午12点到下午2点更新，建议2点后查询
        </span>
      </div>
      <div class="filter-right">
        <el-button @click="handleExport">导出数据</el-button>
      </div>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-row">
      <div class="stat-card" v-for="(item, index) in summaryStats" :key="index">
        <div class="stat-label">{{ item.label }}</div>
        <div class="stat-value" :class="{ 'highlight': item.highlight }">{{ item.value }}</div>
      </div>
    </div>
    
    <!-- 搜索框 -->
    <div class="search-bar">
      <el-input 
        v-model="searchKeyword" 
        placeholder="请输入要搜索的账号" 
        clearable
        style="width: 300px"
        @clear="loadData"
        @keyup.enter="loadData"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>
    
    <!-- 数据表格 -->
    <div class="data-table">
      <el-table :data="filteredAccounts" v-loading="loading" stripe>
        <el-table-column label="账号" min-width="180" fixed="left">
          <template #default="{ row }">
            <div class="account-cell">
              <el-avatar :size="36" :src="row.avatarUrl">
                {{ row.nickname?.[0] || row.username?.[0] }}
              </el-avatar>
              <span class="account-name">{{ row.nickname || row.username }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="平台" width="100" align="center">
          <template #default="{ row }">
            <el-tag size="small" :type="getPlatformTagType(row.platform)">
              {{ getPlatformName(row.platform) }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="totalIncome" label="总收益" width="90" align="center">
          <template #default="{ row }">
            <span>{{ row.totalIncome !== null && row.totalIncome !== undefined ? row.totalIncome.toFixed(2) : '未支持' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="yesterdayIncome" label="昨日收益" width="90" align="center">
          <template #default="{ row }">
            <span>{{ row.yesterdayIncome !== null && row.yesterdayIncome !== undefined ? row.yesterdayIncome.toFixed(2) : '未支持' }}</span>
          </template>
        </el-table-column> -->
        <el-table-column prop="totalViews" label="总播放(阅读)" width="110" align="center">
          <template #default="{ row }">
            <span>{{ row.totalViews !== null && row.totalViews !== undefined ? formatNumber(row.totalViews) : '未支持' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="yesterdayViews" label="昨日播放(阅读)" width="120" align="center">
          <template #default="{ row }">
            <span>{{ row.yesterdayViews !== null && row.yesterdayViews !== undefined ? formatNumber(row.yesterdayViews) : '未支持' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="fansCount" label="粉丝数" width="90" align="center">
          <template #default="{ row }">
            <span class="fans-count">{{ formatNumber(row.fansCount || 0) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="yesterdayComments" label="昨日评论" width="90" align="center">
          <template #default="{ row }">
            <span>{{ row.yesterdayComments ?? 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="yesterdayLikes" label="昨日点赞" width="90" align="center">
          <template #default="{ row }">
            <span>{{ formatNumber(row.yesterdayLikes ?? 0) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="yesterdayFansIncrease" label="昨日涨粉" width="90" align="center">
          <template #default="{ row }">
            <span :class="{ 'increase': row.yesterdayFansIncrease > 0, 'decrease': row.yesterdayFansIncrease < 0 }">
              {{ row.yesterdayFansIncrease ?? 0 }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="140" align="center">
          <template #default="{ row }">
            <span class="update-time">{{ formatTime(row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <span :class="['status-tag', row.status === 'active' ? 'active' : 'inactive']">
              {{ row.status === 'active' ? '正常' : '异常' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              link 
              :loading="row.refreshing"
              @click="handleRefreshAccount(row)"
            >
              刷新数据
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { Search } from '@element-plus/icons-vue';
import { PLATFORMS, AVAILABLE_PLATFORM_TYPES } from '@media-manager/shared';
import type { PlatformType } from '@media-manager/shared';
import { useAuthStore } from '@/stores/auth';
import { useServerStore } from '@/stores/server';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import request from '@/api/request';

const authStore = useAuthStore();
const serverStore = useServerStore();
const loading = ref(false);
const refreshing = ref(false);

// 筛选条件
const selectedGroup = ref<number | ''>('');
const selectedPlatform = ref<PlatformType | ''>('');
const searchKeyword = ref('');

// 分组列表
interface AccountGroup {
  id: number;
  name: string;
}
const accountGroups = ref<AccountGroup[]>([]);

// 可用平台（统一配置：小红书、抖音、视频号、百家号）
const availablePlatforms = computed(() => {
  return AVAILABLE_PLATFORM_TYPES.map(key => ({
    value: key,
    label: PLATFORMS[key].name,
  }));
});

// 账号数据
interface AccountData {
  id: number;
  nickname: string;
  username: string;
  avatarUrl: string;
  platform: PlatformType;
  groupId?: number;
  fansCount: number;
  // totalIncome: number | null;
  // yesterdayIncome: number | null;
  totalViews: number | null;
  yesterdayViews: number | null;
  yesterdayComments: number;
  yesterdayLikes: number;
  yesterdayFansIncrease: number;
  updateTime: string;
  status: string;
  refreshing?: boolean;
}

const accounts = ref<AccountData[]>([]);

// 汇总统计
interface SummaryData {
  totalAccounts: number;
  totalWorks: number;
  // totalIncome: number;
  // yesterdayIncome: number;
  totalViews: number;
  yesterdayViews: number;
  totalFans: number;
  yesterdayComments: number;
  yesterdayLikes: number;
  yesterdayFansIncrease: number;
}

const summaryData = ref<SummaryData>({
  totalAccounts: 0,
  totalWorks: 0,
  // totalIncome: 0,
  // yesterdayIncome: 0,
  totalViews: 0,
  yesterdayViews: 0,
  totalFans: 0,
  yesterdayComments: 0,
  yesterdayLikes: 0,
  yesterdayFansIncrease: 0,
});

// 统计卡片数据（使用后端返回的汇总数据）
const summaryStats = computed(() => [
  { label: '账号总数', value: summaryData.value.totalAccounts },
  { label: '总作品数', value: summaryData.value.totalWorks },
  // { label: '总收益（元）', value: summaryData.value.totalIncome || 0 },
  // { label: '昨日收益（元）', value: summaryData.value.yesterdayIncome || 0 },
  { label: '总播放(阅读)', value: formatNumber(summaryData.value.totalViews || 0) },
  { label: '昨日播放(阅读)', value: formatNumber(summaryData.value.yesterdayViews || 0) },
  { label: '总粉丝', value: formatNumber(summaryData.value.totalFans || 0), highlight: true },
  { label: '昨日评论', value: summaryData.value.yesterdayComments || 0 },
  { label: '昨日点赞', value: formatNumber(summaryData.value.yesterdayLikes || 0) },
  { label: '昨日涨粉', value: summaryData.value.yesterdayFansIncrease || 0 },
]);

// 过滤后的账号列表（只显示统一配置的平台：小红书、抖音、视频号、百家号）
const filteredAccounts = computed(() => {
  let result = accounts.value.filter(a => AVAILABLE_PLATFORM_TYPES.includes(a.platform));
  
  if (selectedGroup.value) {
    result = result.filter(a => a.groupId === selectedGroup.value);
  }
  
  if (selectedPlatform.value) {
    result = result.filter(a => a.platform === selectedPlatform.value);
  }
  
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    result = result.filter(a => 
      a.nickname?.toLowerCase().includes(keyword) || 
      a.username?.toLowerCase().includes(keyword)
    );
  }
  
  return result;
});

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

function getPlatformTagType(platform: PlatformType) {
  const typeMap: Record<string, 'primary' | 'success' | 'warning' | 'danger' | 'info'> = {
    douyin: 'danger',
    xiaohongshu: 'danger',
    bilibili: 'primary',
    kuaishou: 'warning',
    weixin: 'success',
  };
  return typeMap[platform] || 'info';
}

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

function formatTime(time: string) {
  if (!time) return '-';
  const d = dayjs(time);
  if (!d.isValid()) return time;
  const nowYear = dayjs().year();
  return d.year() === nowYear ? d.format('MM-DD HH:mm') : d.format('YYYY-MM-DD HH:mm');
}

// 加载分组列表
async function loadGroups() {
  try {
    const res = await request.get('/api/accounts/groups');
    // 新接口：request 已经解包，res 就是分组数组
    if (Array.isArray(res)) {
      accountGroups.value = res as AccountGroup[];
    } else if ((res as any)?.data?.data) {
      // 兼容旧格式 { data: { data: [] } }
      accountGroups.value = (res as any).data.data || [];
    }
  } catch (error) {
    console.error('加载分组失败:', error);
  }
}

// 加载数据
async function loadData() {
  const userId = authStore.user?.id;
  if (!userId) return;
  
  loading.value = true;
  
  try {
    // 改为直接走 Node 服务（/api/...），避免依赖本地 Python 端口（:5005）
    const data = await request.get('/api/work-day-statistics/overview', {
      params: { user_id: userId }, // 兼容历史参数；后端会忽略并以 token 用户为准
    });

    if (data) {
      // 确保只保留统一配置的平台
      accounts.value = (data.accounts || []).filter((a: AccountData) => 
        AVAILABLE_PLATFORM_TYPES.includes(a.platform)
      );
      
      // 使用后端返回的汇总数据
      if (data.summary) {
        summaryData.value = {
          totalAccounts: data.summary.totalAccounts || 0,
          totalWorks: data.summary.totalWorks || 0,
          // totalIncome: data.summary.totalIncome || 0,
          // yesterdayIncome: data.summary.yesterdayIncome || 0,
          totalViews: data.summary.totalViews || 0,
          yesterdayViews: data.summary.yesterdayViews || 0,
          totalFans: data.summary.totalFans || 0,
          yesterdayComments: data.summary.yesterdayComments || 0,
          yesterdayLikes: data.summary.yesterdayLikes || 0,
          yesterdayFansIncrease: data.summary.yesterdayFansIncrease || 0,
        };
      }
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    ElMessage.error('加载数据失败，请稍后重试');
  } finally {
    loading.value = false;
  }
}

// 刷新所有数据
async function handleRefreshAll() {
  refreshing.value = true;
  try {
    await loadData();
    ElMessage.success('数据刷新成功');
  } finally {
    refreshing.value = false;
  }
}

// 刷新单个账号数据
async function handleRefreshAccount(account: AccountData) {
  account.refreshing = true;
  try {
    const userId = authStore.user?.id;
    if (!userId) return;

    // 直接复用 Node 现有刷新接口
    const data = await request.post(`/api/accounts/${account.id}/refresh`);
    Object.assign(account, data);
    ElMessage.success('账号数据刷新成功');
  } catch (error) {
    ElMessage.error('刷新失败');
  } finally {
    account.refreshing = false;
  }
}

// 导出数据
async function handleExport() {
  try {
    const baseUrl = serverStore.currentServer?.url;
    if (!baseUrl) {
      ElMessage.error('未连接服务器');
      return;
    }

    if (!authStore.accessToken) {
      ElMessage.error('未连接服务器或未登录');
      return;
    }

    const buildUrl = () => {
      const params = new URLSearchParams();
      if (selectedGroup.value) params.set('groupId', String(selectedGroup.value));
      if (selectedPlatform.value) params.set('platform', String(selectedPlatform.value));
      if (searchKeyword.value) params.set('keyword', searchKeyword.value);
      return `${baseUrl}/api/work-day-statistics/overview/export?${params.toString()}`;
    };

    const doFetch = async (token: string) => {
      const url = buildUrl();
      return await fetch(url, {
        method: 'GET',
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
    };

    let resp = await doFetch(authStore.accessToken!);

    // token 过期时，手动触发刷新逻辑并重试一次
    if (resp.status === 401) {
      const refreshed = await authStore.refreshAccessToken();
      if (!refreshed || !authStore.accessToken) {
        ElMessage.error('登录已过期，请重新登录');
        return;
      }
      resp = await doFetch(authStore.accessToken);
    }

    if (!resp.ok) {
      const text = await resp.text().catch(() => '');
      throw new Error(text || `导出失败，状态码：${resp.status}`);
    }

    const blob = await resp.blob();
    const downloadUrl = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = downloadUrl;
    a.download = `数据总览_${dayjs().format('YYYYMMDD_HHmmss')}.xlsx`;
    document.body.appendChild(a);
    a.click();
    a.remove();
    window.URL.revokeObjectURL(downloadUrl);
  } catch (error: any) {
    console.error('导出失败:', error);
    ElMessage.error(error?.message || '导出失败');
  }
}

onMounted(() => {
  loadGroups();
  loadData();
});
</script>

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

.analytics-overview {
  .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-tip {
        font-size: 12px;
        color: #f56c6c;
        margin-left: 8px;
      }
    }
  }
  
  .stats-row {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 0;
    margin-bottom: 20px;
    background: #fff;
    border-radius: $radius-lg;
    box-shadow: $shadow-sm;
    overflow: hidden;
    
    .stat-card {
      padding: 20px 16px;
      text-align: center;
      border-right: 1px solid #f0f0f0;
      
      &:last-child {
        border-right: none;
      }
      
      .stat-label {
        font-size: 12px;
        color: $text-secondary;
        margin-bottom: 8px;
        white-space: nowrap;
      }
      
      .stat-value {
        font-size: 24px;
        font-weight: 600;
        color: $text-primary;
        
        &.highlight {
          color: $primary-color;
        }
      }
    }
  }
  
  .search-bar {
    margin-bottom: 16px;
  }
  
  .data-table {
    background: #fff;
    border-radius: $radius-lg;
    box-shadow: $shadow-sm;
    overflow: hidden;
    
    .account-cell {
      display: flex;
      align-items: center;
      gap: 10px;
      
      .account-name {
        font-weight: 500;
        color: $text-primary;
      }
    }
    
    .fans-count {
      color: $primary-color;
      font-weight: 500;
    }
    
    .increase {
      color: #10b981;
    }
    
    .decrease {
      color: #ef4444;
    }
    
    .update-time {
      font-size: 12px;
      color: $text-secondary;
    }
    
    .status-tag {
      font-size: 12px;
      padding: 2px 8px;
      border-radius: 4px;
      
      &.active {
        color: #10b981;
        background: rgba(16, 185, 129, 0.1);
      }
      
      &.inactive {
        color: #ef4444;
        background: rgba(239, 68, 68, 0.1);
      }
    }
  }
}

@media (max-width: 1600px) {
  .analytics-overview {
    .stats-row {
      grid-template-columns: repeat(5, 1fr);
      
      .stat-card {
        &:nth-child(5) {
          border-right: none;
        }
        
        &:nth-child(n+6) {
          border-top: 1px solid #f0f0f0;
        }
      }
    }
  }
}

@media (max-width: 1200px) {
  .analytics-overview {
    .stats-row {
      grid-template-columns: repeat(3, 1fr);
      
      .stat-card {
        &:nth-child(3n) {
          border-right: none;
        }
        
        &:nth-child(n+4) {
          border-top: 1px solid #f0f0f0;
        }
      }
    }
    
    .filter-bar {
      flex-direction: column;
      align-items: flex-start;
      gap: 12px;
      
      .filter-left {
        flex-wrap: wrap;
        
        .filter-tip {
          width: 100%;
          margin-left: 0;
          margin-top: 8px;
        }
      }
    }
  }
}
</style>
