<template>
  <div class="work-analytics">
    <!-- 顶部筛选栏 -->
    <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="selectedAccounts" 
          multiple 
          collapse-tags 
          collapse-tags-tooltip
          placeholder="选择账号" 
          style="width: 160px"
        >
          <el-option 
            v-for="account in accountList" 
            :key="account.id" 
            :label="account.nickname" 
            :value="account.id"
          />
        </el-select>
        <el-button type="primary" @click="handleQuery">查询</el-button>
      </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-icon">
          <el-icon :size="18"><component :is="item.icon" /></el-icon>
        </div>
        <div class="stat-info">
          <div class="stat-label">{{ item.label }}</div>
          <div class="stat-value">{{ item.value }}</div>
        </div>
      </div>
    </div>
    
    <!-- 第二行筛选 -->
    <div class="filter-bar secondary">
      <div class="filter-left">
        <el-select v-model="selectedGroup" placeholder="全部" clearable style="width: 120px">
          <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: 120px">
          <el-option label="全部平台" value="" />
          <el-option 
            v-for="platform in availablePlatforms" 
            :key="platform.value" 
            :label="platform.label" 
            :value="platform.value"
          />
        </el-select>
        <el-select v-model="sortBy" style="width: 160px">
          <el-option label="按发布时间顺序排列" value="publish_desc" />
          <el-option label="按发布时间倒序排列" value="publish_asc" />
          <el-option label="按阅读量排序" value="views_desc" />
          <el-option label="按点赞量排序" value="likes_desc" />
          <el-option label="按评论量排序" value="comments_desc" />
        </el-select>
        <el-input 
          v-model="searchKeyword" 
          placeholder="请输入要搜索的作品标题" 
          clearable
          style="width: 240px"
          @clear="handleQuery"
          @keyup.enter="handleQuery"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>
    
    <!-- 数据表格 -->
    <div class="data-table">
      <el-table :data="workList" v-loading="loading" stripe>
        <el-table-column label="账号" width="150">
          <template #default="{ row }">
            <div class="account-cell">
              <el-avatar :size="32" :src="row.accountAvatar">
                {{ row.accountName?.[0] }}
              </el-avatar>
              <span class="account-name">{{ row.accountName }}</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 label="标题" min-width="300">
          <template #default="{ row }">
            <div class="title-cell">
              <div class="work-title">{{ row.title }}</div>
              <div class="work-stats">
                <span class="stat-item">推荐 <em>{{ row.recommendCount ?? '--' }}</em></span>
                <span class="stat-item">阅读 <em>{{ row.viewsCount ?? 0 }}</em></span>
                <span class="stat-item">评论 <em>{{ row.commentsCount ?? 0 }}</em></span>
                <span class="stat-item">分享 <em>{{ row.sharesCount ?? 0 }}</em></span>
                <span class="stat-item">收藏 <em>{{ row.collectsCount ?? 0 }}</em></span>
                <span class="stat-item">点赞 <em>{{ row.likesCount ?? 0 }}</em></span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="workType" label="类型" width="80" align="center">
          <template #default="{ row }">
            <span>{{ row.workType || '动态' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="publishTime" label="发布时间" width="160" align="center">
          <template #default="{ row }">
            <span class="publish-time">{{ formatTime(row.publishTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="totalWorks"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleQuery"
          @current-change="handleQuery"
        />
      </div>
    </div>
    
    <!-- 作品详情抽屉 -->
    <el-drawer v-model="drawerVisible" title="作品详情" size="50%">
      <div v-if="selectedWork" class="work-detail">
        <!-- 作品基本信息 -->
        <div class="detail-header">
          <el-image 
            :src="selectedWork.coverUrl" 
            class="work-cover"
            fit="cover"
          >
            <template #error>
              <div class="cover-placeholder">
                <el-icon :size="32"><Picture /></el-icon>
              </div>
            </template>
          </el-image>
          <div class="header-info">
            <h3>{{ selectedWork.title }}</h3>
            <div class="meta-info">
              <el-tag size="small">{{ getPlatformName(selectedWork.platform) }}</el-tag>
              <span class="publish-time">发布于 {{ formatTime(selectedWork.publishTime) }}</span>
            </div>
          </div>
        </div>
        
        <!-- 数据统计 -->
        <div class="detail-stats">
          <div class="stat-item">
            <div class="stat-value">{{ selectedWork.viewsCount || 0 }}</div>
            <div class="stat-label">阅读</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ selectedWork.likesCount || 0 }}</div>
            <div class="stat-label">点赞</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ selectedWork.commentsCount || 0 }}</div>
            <div class="stat-label">评论</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ selectedWork.collectsCount || 0 }}</div>
            <div class="stat-label">收藏</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ selectedWork.sharesCount || 0 }}</div>
            <div class="stat-label">分享</div>
          </div>
        </div>
        
        <!-- 作品内容 -->
        <div class="detail-content" v-if="selectedWork.content">
          <h4>作品内容</h4>
          <div class="content-text">{{ selectedWork.content }}</div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { Search, Picture, Document, View, ChatDotRound, Share, Star, Pointer } from '@element-plus/icons-vue';
import { PLATFORMS } from '@media-manager/shared';
import type { PlatformType } from '@media-manager/shared';
import { useAuthStore } from '@/stores/auth';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import request from '@/api/request';

const PYTHON_API_URL = 'http://localhost:5005';

const authStore = useAuthStore();
const loading = ref(false);

// 日期筛选
const startDate = ref(dayjs().subtract(30, 'day').format('YYYY-MM-DD'));
const endDate = ref(dayjs().format('YYYY-MM-DD'));
const activeQuickBtn = ref('lastMonth');

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

// 账号选择
const selectedAccounts = ref<number[]>([]);
const accountList = ref<{ id: number; nickname: string }[]>([]);

// 分组和平台筛选
const selectedGroup = ref<number | ''>('');
const selectedPlatform = ref<PlatformType | ''>('');
const sortBy = ref('publish_desc');
const searchKeyword = ref('');

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

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

// 分页
const currentPage = ref(1);
const pageSize = ref(20);
const totalWorks = ref(0);

// 汇总统计
const summaryData = ref({
  totalWorks: 0,
  recommendCount: 0,
  viewsCount: 0,
  commentsCount: 0,
  sharesCount: 0,
  collectsCount: 0,
  likesCount: 0,
});

// 统计卡片数据
const summaryStats = computed(() => [
  { label: '作品总数', value: summaryData.value.totalWorks, icon: Document },
  { label: '推荐量', value: summaryData.value.recommendCount, icon: Pointer },
  { label: '播放(阅读)量', value: summaryData.value.viewsCount, icon: View },
  { label: '评论量', value: summaryData.value.commentsCount, icon: ChatDotRound },
  { label: '分享量', value: summaryData.value.sharesCount, icon: Share },
  { label: '收藏量', value: summaryData.value.collectsCount, icon: Star },
  { label: '点赞量', value: summaryData.value.likesCount, icon: Pointer },
]);

// 作品数据
interface WorkData {
  id: number;
  title: string;
  coverUrl: string;
  content: string;
  platform: PlatformType;
  accountId: number;
  accountName: string;
  accountAvatar: string;
  workType: string;
  publishTime: string;
  recommendCount: number | null;
  viewsCount: number;
  commentsCount: number;
  sharesCount: number;
  collectsCount: number;
  likesCount: number;
}

const workList = ref<WorkData[]>([]);

// 抽屉相关
const drawerVisible = ref(false);
const selectedWork = ref<WorkData | null>(null);

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 formatTime(time: string) {
  if (!time) return '-';
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
}

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

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

// 加载账号列表
async function loadAccountList() {
  try {
    const res = await request.get('/api/accounts');
    if (res.data.success) {
      accountList.value = (res.data.data || []).map((a: any) => ({
        id: a.id,
        nickname: a.nickname || a.username,
      }));
    }
  } catch (error) {
    console.error('加载账号列表失败:', error);
  }
}

// 加载分组列表
async function loadGroups() {
  try {
    const res = await request.get('/api/accounts/groups');
    if (res.data.success) {
      accountGroups.value = res.data.data || [];
    }
  } catch (error) {
    console.error('加载分组失败:', error);
  }
}

// 加载数据
async function loadData() {
  const userId = authStore.user?.id;
  if (!userId) return;
  
  loading.value = true;
  
  try {
    const queryParams = new URLSearchParams({
      user_id: userId.toString(),
      start_date: startDate.value,
      end_date: endDate.value,
      page: currentPage.value.toString(),
      page_size: pageSize.value.toString(),
      sort_by: sortBy.value,
    });
    
    if (selectedPlatform.value) {
      queryParams.append('platform', selectedPlatform.value);
    }
    
    if (selectedAccounts.value.length > 0) {
      queryParams.append('account_ids', selectedAccounts.value.join(','));
    }
    
    if (searchKeyword.value) {
      queryParams.append('keyword', searchKeyword.value);
    }
    
    const response = await fetch(`${PYTHON_API_URL}/work_day_statistics/works?${queryParams}`);
    const result = await response.json();
    
    if (result.success && result.data) {
      workList.value = result.data.works || [];
      totalWorks.value = result.data.total || 0;
      
      if (result.data.summary) {
        summaryData.value = result.data.summary;
      }
    }
  } catch (error) {
    console.error('加载作品数据失败:', error);
  } finally {
    loading.value = false;
  }
}

// 查看详情
function handleView(row: WorkData) {
  selectedWork.value = row;
  drawerVisible.value = true;
}

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

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

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

.work-analytics {
  .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;
    
    &.secondary {
      margin-bottom: 16px;
      padding: 12px 20px;
    }
    
    .filter-left {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .filter-label {
        font-size: 14px;
        color: $text-regular;
      }
      
      .quick-btns {
        display: flex;
        gap: 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;
      display: flex;
      align-items: center;
      gap: 12px;
      border-right: 1px solid #f0f0f0;
      
      &:last-child {
        border-right: none;
      }
      
      .stat-icon {
        width: 36px;
        height: 36px;
        background: $primary-color-light;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: $primary-color;
        flex-shrink: 0;
      }
      
      .stat-info {
        .stat-label {
          font-size: 12px;
          color: $text-secondary;
          margin-bottom: 4px;
          white-space: nowrap;
        }
        
        .stat-value {
          font-size: 20px;
          font-weight: 600;
          color: $text-primary;
        }
      }
    }
  }
  
  .data-table {
    background: #fff;
    border-radius: $radius-lg;
    box-shadow: $shadow-sm;
    overflow: hidden;
    
    .account-cell {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .account-name {
        font-weight: 500;
        color: $text-primary;
      }
    }
    
    .title-cell {
      .work-title {
        font-weight: 500;
        color: $primary-color;
        margin-bottom: 6px;
        cursor: pointer;
        
        &:hover {
          text-decoration: underline;
        }
      }
      
      .work-stats {
        display: flex;
        gap: 16px;
        font-size: 12px;
        color: $text-secondary;
        
        .stat-item {
          em {
            font-style: normal;
            color: $primary-color;
            margin-left: 2px;
          }
        }
      }
    }
    
    .publish-time {
      font-size: 13px;
      color: $text-secondary;
    }
    
    .pagination-wrapper {
      padding: 16px 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}

.work-detail {
  .detail-header {
    display: flex;
    gap: 16px;
    margin-bottom: 24px;
    
    .work-cover {
      width: 120px;
      height: 120px;
      border-radius: 8px;
      flex-shrink: 0;
      
      .cover-placeholder {
        width: 100%;
        height: 100%;
        background: #f3f4f6;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #9ca3af;
      }
    }
    
    .header-info {
      flex: 1;
      
      h3 {
        margin: 0 0 12px 0;
        font-size: 16px;
        line-height: 1.5;
      }
      
      .meta-info {
        display: flex;
        align-items: center;
        gap: 12px;
        
        .publish-time {
          font-size: 13px;
          color: $text-secondary;
        }
      }
    }
  }
  
  .detail-stats {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 16px;
    margin-bottom: 24px;
    
    .stat-item {
      background: #f8fafc;
      border-radius: 12px;
      padding: 16px;
      text-align: center;
      
      .stat-value {
        font-size: 24px;
        font-weight: 600;
        color: $primary-color;
      }
      
      .stat-label {
        font-size: 13px;
        color: $text-secondary;
        margin-top: 4px;
      }
    }
  }
  
  .detail-content {
    h4 {
      margin: 0 0 12px 0;
      font-size: 15px;
      color: $text-primary;
    }
    
    .content-text {
      font-size: 14px;
      line-height: 1.8;
      color: $text-regular;
      white-space: pre-wrap;
    }
  }
}

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

@media (max-width: 1200px) {
  .work-analytics {
    .filter-bar {
      flex-direction: column;
      align-items: flex-start;
      gap: 12px;
      
      .filter-left {
        flex-wrap: wrap;
      }
    }
    
    .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;
        }
      }
    }
  }
}
</style>
