<template>
  <div class="works-page">
    <div class="page-header">
      <h2>作品管理</h2>
      <div class="header-stats">
        <span>总作品: {{ stats.totalCount }}</span>
        <span>总播放: {{ formatNumber(stats.totalPlayCount) }}</span>
        <span>总点赞: {{ formatNumber(stats.totalLikeCount) }}</span>
      </div>
    </div>
    
    <!-- 筛选栏 -->
    <div class="page-card filter-bar">
      <el-select v-model="filter.accountId" placeholder="选择账号" clearable style="width: 200px">
        <el-option
          v-for="account in accounts"
          :key="account.id"
          :label="`${account.accountName} (${getPlatformName(account.platform)})`"
          :value="account.id"
        />
      </el-select>
      <el-select v-model="filter.platform" placeholder="平台" clearable style="width: 120px">
        <el-option
          v-for="platform in platforms"
          :key="platform.type"
          :label="platform.name"
          :value="platform.type"
        />
      </el-select>
      <el-select v-model="filter.status" placeholder="状态" clearable style="width: 120px">
        <el-option label="已发布" value="published" />
        <el-option label="审核中" value="reviewing" />
        <el-option label="未通过" value="rejected" />
        <el-option label="草稿" value="draft" />
        <el-option label="已删除" value="deleted" />
      </el-select>
      <el-input 
        v-model="filter.keyword" 
        placeholder="搜索作品标题" 
        clearable 
        style="width: 200px"
        @keyup.enter="loadWorks"
      />
      <el-button type="primary" @click="loadWorks">
        <el-icon><Search /></el-icon>
        搜索
      </el-button>
      <el-button @click="refreshAllWorks" :loading="refreshing" v-if="!taskStore.runningSyncWorksTask">
        <el-icon><Refresh /></el-icon>
        同步作品
      </el-button>
      <el-button type="danger" @click="stopSyncWorks" v-else>
        <el-icon><CircleCloseFilled /></el-icon>
        停止同步
      </el-button>
      <el-button type="success" @click="syncAllComments" :loading="syncingComments">
        <el-icon><ChatDotSquare /></el-icon>
        同步评论
      </el-button>
    </div>
    
    <!-- 作品列表 -->
    <div class="page-card">
      <div class="works-grid" v-loading="loading">
        <div v-if="works.length === 0 && !loading" class="empty-state">
          <el-empty description="暂无作品数据">
            <el-button type="primary" @click="refreshAllWorks">同步作品</el-button>
          </el-empty>
        </div>
        
        <div 
          v-for="work in works" 
          :key="work.id" 
          class="work-card"
          @click="openWorkDetail(work)"
        >
          <div class="work-cover">
            <img :src="getWorkCoverSrc(work)" :alt="work.title" @error="handleImageError" />
          </div>
          
          <div class="work-info">
            <div class="work-title" :title="work.title">{{ work.title || '无标题' }}</div>
            <div class="work-meta">
              <el-tag size="small" type="info">{{ getPlatformName(work.platform) }}</el-tag>
            </div>
            <div class="work-stats">
              <span><el-icon><VideoPlay /></el-icon> {{ formatNumber(work.playCount) }}</span>
              <span><el-icon><Star /></el-icon> {{ formatNumber(work.likeCount) }}</span>
              <span><el-icon><ChatDotSquare /></el-icon> {{ work.commentCount }}</span>
              <span><el-icon><Share /></el-icon> {{ work.shareCount }}</span>
            </div>
          </div>
          
          <div class="work-actions">
            <el-button type="primary" link size="small" @click.stop="viewComments(work)">
              查看评论 ({{ work.commentCount }})
            </el-button>
          </div>
        </div>
      </div>
      
      <el-pagination
        v-if="pagination.total > 0"
        v-model:current-page="pagination.page"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        layout="total, prev, pager, next"
        style="margin-top: 20px"
        @current-change="loadWorks"
      />
    </div>
    
    <!-- 作品详情对话框 -->
    <el-dialog 
      v-model="showDetailDialog" 
      :title="currentWork?.title || '作品详情'" 
      width="800px"
      destroy-on-close
    >
      <div class="work-detail" v-if="currentWork">
        <div class="detail-left">
          <div class="detail-cover">
            <img :src="currentWork.coverUrl" :alt="currentWork.title" />
          </div>
        </div>
        <div class="detail-right">
          <div class="detail-row">
            <label>平台：</label>
            <el-tag>{{ getPlatformName(currentWork.platform) }}</el-tag>
          </div>
          <div class="detail-row">
            <label>状态：</label>
            <el-tag :type="getStatusType(currentWork.status)">
              {{ getStatusText(currentWork.status) }}
            </el-tag>
          </div>
          <div class="detail-row">
            <label>发布时间：</label>
            <span>{{ formatDate(currentWork.publishTime) }}</span>
          </div>
          <div class="detail-row">
            <label>时长：</label>
            <span>{{ formatDuration(currentWork.duration) }}</span>
          </div>
          <div class="detail-stats">
            <div class="stat-item">
              <div class="stat-value">{{ formatNumber(currentWork.playCount) }}</div>
              <div class="stat-label">播放</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ formatNumber(currentWork.likeCount) }}</div>
              <div class="stat-label">点赞</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ currentWork.commentCount }}</div>
              <div class="stat-label">评论</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ currentWork.shareCount }}</div>
              <div class="stat-label">分享</div>
            </div>
          </div>
          <div class="detail-description" v-if="currentWork.description">
            <label>描述：</label>
            <p>{{ currentWork.description }}</p>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="showDetailDialog = false">关闭</el-button>
        <el-button type="primary" @click="viewComments(currentWork!)">
          查看评论
        </el-button>
        <el-button 
          type="danger" 
          @click="deletePlatformWork(currentWork!)"
          v-if="currentWork?.platform === 'douyin' || currentWork?.platform === 'xiaohongshu'"
        >
          <el-icon><Delete /></el-icon>
          删除平台作品
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 评论抽屉 -->
    <el-drawer
      v-model="showCommentsDrawer"
      :title="commentsWork ? `评论 - ${commentsWork.title || '作品'}` : '所有评论'"
      size="500px"
      destroy-on-close
    >
      <div class="comments-drawer-header" v-if="commentsWork">
        <img :src="getWorkCoverSrc(commentsWork)" class="work-thumb" @error="handleImageError" />
        <div class="work-brief">
          <div class="work-brief-title">{{ commentsWork.title || '无标题' }}</div>
          <div class="work-brief-meta">
            <el-tag size="small">{{ getPlatformName(commentsWork.platform) }}</el-tag>
            <span>{{ commentsWork.commentCount }} 条评论</span>
          </div>
        </div>
      </div>
      <div class="comments-drawer-header" v-else>
        <div class="work-brief">
          <div class="work-brief-title">所有评论</div>
          <div class="work-brief-meta">
            <span>共 {{ commentsPagination.total }} 条评论</span>
          </div>
        </div>
      </div>
      
      <el-divider />
      
      <div class="comments-list" v-loading="commentsLoading">
        <div v-if="comments.length === 0 && !commentsLoading" class="empty-comments">
          <el-empty description="暂无评论" :image-size="80" />
        </div>
        
        <div v-for="comment in comments" :key="comment.id" class="comment-item">
          <el-avatar :size="36" :src="comment.authorAvatar || undefined">
            {{ comment.authorName?.[0] }}
          </el-avatar>
          <div class="comment-body">
            <div class="comment-header">
              <span class="author-name">{{ comment.authorName }}</span>
              <span class="comment-time">{{ formatDate(comment.commentTime) }}</span>
            </div>
            <div class="comment-text">{{ comment.content }}</div>
            <div class="comment-actions">
              <span class="like-count">
                <el-icon><Star /></el-icon> {{ comment.likeCount }}
              </span>
              <el-button 
                v-if="!comment.replyContent"
                type="primary" 
                link 
                size="small"
                @click="openReplyDialog(comment)"
              >
                回复
              </el-button>
            </div>
            <div v-if="comment.replyContent" class="reply-box">
              <strong>已回复：</strong>{{ comment.replyContent }}
            </div>
          </div>
        </div>
      </div>
      
      <div class="comments-pagination" v-if="commentsPagination.total > commentsPagination.pageSize">
        <el-pagination
          v-model:current-page="commentsPagination.page"
          :page-size="commentsPagination.pageSize"
          :total="commentsPagination.total"
          layout="prev, pager, next"
          small
          @change="loadComments"
        />
      </div>
    </el-drawer>
    
    <!-- 回复评论对话框 -->
    <el-dialog v-model="showReplyDialog" title="回复评论" width="500px">
      <div class="reply-original">
        <strong>原评论：</strong>
        <p>{{ replyTarget?.content }}</p>
      </div>
      <el-input
        v-model="replyContent"
        type="textarea"
        :rows="4"
        placeholder="输入回复内容"
      />
      <template #footer>
        <el-button @click="showReplyDialog = false">取消</el-button>
        <el-button type="primary" @click="handleReply" :loading="replying">
          回复
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 评论同步对话框 -->
    <el-dialog 
      v-model="showSyncDialog" 
      title="同步评论" 
      width="450px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="syncState.status !== 'syncing'"
    >
      <div class="sync-status">
        <!-- 同步中 -->
        <template v-if="syncState.status === 'syncing'">
          <div class="sync-animation">
            <el-icon class="is-loading" :size="48" color="#409eff"><Loading /></el-icon>
          </div>
          <div class="sync-text">
            正在同步评论<span class="sync-dots">{{ syncDots }}</span>
          </div>
          <el-progress 
            :percentage="Math.floor(syncState.progress)" 
            :stroke-width="8"
            style="margin: 16px 0"
          />
          <div class="sync-hint">
            正在从平台获取评论数据，请耐心等待...
          </div>
          <div class="sync-steps">
            <span :class="{ active: syncState.step >= 1 }">连接平台</span>
            <span :class="{ active: syncState.step >= 2 }">获取作品</span>
            <span :class="{ active: syncState.step >= 3 }">提取评论</span>
          </div>
        </template>
        
        <!-- 同步成功 -->
        <template v-else-if="syncState.status === 'success'">
          <div class="sync-animation">
            <el-icon :size="48" color="#67c23a"><CircleCheckFilled /></el-icon>
          </div>
          <div class="sync-text success">同步完成</div>
          <div class="sync-result">
            <p>成功同步 <strong>{{ syncState.syncedCount }}</strong> 条评论</p>
            <p v-if="syncState.accountsCount">涉及 {{ syncState.accountsCount }} 个账号</p>
          </div>
          <el-button type="primary" link @click="viewAllComments" style="margin-top: 12px">
            查看所有评论
          </el-button>
        </template>
        
        <!-- 同步失败 -->
        <template v-else-if="syncState.status === 'failed'">
          <div class="sync-animation">
            <el-icon :size="48" color="#f56c6c"><CircleCloseFilled /></el-icon>
          </div>
          <div class="sync-text error">同步失败</div>
          <div class="sync-error">{{ syncState.error }}</div>
        </template>
        
        <!-- 无评论 -->
        <template v-else-if="syncState.status === 'empty'">
          <div class="sync-animation">
            <el-icon :size="48" color="#909399"><WarningFilled /></el-icon>
          </div>
          <div class="sync-text">未获取到新评论</div>
          <div class="sync-hint">可能原因：平台暂无新评论，或 Cookie 已过期</div>
        </template>
      </div>
      
      <template #footer>
        <el-button v-if="syncState.status === 'syncing'" type="danger" @click="stopCommentSync">
          中断同步
        </el-button>
        <el-button v-else type="primary" @click="closeSyncDialog">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed, watch } from 'vue';
import { Search, Refresh, VideoPlay, Star, ChatDotSquare, Share, Loading, CircleCheckFilled, CircleCloseFilled, WarningFilled, Delete } from '@element-plus/icons-vue';
import { ElMessageBox } from 'element-plus';
import { ElMessage } from 'element-plus';
import request from '@/api/request';
import { accountsApi } from '@/api/accounts';
import { PLATFORMS, AVAILABLE_PLATFORM_TYPES, WS_EVENTS } from '@media-manager/shared';
import type { Work, WorkStats, PlatformAccount, PlatformType, Comment } from '@media-manager/shared';
import { useServerStore } from '@/stores/server';
import { useAuthStore } from '@/stores/auth';
import { useTaskQueueStore } from '@/stores/taskQueue';
import dayjs from 'dayjs';

const serverStore = useServerStore();
const authStore = useAuthStore();
const taskStore = useTaskQueueStore();

// 监听作品刷新信号，当 sync_works 任务完成时自动刷新作品列表
watch(() => taskStore.worksRefreshTrigger, () => {
  console.log('[Works] worksRefreshTrigger changed, refreshing list...');
  loadWorks();
  loadStats();
});

// Bug #6070: 监听账号数据变更事件，新增账号后自动刷新作品列表（因为新账号需要显示其作品）
watch(() => taskStore.accountRefreshTrigger, () => {
  console.log('[Works] accountRefreshTrigger changed, refreshing list...');
  loadWorks();
  loadStats();
});

const loading = ref(false);
const refreshing = ref(false);
const syncingComments = ref(false);
const showDetailDialog = ref(false);
const showCommentsDrawer = ref(false);
const showReplyDialog = ref(false);
const showSyncDialog = ref(false);
const commentsLoading = ref(false);
const replying = ref(false);

// 评论同步状态
const syncDots = ref('');
const syncState = reactive({
  status: 'syncing' as 'syncing' | 'success' | 'failed' | 'empty',
  progress: 0,
  step: 1,
  syncedCount: 0,
  accountsCount: 0,
  error: '',
});
let syncTimer: ReturnType<typeof setInterval> | null = null;

const works = ref<Work[]>([]);
const accounts = ref<PlatformAccount[]>([]);
const currentWork = ref<Work | null>(null);
const commentsWork = ref<Work | null>(null);
const comments = ref<Comment[]>([]);
const replyTarget = ref<Comment | null>(null);
const replyContent = ref('');

const stats = ref<WorkStats>({
  totalCount: 0,
  publishedCount: 0,
  totalPlayCount: 0,
  totalLikeCount: 0,
  totalCommentCount: 0,
});

const commentsPagination = reactive({
  page: 1,
  pageSize: 15,
  total: 0,
});

// 平台选项（统一配置：小红书、抖音、视频号、百家号）
const platforms = computed(() => 
  AVAILABLE_PLATFORM_TYPES.map(type => PLATFORMS[type])
);

const filter = reactive({
  accountId: undefined as number | undefined,
  platform: '' as PlatformType | '',
  status: '',
  keyword: '',
});

const pagination = reactive({
  page: 1,
  pageSize: 15,
  total: 0,
});

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

function getStatusType(status: string) {
  const map: Record<string, 'success' | 'warning' | 'danger' | 'info'> = {
    published: 'success',
    reviewing: 'warning',
    rejected: 'danger',
    draft: 'info',
    deleted: 'danger',
    failed: 'danger',
    processing: 'warning',
    pending: 'info',
  };
  return map[status] || 'info';
}

function getStatusText(status: string) {
  const map: Record<string, string> = {
    published: '已发布',
    reviewing: '审核中',
    rejected: '未通过',
    draft: '草稿',
    deleted: '已删除',
    failed: '失败',
    processing: '发布中',
    pending: '待发布',
  };
  return map[status] || status;
}

function formatDate(date: string) {
  if (!date) return '-';
  return dayjs(date).format('YYYY-MM-DD HH:mm');
}

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

// 格式化时长（秒转换为 时:分:秒 或 分:秒）
function formatDuration(seconds: number | string | undefined): string {
  if (!seconds && seconds !== 0) return '-';
  
  const totalSeconds = typeof seconds === 'string' ? parseInt(seconds, 10) : seconds;
  if (isNaN(totalSeconds) || totalSeconds < 0) return '-';
  
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const secs = totalSeconds % 60;
  
  if (hours > 0) {
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  }
  return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}

// 作品列表/评论等处的封面：兼容 coverUrl / cover_url，无封面时用占位图
const COVER_PLACEHOLDER = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><rect fill="%23f0f0f0" width="100" height="100"/><text x="50" y="55" text-anchor="middle" fill="%23999" font-size="12">无封面</text></svg>';

function getWorkCoverSrc(work: Work): string {
  const url = (work as { coverUrl?: string; cover_url?: string }).coverUrl ?? (work as { cover_url?: string }).cover_url ?? '';
  if (!url || typeof url !== 'string' || !url.trim()) return COVER_PLACEHOLDER;
  return getSecureCoverUrl(url);
}

// 将 HTTP 图片 URL 转换为 HTTPS（小红书等平台的图片 URL 可能是 HTTP）
function getSecureCoverUrl(url: string): string {
  if (!url) return '';
  // 将 http:// 转换为 https://
  if (url.startsWith('http://')) {
    return url.replace('http://', 'https://');
  }
  return url;
}

function handleImageError(e: Event) {
  const img = e.target as HTMLImageElement;
  img.src = COVER_PLACEHOLDER;
}

async function loadWorks() {
  loading.value = true;
  try {
    const result = await request.get('/api/works', {
      params: {
        page: pagination.page,
        pageSize: pagination.pageSize,
        accountId: filter.accountId,
        platform: filter.platform || undefined,
        status: filter.status || undefined,
        keyword: filter.keyword || undefined,
      },
    }) as { items: Work[]; total: number };
    works.value = result?.items || [];
    pagination.total = result?.total || 0;
  } catch {
    works.value = [];
  } finally {
    loading.value = false;
  }
  // 修复 #6074：同步更新统计数据，避免快速切换筛选条件时 loadStats 结果与作品列表不一致
  await loadStats();
}

async function loadStats() {
  try {
    const params: Record<string, unknown> = {};
    if (filter.accountId) params.accountId = filter.accountId;
    if (filter.platform) params.platform = filter.platform;
    if (filter.status) params.status = filter.status;
    if (filter.keyword) params.keyword = filter.keyword;
    const result = await request.get('/api/works/stats', { params }) as WorkStats;
    if (result) {
      stats.value = result;
    }
  } catch {
    // 忽略错误
  }
}

async function loadAccounts() {
  try {
    accounts.value = await accountsApi.getAccounts();
  } catch {
    // 忽略错误
  }
}

async function refreshAllWorks() {
  if (!accounts.value.length) {
    ElMessage.warning('请先添加平台账号');
    return;
  }
  
  refreshing.value = true;
  try {
    // 根据筛选：选了账号只同步该账号；只选了平台则只同步该平台；都没选则同步所有
    const accountId = filter.accountId;
    const platform = filter.platform || undefined;
    const account = accountId ? accounts.value.find((a) => a.id === accountId) : undefined;
    const accountName = account ? `${account.accountName || '账号'} (${getPlatformName(account.platform as PlatformType)})` : undefined;
    const platformName = platform ? getPlatformName(platform) : undefined;
    await taskStore.syncWorks(accountId, accountName, platform, platformName);
    const msg = accountId
      ? '已创建同步任务，仅同步当前选中账号'
      : platform
        ? `已创建同步任务，仅同步「${platformName}」平台账号`
        : '已创建同步任务，将同步所有账号';
    ElMessage.success(msg);
    taskStore.openDialog();
  } catch (error) {
    ElMessage.error((error as Error)?.message || '创建同步任务失败');
  } finally {
    refreshing.value = false;
  }
}

// 停止正在运行的作品同步任务
async function stopSyncWorks() {
  const task = taskStore.runningSyncWorksTask;
  if (!task) return;
  
  try {
    const ok = await taskStore.cancelTask(task.id);
    if (ok) {
      ElMessage.success('已发送取消请求，同步任务将停止');
    }
  } catch {
    ElMessage.error('取消同步任务失败');
  }
}

// WebSocket 连接用于接收同步结果
let ws: WebSocket | null = null;
let wsReconnectTimer: ReturnType<typeof setTimeout> | null = null;
let syncTimeoutTimer: ReturnType<typeof setTimeout> | null = null;

function setupWebSocket() {
  // 检查是否已连接
  if (ws && ws.readyState === WebSocket.OPEN) {
    console.log('[WS] Already connected');
    return;
  }
  
  // 检查 token 是否可用
  const token = authStore.accessToken;
  if (!token) {
    console.warn('[WS] No token available, cannot setup WebSocket');
    return;
  }
  
  const serverUrl = serverStore.currentServer?.url || 'http://localhost:3000';
  const wsUrl = serverUrl.replace(/^http/, 'ws') + '/ws';
  
  console.log('[WS] Connecting to:', wsUrl);
  console.log('[WS] Token available:', token.slice(0, 20) + '...');
  
  try {
    ws = new WebSocket(wsUrl);
    
    ws.onopen = () => {
      console.log('[WS] Connected, sending auth...');
      if (ws) {
        ws.send(JSON.stringify({ type: WS_EVENTS.AUTH, payload: { token } }));
      }
    };
    
    ws.onmessage = (event) => {
      console.log('[WS] Raw message received:', event.data);
      try {
        const data = JSON.parse(event.data);
        console.log('[WS] Parsed message:', data);
        console.log('[WS] Message type:', data.type);
        handleWebSocketMessage(data);
        console.log('[WS] After handling, syncState:', JSON.stringify(syncState));
      } catch (e) {
        console.error('[WS] Error processing message:', e);
      }
    };
    
    ws.onclose = () => {
      console.log('[WS] Disconnected');
      // 5秒后尝试重连
      wsReconnectTimer = setTimeout(setupWebSocket, 5000);
    };
    
    ws.onerror = (e) => {
      console.error('[WS] Error:', e);
      ws?.close();
    };
  } catch (e) {
    console.error('[WS] Setup error:', e);
  }
}

function handleWebSocketMessage(data: { type?: string; payload?: Record<string, unknown> }) {
  console.log('[WS] Message received:', JSON.stringify(data));
  
  // 优先从 payload.event 获取事件类型，其次从 type 获取
  const event = (data.payload?.event as string) || data.type || '';
  console.log('[WS] Event:', event);
  
  // 清除超时定时器
  if (syncTimeoutTimer && (event === 'synced' || event === 'sync_failed')) {
    clearTimeout(syncTimeoutTimer);
    syncTimeoutTimer = null;
  }
  
  switch (event) {
    case 'sync_started':
      console.log('[WS] Sync started');
      syncState.progress = 5;
      syncState.step = 1;
      break;
    
    case 'sync_progress':
      if (data.payload) {
        const { current, total, progress } = data.payload as { current: number; total: number; progress: number };
        console.log(`[WS] Progress: ${current}/${total} (${progress}%)`);
        syncState.progress = Math.min(90, Math.round(progress * 0.9));
        if (current >= 1) syncState.step = 2;
        if (current > 1) syncState.step = 3;
      }
      break;
      
    case 'synced':
      console.log('[WS] Sync completed:', data.payload);
      stopSyncAnimation();
      syncState.progress = 100;
      syncState.step = 3;
      syncState.syncedCount = (data.payload?.syncedCount as number) || 0;
      syncState.accountsCount = (data.payload?.accountCount as number) || 0;
      syncState.status = syncState.syncedCount > 0 ? 'success' : 'empty';
      syncingComments.value = false;
      if (commentsWork.value) loadComments();
      break;
      
    case 'sync_failed':
      console.log('[WS] Sync failed:', data.payload);
      stopSyncAnimation();
      syncState.status = 'failed';
      syncState.error = (data.payload?.message as string) || '同步失败';
      syncingComments.value = false;
      break;
  }
}

// 超时处理：如果2分钟内没收到 WebSocket 消息，显示完成状态
function startSyncTimeout() {
  if (syncTimeoutTimer) {
    clearTimeout(syncTimeoutTimer);
  }
  syncTimeoutTimer = setTimeout(() => {
    if (syncState.status === 'syncing') {
      console.log('[Sync] Timeout, assuming completed');
      stopSyncAnimation();
      syncState.status = 'success';
      syncState.syncedCount = 0;
      syncingComments.value = false;
      ElMessage.info('同步已完成，请刷新页面查看结果');
    }
  }, 120000); // 2分钟超时
}

function cleanupWebSocket() {
  if (wsReconnectTimer) {
    clearTimeout(wsReconnectTimer);
    wsReconnectTimer = null;
  }
  if (syncTimeoutTimer) {
    clearTimeout(syncTimeoutTimer);
    syncTimeoutTimer = null;
  }
  if (ws) {
    ws.close();
    ws = null;
  }
}

async function syncAllComments() {
  if (!accounts.value.length) {
    ElMessage.warning('请先添加平台账号');
    return;
  }

  // 使用任务队列
  try {
    await request.post('/api/comments/sync');
    ElMessage.success('评论同步任务已创建，请在任务队列中查看进度');
    // 打开任务队列弹框
    taskStore.openDialog();
  } catch (error) {
    ElMessage.error((error as Error)?.message || '创建同步任务失败');
  }
}

function startSyncAnimation() {
  let dotCount = 0;
  syncTimer = setInterval(() => {
    dotCount = (dotCount + 1) % 4;
    syncDots.value = '.'.repeat(dotCount);
    
    // 只在没有收到 WebSocket 进度时才慢慢增加进度（作为备用）
    // 真实进度由 WebSocket 消息更新
    if (syncState.progress < 20 && syncState.step === 1) {
      // 连接平台阶段，缓慢增加
      syncState.progress += 1;
    }
  }, 500);
}

function stopSyncAnimation() {
  if (syncTimer) {
    clearInterval(syncTimer);
    syncTimer = null;
  }
  syncState.progress = 100;
  syncState.step = 3;
}

function closeSyncDialog() {
  showSyncDialog.value = false;
  stopSyncAnimation();
}

// #6072: 中断评论同步
function stopCommentSync() {
  stopSyncAnimation();
  if (syncTimeoutTimer) {
    clearTimeout(syncTimeoutTimer);
    syncTimeoutTimer = null;
  }
  syncState.status = 'failed';
  syncState.error = '用户手动中断同步';
  syncingComments.value = false;
  ElMessage.info('已中断评论同步');
}

function viewAllComments() {
  closeSyncDialog();
  commentsWork.value = null; // 不筛选特定作品
  commentsPagination.page = 1;
  showCommentsDrawer.value = true;
  loadComments();
}

function openWorkDetail(work: Work) {
  currentWork.value = work;
  showDetailDialog.value = true;
}

function viewComments(work: Work) {
  showDetailDialog.value = false;
  commentsWork.value = work;
  commentsPagination.page = 1;
  showCommentsDrawer.value = true;
  loadComments();
}

async function deletePlatformWork(work: Work) {
  try {
    await ElMessageBox.confirm(
      '确定要从平台删除该作品吗？此操作不可恢复！',
      '删除确认',
      { type: 'warning' }
    );
    
    showDetailDialog.value = false;
    
    // 调用删除平台作品 API
    await request.post(`/api/works/${work.id}/delete-platform`);
    ElMessage.success('删除任务已创建，请在任务队列中查看进度');
    taskStore.openDialog();
  } catch {
    // 取消或错误
  }
}

async function loadComments() {
  commentsLoading.value = true;
  try {
    const params: Record<string, unknown> = {
      page: commentsPagination.page,
      pageSize: commentsPagination.pageSize,
    };
    
    // 如果有选中的作品，按作品筛选；否则查询所有评论
    if (commentsWork.value) {
      params.workId = commentsWork.value.id;
    }
    
    const result = await request.get('/api/comments', { params });
    comments.value = result.items || [];
    commentsPagination.total = result.total || 0;
  } catch {
    comments.value = [];
  } finally {
    commentsLoading.value = false;
  }
}

function openReplyDialog(comment: Comment) {
  replyTarget.value = comment;
  replyContent.value = '';
  showReplyDialog.value = true;
}

async function handleReply() {
  if (!replyTarget.value || !replyContent.value.trim()) {
    ElMessage.warning('请输入回复内容');
    return;
  }
  
  replying.value = true;
  try {
    await request.post('/api/comments/reply', {
      commentId: replyTarget.value.id,
      content: replyContent.value,
    });
    ElMessage.success('回复成功');
    showReplyDialog.value = false;
    loadComments();
  } catch {
    // 错误已处理
  } finally {
    replying.value = false;
  }
}

onMounted(() => {
  loadAccounts();
  loadWorks();
  loadStats();
  // WebSocket 连接改为在需要时才建立（点击同步评论按钮时）
});

onUnmounted(() => {
  stopSyncAnimation();
  cleanupWebSocket();
});
</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-stats {
    display: flex;
    gap: 20px;
    color: $text-secondary;
  }
}

.filter-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 20px;
}

.works-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  min-height: 200px;
}

.work-card {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s;
  cursor: pointer;
  
  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
    transform: translateY(-2px);
  }
  
  .work-cover {
    position: relative;
    width: 100%;
    padding-top: 56.25%; // 16:9
    background: #f0f0f0;
    
    img {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
  
  .work-info {
    padding: 12px;
    
    .work-title {
      font-size: 14px;
      font-weight: 500;
      color: $text-primary;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      margin-bottom: 8px;
    }
    
    .work-meta {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 8px;
    }
    
    .work-stats {
      display: flex;
      gap: 12px;
      font-size: 12px;
      color: $text-secondary;
      
      span {
        display: flex;
        align-items: center;
        gap: 4px;
      }
    }
  }
  
  .work-actions {
    padding: 8px 12px;
    border-top: 1px solid $border-lighter;
    text-align: right;
  }
}

.empty-state {
  grid-column: 1 / -1;
  padding: 60px 0;
}

.work-detail {
  display: flex;
  gap: 24px;
  
  .detail-left {
    flex-shrink: 0;
    width: 300px;
    
    .detail-cover {
      width: 100%;
      border-radius: 8px;
      overflow: hidden;
      background: #f0f0f0;
      
      img {
        width: 100%;
        display: block;
      }
    }
  }
  
  .detail-right {
    flex: 1;
    
    .detail-row {
      display: flex;
      align-items: center;
      margin-bottom: 12px;
      
      label {
        width: 80px;
        color: $text-secondary;
      }
    }
    
    .detail-stats {
      display: flex;
      gap: 20px;
      margin: 20px 0;
      padding: 16px;
      background: $bg-base;
      border-radius: 8px;
      
      .stat-item {
        text-align: center;
        
        .stat-value {
          font-size: 20px;
          font-weight: 600;
          color: $primary-color;
        }
        
        .stat-label {
          font-size: 12px;
          color: $text-secondary;
          margin-top: 4px;
        }
      }
    }
    
    .detail-description {
      label {
        display: block;
        color: $text-secondary;
        margin-bottom: 8px;
      }
      
      p {
        margin: 0;
        color: $text-regular;
        line-height: 1.6;
      }
    }
  }
}

// 评论抽屉样式
.comments-drawer-header {
  display: flex;
  gap: 12px;
  
  .work-thumb {
    width: 80px;
    height: 45px;
    object-fit: cover;
    border-radius: 4px;
    background: #f0f0f0;
  }
  
  .work-brief {
    flex: 1;
    
    .work-brief-title {
      font-weight: 500;
      margin-bottom: 4px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .work-brief-meta {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 12px;
      color: $text-secondary;
    }
  }
}

.comments-list {
  min-height: 200px;
}

.empty-comments {
  padding: 40px 0;
}

.comment-item {
  display: flex;
  gap: 12px;
  padding: 12px 0;
  border-bottom: 1px solid $border-lighter;
  
  &:last-child {
    border-bottom: none;
  }
  
  .comment-body {
    flex: 1;
    min-width: 0;
    
    .comment-header {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 6px;
      
      .author-name {
        font-weight: 500;
        font-size: 14px;
      }
      
      .comment-time {
        font-size: 12px;
        color: $text-secondary;
      }
    }
    
    .comment-text {
      font-size: 14px;
      line-height: 1.5;
      color: $text-primary;
      word-break: break-word;
    }
    
    .comment-actions {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-top: 8px;
      
      .like-count {
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 12px;
        color: $text-secondary;
      }
    }
    
    .reply-box {
      margin-top: 8px;
      padding: 8px 12px;
      background: $bg-base;
      border-radius: 4px;
      font-size: 13px;
      color: $text-regular;
    }
  }
}

.comments-pagination {
  padding: 16px 0;
  display: flex;
  justify-content: center;
}

.reply-original {
  margin-bottom: 16px;
  padding: 12px;
  background: $bg-base;
  border-radius: 4px;
  
  p {
    margin: 8px 0 0;
  }
}

// 同步对话框样式
.sync-status {
  text-align: center;
  padding: 20px 0;
  
  .sync-animation {
    margin-bottom: 16px;
  }
  
  .sync-text {
    font-size: 18px;
    font-weight: 500;
    color: $text-primary;
    margin-bottom: 8px;
    
    &.success { color: #67c23a; }
    &.error { color: #f56c6c; }
    
    .sync-dots {
      display: inline-block;
      width: 24px;
      text-align: left;
    }
  }
  
  .sync-hint {
    font-size: 13px;
    color: $text-secondary;
    margin: 12px 0;
  }
  
  .sync-steps {
    display: flex;
    justify-content: center;
    gap: 24px;
    margin-top: 16px;
    
    span {
      font-size: 13px;
      color: $text-placeholder;
      position: relative;
      
      &.active {
        color: $primary-color;
        font-weight: 500;
      }
      
      &:not(:last-child)::after {
        content: '→';
        position: absolute;
        right: -16px;
        color: $text-placeholder;
      }
    }
  }
  
  .sync-result {
    margin-top: 16px;
    font-size: 14px;
    color: $text-regular;
    
    p {
      margin: 4px 0;
    }
    
    strong {
      color: $primary-color;
      font-size: 20px;
    }
  }
  
  .sync-error {
    margin-top: 12px;
    font-size: 13px;
    color: $text-secondary;
  }
}
</style>
