index.vue 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315
  1. <template>
  2. <div class="works-page">
  3. <div class="page-header">
  4. <h2>作品管理</h2>
  5. <div class="header-stats">
  6. <span>总作品: {{ stats.totalCount }}</span>
  7. <span>总播放: {{ formatNumber(stats.totalPlayCount) }}</span>
  8. <span>总点赞: {{ formatNumber(stats.totalLikeCount) }}</span>
  9. </div>
  10. </div>
  11. <!-- 筛选栏 -->
  12. <div class="page-card filter-bar">
  13. <el-select v-model="filter.accountId" placeholder="选择账号" clearable style="width: 200px">
  14. <el-option
  15. v-for="account in accounts"
  16. :key="account.id"
  17. :label="`${account.accountName} (${getPlatformName(account.platform)})`"
  18. :value="account.id"
  19. />
  20. </el-select>
  21. <el-select v-model="filter.platform" placeholder="平台" clearable style="width: 120px">
  22. <el-option
  23. v-for="platform in platforms"
  24. :key="platform.type"
  25. :label="platform.name"
  26. :value="platform.type"
  27. />
  28. </el-select>
  29. <el-select v-model="filter.status" placeholder="状态" clearable style="width: 120px">
  30. <el-option label="已发布" value="published" />
  31. <el-option label="审核中" value="reviewing" />
  32. <el-option label="未通过" value="rejected" />
  33. <el-option label="草稿" value="draft" />
  34. <el-option label="已删除" value="deleted" />
  35. </el-select>
  36. <el-input
  37. v-model="filter.keyword"
  38. placeholder="搜索作品标题"
  39. clearable
  40. style="width: 200px"
  41. @keyup.enter="loadWorks"
  42. />
  43. <el-button type="primary" @click="loadWorks">
  44. <el-icon><Search /></el-icon>
  45. 搜索
  46. </el-button>
  47. <el-button @click="refreshAllWorks" :loading="refreshing" v-if="!taskStore.runningSyncWorksTask">
  48. <el-icon><Refresh /></el-icon>
  49. 同步作品
  50. </el-button>
  51. <el-button type="danger" @click="stopSyncWorks" v-else>
  52. <el-icon><CircleCloseFilled /></el-icon>
  53. 停止同步
  54. </el-button>
  55. <el-button type="success" @click="syncAllComments" :loading="syncingComments">
  56. <el-icon><ChatDotSquare /></el-icon>
  57. 同步评论
  58. </el-button>
  59. </div>
  60. <!-- 作品列表 -->
  61. <div class="page-card">
  62. <div class="works-grid" v-loading="loading">
  63. <div v-if="works.length === 0 && !loading" class="empty-state">
  64. <el-empty description="暂无作品数据">
  65. <el-button type="primary" @click="refreshAllWorks">同步作品</el-button>
  66. </el-empty>
  67. </div>
  68. <div
  69. v-for="work in works"
  70. :key="work.id"
  71. class="work-card"
  72. @click="openWorkDetail(work)"
  73. >
  74. <div class="work-cover">
  75. <img :src="getWorkCoverSrc(work)" :alt="work.title" @error="handleImageError" />
  76. </div>
  77. <div class="work-info">
  78. <div class="work-title" :title="work.title">{{ work.title || '无标题' }}</div>
  79. <div class="work-meta">
  80. <el-tag size="small" type="info">{{ getPlatformName(work.platform) }}</el-tag>
  81. </div>
  82. <div class="work-stats">
  83. <span><el-icon><VideoPlay /></el-icon> {{ formatNumber(work.playCount) }}</span>
  84. <span><el-icon><Star /></el-icon> {{ formatNumber(work.likeCount) }}</span>
  85. <span><el-icon><ChatDotSquare /></el-icon> {{ work.commentCount }}</span>
  86. <span><el-icon><Share /></el-icon> {{ work.shareCount }}</span>
  87. </div>
  88. </div>
  89. <div class="work-actions">
  90. <el-button type="primary" link size="small" @click.stop="viewComments(work)">
  91. 查看评论 ({{ work.commentCount }})
  92. </el-button>
  93. </div>
  94. </div>
  95. </div>
  96. <el-pagination
  97. v-if="pagination.total > 0"
  98. v-model:current-page="pagination.page"
  99. :page-size="pagination.pageSize"
  100. :total="pagination.total"
  101. layout="total, prev, pager, next"
  102. style="margin-top: 20px"
  103. @current-change="loadWorks"
  104. />
  105. </div>
  106. <!-- 作品详情对话框 -->
  107. <el-dialog
  108. v-model="showDetailDialog"
  109. :title="currentWork?.title || '作品详情'"
  110. width="800px"
  111. destroy-on-close
  112. >
  113. <div class="work-detail" v-if="currentWork">
  114. <div class="detail-left">
  115. <div class="detail-cover">
  116. <img :src="currentWork.coverUrl" :alt="currentWork.title" />
  117. </div>
  118. </div>
  119. <div class="detail-right">
  120. <div class="detail-row">
  121. <label>平台:</label>
  122. <el-tag>{{ getPlatformName(currentWork.platform) }}</el-tag>
  123. </div>
  124. <div class="detail-row">
  125. <label>状态:</label>
  126. <el-tag :type="getStatusType(currentWork.status)">
  127. {{ getStatusText(currentWork.status) }}
  128. </el-tag>
  129. </div>
  130. <div class="detail-row">
  131. <label>发布时间:</label>
  132. <span>{{ formatDate(currentWork.publishTime) }}</span>
  133. </div>
  134. <div class="detail-row">
  135. <label>时长:</label>
  136. <span>{{ formatDuration(currentWork.duration) }}</span>
  137. </div>
  138. <div class="detail-stats">
  139. <div class="stat-item">
  140. <div class="stat-value">{{ formatNumber(currentWork.playCount) }}</div>
  141. <div class="stat-label">播放</div>
  142. </div>
  143. <div class="stat-item">
  144. <div class="stat-value">{{ formatNumber(currentWork.likeCount) }}</div>
  145. <div class="stat-label">点赞</div>
  146. </div>
  147. <div class="stat-item">
  148. <div class="stat-value">{{ currentWork.commentCount }}</div>
  149. <div class="stat-label">评论</div>
  150. </div>
  151. <div class="stat-item">
  152. <div class="stat-value">{{ currentWork.shareCount }}</div>
  153. <div class="stat-label">分享</div>
  154. </div>
  155. </div>
  156. <div class="detail-description" v-if="currentWork.description">
  157. <label>描述:</label>
  158. <p>{{ currentWork.description }}</p>
  159. </div>
  160. </div>
  161. </div>
  162. <template #footer>
  163. <el-button @click="showDetailDialog = false">关闭</el-button>
  164. <el-button type="primary" @click="viewComments(currentWork!)">
  165. 查看评论
  166. </el-button>
  167. <el-button
  168. type="danger"
  169. @click="deletePlatformWork(currentWork!)"
  170. v-if="currentWork?.platform === 'douyin' || currentWork?.platform === 'xiaohongshu'"
  171. >
  172. <el-icon><Delete /></el-icon>
  173. 删除平台作品
  174. </el-button>
  175. </template>
  176. </el-dialog>
  177. <!-- 评论抽屉 -->
  178. <el-drawer
  179. v-model="showCommentsDrawer"
  180. :title="commentsWork ? `评论 - ${commentsWork.title || '作品'}` : '所有评论'"
  181. size="500px"
  182. destroy-on-close
  183. >
  184. <div class="comments-drawer-header" v-if="commentsWork">
  185. <img :src="getWorkCoverSrc(commentsWork)" class="work-thumb" @error="handleImageError" />
  186. <div class="work-brief">
  187. <div class="work-brief-title">{{ commentsWork.title || '无标题' }}</div>
  188. <div class="work-brief-meta">
  189. <el-tag size="small">{{ getPlatformName(commentsWork.platform) }}</el-tag>
  190. <span>{{ commentsWork.commentCount }} 条评论</span>
  191. </div>
  192. </div>
  193. </div>
  194. <div class="comments-drawer-header" v-else>
  195. <div class="work-brief">
  196. <div class="work-brief-title">所有评论</div>
  197. <div class="work-brief-meta">
  198. <span>共 {{ commentsPagination.total }} 条评论</span>
  199. </div>
  200. </div>
  201. </div>
  202. <el-divider />
  203. <div class="comments-list" v-loading="commentsLoading">
  204. <div v-if="comments.length === 0 && !commentsLoading" class="empty-comments">
  205. <el-empty description="暂无评论" :image-size="80" />
  206. </div>
  207. <div v-for="comment in comments" :key="comment.id" class="comment-item">
  208. <el-avatar :size="36" :src="comment.authorAvatar || undefined">
  209. {{ comment.authorName?.[0] }}
  210. </el-avatar>
  211. <div class="comment-body">
  212. <div class="comment-header">
  213. <span class="author-name">{{ comment.authorName }}</span>
  214. <span class="comment-time">{{ formatDate(comment.commentTime) }}</span>
  215. </div>
  216. <div class="comment-text">{{ comment.content }}</div>
  217. <div class="comment-actions">
  218. <span class="like-count">
  219. <el-icon><Star /></el-icon> {{ comment.likeCount }}
  220. </span>
  221. <el-button
  222. v-if="!comment.replyContent"
  223. type="primary"
  224. link
  225. size="small"
  226. @click="openReplyDialog(comment)"
  227. >
  228. 回复
  229. </el-button>
  230. </div>
  231. <div v-if="comment.replyContent" class="reply-box">
  232. <strong>已回复:</strong>{{ comment.replyContent }}
  233. </div>
  234. </div>
  235. </div>
  236. </div>
  237. <div class="comments-pagination" v-if="commentsPagination.total > commentsPagination.pageSize">
  238. <el-pagination
  239. v-model:current-page="commentsPagination.page"
  240. :page-size="commentsPagination.pageSize"
  241. :total="commentsPagination.total"
  242. layout="prev, pager, next"
  243. small
  244. @change="loadComments"
  245. />
  246. </div>
  247. </el-drawer>
  248. <!-- 回复评论对话框 -->
  249. <el-dialog v-model="showReplyDialog" title="回复评论" width="500px">
  250. <div class="reply-original">
  251. <strong>原评论:</strong>
  252. <p>{{ replyTarget?.content }}</p>
  253. </div>
  254. <el-input
  255. v-model="replyContent"
  256. type="textarea"
  257. :rows="4"
  258. placeholder="输入回复内容"
  259. />
  260. <template #footer>
  261. <el-button @click="showReplyDialog = false">取消</el-button>
  262. <el-button type="primary" @click="handleReply" :loading="replying">
  263. 回复
  264. </el-button>
  265. </template>
  266. </el-dialog>
  267. <!-- 评论同步对话框 -->
  268. <el-dialog
  269. v-model="showSyncDialog"
  270. title="同步评论"
  271. width="450px"
  272. :close-on-click-modal="false"
  273. :close-on-press-escape="false"
  274. :show-close="syncState.status !== 'syncing'"
  275. >
  276. <div class="sync-status">
  277. <!-- 同步中 -->
  278. <template v-if="syncState.status === 'syncing'">
  279. <div class="sync-animation">
  280. <el-icon class="is-loading" :size="48" color="#409eff"><Loading /></el-icon>
  281. </div>
  282. <div class="sync-text">
  283. 正在同步评论<span class="sync-dots">{{ syncDots }}</span>
  284. </div>
  285. <el-progress
  286. :percentage="Math.floor(syncState.progress)"
  287. :stroke-width="8"
  288. style="margin: 16px 0"
  289. />
  290. <div class="sync-hint">
  291. 正在从平台获取评论数据,请耐心等待...
  292. </div>
  293. <div class="sync-steps">
  294. <span :class="{ active: syncState.step >= 1 }">连接平台</span>
  295. <span :class="{ active: syncState.step >= 2 }">获取作品</span>
  296. <span :class="{ active: syncState.step >= 3 }">提取评论</span>
  297. </div>
  298. </template>
  299. <!-- 同步成功 -->
  300. <template v-else-if="syncState.status === 'success'">
  301. <div class="sync-animation">
  302. <el-icon :size="48" color="#67c23a"><CircleCheckFilled /></el-icon>
  303. </div>
  304. <div class="sync-text success">同步完成</div>
  305. <div class="sync-result">
  306. <p>成功同步 <strong>{{ syncState.syncedCount }}</strong> 条评论</p>
  307. <p v-if="syncState.accountsCount">涉及 {{ syncState.accountsCount }} 个账号</p>
  308. </div>
  309. <el-button type="primary" link @click="viewAllComments" style="margin-top: 12px">
  310. 查看所有评论
  311. </el-button>
  312. </template>
  313. <!-- 同步失败 -->
  314. <template v-else-if="syncState.status === 'failed'">
  315. <div class="sync-animation">
  316. <el-icon :size="48" color="#f56c6c"><CircleCloseFilled /></el-icon>
  317. </div>
  318. <div class="sync-text error">同步失败</div>
  319. <div class="sync-error">{{ syncState.error }}</div>
  320. </template>
  321. <!-- 无评论 -->
  322. <template v-else-if="syncState.status === 'empty'">
  323. <div class="sync-animation">
  324. <el-icon :size="48" color="#909399"><WarningFilled /></el-icon>
  325. </div>
  326. <div class="sync-text">未获取到新评论</div>
  327. <div class="sync-hint">可能原因:平台暂无新评论,或 Cookie 已过期</div>
  328. </template>
  329. </div>
  330. <template #footer>
  331. <el-button v-if="syncState.status === 'syncing'" type="danger" @click="stopCommentSync">
  332. 中断同步
  333. </el-button>
  334. <el-button v-else type="primary" @click="closeSyncDialog">确定</el-button>
  335. </template>
  336. </el-dialog>
  337. </div>
  338. </template>
  339. <script setup lang="ts">
  340. import { ref, reactive, onMounted, onUnmounted, computed, watch } from 'vue';
  341. import { Search, Refresh, VideoPlay, Star, ChatDotSquare, Share, Loading, CircleCheckFilled, CircleCloseFilled, WarningFilled, Delete } from '@element-plus/icons-vue';
  342. import { ElMessageBox } from 'element-plus';
  343. import { ElMessage } from 'element-plus';
  344. import request from '@/api/request';
  345. import { accountsApi } from '@/api/accounts';
  346. import { PLATFORMS, AVAILABLE_PLATFORM_TYPES, WS_EVENTS } from '@media-manager/shared';
  347. import type { Work, WorkStats, PlatformAccount, PlatformType, Comment } from '@media-manager/shared';
  348. import { useServerStore } from '@/stores/server';
  349. import { useAuthStore } from '@/stores/auth';
  350. import { useTaskQueueStore } from '@/stores/taskQueue';
  351. import dayjs from 'dayjs';
  352. const serverStore = useServerStore();
  353. const authStore = useAuthStore();
  354. const taskStore = useTaskQueueStore();
  355. // 监听作品刷新信号,当 sync_works 任务完成时自动刷新作品列表
  356. watch(() => taskStore.worksRefreshTrigger, () => {
  357. console.log('[Works] worksRefreshTrigger changed, refreshing list...');
  358. loadWorks();
  359. loadStats();
  360. });
  361. const loading = ref(false);
  362. const refreshing = ref(false);
  363. const syncingComments = ref(false);
  364. const showDetailDialog = ref(false);
  365. const showCommentsDrawer = ref(false);
  366. const showReplyDialog = ref(false);
  367. const showSyncDialog = ref(false);
  368. const commentsLoading = ref(false);
  369. const replying = ref(false);
  370. // 评论同步状态
  371. const syncDots = ref('');
  372. const syncState = reactive({
  373. status: 'syncing' as 'syncing' | 'success' | 'failed' | 'empty',
  374. progress: 0,
  375. step: 1,
  376. syncedCount: 0,
  377. accountsCount: 0,
  378. error: '',
  379. });
  380. let syncTimer: ReturnType<typeof setInterval> | null = null;
  381. const works = ref<Work[]>([]);
  382. const accounts = ref<PlatformAccount[]>([]);
  383. const currentWork = ref<Work | null>(null);
  384. const commentsWork = ref<Work | null>(null);
  385. const comments = ref<Comment[]>([]);
  386. const replyTarget = ref<Comment | null>(null);
  387. const replyContent = ref('');
  388. const stats = ref<WorkStats>({
  389. totalCount: 0,
  390. publishedCount: 0,
  391. totalPlayCount: 0,
  392. totalLikeCount: 0,
  393. totalCommentCount: 0,
  394. });
  395. const commentsPagination = reactive({
  396. page: 1,
  397. pageSize: 15,
  398. total: 0,
  399. });
  400. // 平台选项(统一配置:小红书、抖音、视频号、百家号)
  401. const platforms = computed(() =>
  402. AVAILABLE_PLATFORM_TYPES.map(type => PLATFORMS[type])
  403. );
  404. const filter = reactive({
  405. accountId: undefined as number | undefined,
  406. platform: '' as PlatformType | '',
  407. status: '',
  408. keyword: '',
  409. });
  410. const pagination = reactive({
  411. page: 1,
  412. pageSize: 15,
  413. total: 0,
  414. });
  415. function getPlatformName(platform: PlatformType) {
  416. return PLATFORMS[platform]?.name || platform;
  417. }
  418. function getStatusType(status: string) {
  419. const map: Record<string, 'success' | 'warning' | 'danger' | 'info'> = {
  420. published: 'success',
  421. reviewing: 'warning',
  422. rejected: 'danger',
  423. draft: 'info',
  424. deleted: 'danger',
  425. failed: 'danger',
  426. processing: 'warning',
  427. pending: 'info',
  428. };
  429. return map[status] || 'info';
  430. }
  431. function getStatusText(status: string) {
  432. const map: Record<string, string> = {
  433. published: '已发布',
  434. reviewing: '审核中',
  435. rejected: '未通过',
  436. draft: '草稿',
  437. deleted: '已删除',
  438. failed: '失败',
  439. processing: '发布中',
  440. pending: '待发布',
  441. };
  442. return map[status] || status;
  443. }
  444. function formatDate(date: string) {
  445. if (!date) return '-';
  446. return dayjs(date).format('YYYY-MM-DD HH:mm');
  447. }
  448. function formatNumber(num: number) {
  449. if (num >= 10000) {
  450. return (num / 10000).toFixed(1) + '万';
  451. }
  452. return num?.toString() || '0';
  453. }
  454. // 格式化时长(秒转换为 时:分:秒 或 分:秒)
  455. function formatDuration(seconds: number | string | undefined): string {
  456. if (!seconds && seconds !== 0) return '-';
  457. const totalSeconds = typeof seconds === 'string' ? parseInt(seconds, 10) : seconds;
  458. if (isNaN(totalSeconds) || totalSeconds < 0) return '-';
  459. const hours = Math.floor(totalSeconds / 3600);
  460. const minutes = Math.floor((totalSeconds % 3600) / 60);
  461. const secs = totalSeconds % 60;
  462. if (hours > 0) {
  463. return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  464. }
  465. return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  466. }
  467. // 作品列表/评论等处的封面:兼容 coverUrl / cover_url,无封面时用占位图
  468. 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>';
  469. function getWorkCoverSrc(work: Work): string {
  470. const url = (work as { coverUrl?: string; cover_url?: string }).coverUrl ?? (work as { cover_url?: string }).cover_url ?? '';
  471. if (!url || typeof url !== 'string' || !url.trim()) return COVER_PLACEHOLDER;
  472. return getSecureCoverUrl(url);
  473. }
  474. // 将 HTTP 图片 URL 转换为 HTTPS(小红书等平台的图片 URL 可能是 HTTP)
  475. function getSecureCoverUrl(url: string): string {
  476. if (!url) return '';
  477. // 将 http:// 转换为 https://
  478. if (url.startsWith('http://')) {
  479. return url.replace('http://', 'https://');
  480. }
  481. return url;
  482. }
  483. function handleImageError(e: Event) {
  484. const img = e.target as HTMLImageElement;
  485. img.src = COVER_PLACEHOLDER;
  486. }
  487. async function loadWorks() {
  488. loading.value = true;
  489. try {
  490. const result = await request.get('/api/works', {
  491. params: {
  492. page: pagination.page,
  493. pageSize: pagination.pageSize,
  494. accountId: filter.accountId,
  495. platform: filter.platform || undefined,
  496. status: filter.status || undefined,
  497. keyword: filter.keyword || undefined,
  498. },
  499. }) as { items: Work[]; total: number };
  500. works.value = result?.items || [];
  501. pagination.total = result?.total || 0;
  502. } catch {
  503. works.value = [];
  504. } finally {
  505. loading.value = false;
  506. }
  507. // 修复 #6074:同步更新统计数据,避免快速切换筛选条件时 loadStats 结果与作品列表不一致
  508. await loadStats();
  509. }
  510. async function loadStats() {
  511. try {
  512. const params: Record<string, unknown> = {};
  513. if (filter.accountId) params.accountId = filter.accountId;
  514. if (filter.platform) params.platform = filter.platform;
  515. if (filter.status) params.status = filter.status;
  516. if (filter.keyword) params.keyword = filter.keyword;
  517. const result = await request.get('/api/works/stats', { params }) as WorkStats;
  518. if (result) {
  519. stats.value = result;
  520. }
  521. } catch {
  522. // 忽略错误
  523. }
  524. }
  525. async function loadAccounts() {
  526. try {
  527. accounts.value = await accountsApi.getAccounts();
  528. } catch {
  529. // 忽略错误
  530. }
  531. }
  532. async function refreshAllWorks() {
  533. if (!accounts.value.length) {
  534. ElMessage.warning('请先添加平台账号');
  535. return;
  536. }
  537. refreshing.value = true;
  538. try {
  539. // 根据筛选:选了账号只同步该账号;只选了平台则只同步该平台;都没选则同步所有
  540. const accountId = filter.accountId;
  541. const platform = filter.platform || undefined;
  542. const account = accountId ? accounts.value.find((a) => a.id === accountId) : undefined;
  543. const accountName = account ? `${account.accountName || '账号'} (${getPlatformName(account.platform as PlatformType)})` : undefined;
  544. const platformName = platform ? getPlatformName(platform) : undefined;
  545. await taskStore.syncWorks(accountId, accountName, platform, platformName);
  546. const msg = accountId
  547. ? '已创建同步任务,仅同步当前选中账号'
  548. : platform
  549. ? `已创建同步任务,仅同步「${platformName}」平台账号`
  550. : '已创建同步任务,将同步所有账号';
  551. ElMessage.success(msg);
  552. taskStore.openDialog();
  553. } catch (error) {
  554. ElMessage.error((error as Error)?.message || '创建同步任务失败');
  555. } finally {
  556. refreshing.value = false;
  557. }
  558. }
  559. // 停止正在运行的作品同步任务
  560. async function stopSyncWorks() {
  561. const task = taskStore.runningSyncWorksTask;
  562. if (!task) return;
  563. try {
  564. const ok = await taskStore.cancelTask(task.id);
  565. if (ok) {
  566. ElMessage.success('已发送取消请求,同步任务将停止');
  567. }
  568. } catch {
  569. ElMessage.error('取消同步任务失败');
  570. }
  571. }
  572. // WebSocket 连接用于接收同步结果
  573. let ws: WebSocket | null = null;
  574. let wsReconnectTimer: ReturnType<typeof setTimeout> | null = null;
  575. let syncTimeoutTimer: ReturnType<typeof setTimeout> | null = null;
  576. function setupWebSocket() {
  577. // 检查是否已连接
  578. if (ws && ws.readyState === WebSocket.OPEN) {
  579. console.log('[WS] Already connected');
  580. return;
  581. }
  582. // 检查 token 是否可用
  583. const token = authStore.accessToken;
  584. if (!token) {
  585. console.warn('[WS] No token available, cannot setup WebSocket');
  586. return;
  587. }
  588. const serverUrl = serverStore.currentServer?.url || 'http://localhost:3000';
  589. const wsUrl = serverUrl.replace(/^http/, 'ws') + '/ws';
  590. console.log('[WS] Connecting to:', wsUrl);
  591. console.log('[WS] Token available:', token.slice(0, 20) + '...');
  592. try {
  593. ws = new WebSocket(wsUrl);
  594. ws.onopen = () => {
  595. console.log('[WS] Connected, sending auth...');
  596. if (ws) {
  597. ws.send(JSON.stringify({ type: WS_EVENTS.AUTH, payload: { token } }));
  598. }
  599. };
  600. ws.onmessage = (event) => {
  601. console.log('[WS] Raw message received:', event.data);
  602. try {
  603. const data = JSON.parse(event.data);
  604. console.log('[WS] Parsed message:', data);
  605. console.log('[WS] Message type:', data.type);
  606. handleWebSocketMessage(data);
  607. console.log('[WS] After handling, syncState:', JSON.stringify(syncState));
  608. } catch (e) {
  609. console.error('[WS] Error processing message:', e);
  610. }
  611. };
  612. ws.onclose = () => {
  613. console.log('[WS] Disconnected');
  614. // 5秒后尝试重连
  615. wsReconnectTimer = setTimeout(setupWebSocket, 5000);
  616. };
  617. ws.onerror = (e) => {
  618. console.error('[WS] Error:', e);
  619. ws?.close();
  620. };
  621. } catch (e) {
  622. console.error('[WS] Setup error:', e);
  623. }
  624. }
  625. function handleWebSocketMessage(data: { type?: string; payload?: Record<string, unknown> }) {
  626. console.log('[WS] Message received:', JSON.stringify(data));
  627. // 优先从 payload.event 获取事件类型,其次从 type 获取
  628. const event = (data.payload?.event as string) || data.type || '';
  629. console.log('[WS] Event:', event);
  630. // 清除超时定时器
  631. if (syncTimeoutTimer && (event === 'synced' || event === 'sync_failed')) {
  632. clearTimeout(syncTimeoutTimer);
  633. syncTimeoutTimer = null;
  634. }
  635. switch (event) {
  636. case 'sync_started':
  637. console.log('[WS] Sync started');
  638. syncState.progress = 5;
  639. syncState.step = 1;
  640. break;
  641. case 'sync_progress':
  642. if (data.payload) {
  643. const { current, total, progress } = data.payload as { current: number; total: number; progress: number };
  644. console.log(`[WS] Progress: ${current}/${total} (${progress}%)`);
  645. syncState.progress = Math.min(90, Math.round(progress * 0.9));
  646. if (current >= 1) syncState.step = 2;
  647. if (current > 1) syncState.step = 3;
  648. }
  649. break;
  650. case 'synced':
  651. console.log('[WS] Sync completed:', data.payload);
  652. stopSyncAnimation();
  653. syncState.progress = 100;
  654. syncState.step = 3;
  655. syncState.syncedCount = (data.payload?.syncedCount as number) || 0;
  656. syncState.accountsCount = (data.payload?.accountCount as number) || 0;
  657. syncState.status = syncState.syncedCount > 0 ? 'success' : 'empty';
  658. syncingComments.value = false;
  659. if (commentsWork.value) loadComments();
  660. break;
  661. case 'sync_failed':
  662. console.log('[WS] Sync failed:', data.payload);
  663. stopSyncAnimation();
  664. syncState.status = 'failed';
  665. syncState.error = (data.payload?.message as string) || '同步失败';
  666. syncingComments.value = false;
  667. break;
  668. }
  669. }
  670. // 超时处理:如果2分钟内没收到 WebSocket 消息,显示完成状态
  671. function startSyncTimeout() {
  672. if (syncTimeoutTimer) {
  673. clearTimeout(syncTimeoutTimer);
  674. }
  675. syncTimeoutTimer = setTimeout(() => {
  676. if (syncState.status === 'syncing') {
  677. console.log('[Sync] Timeout, assuming completed');
  678. stopSyncAnimation();
  679. syncState.status = 'success';
  680. syncState.syncedCount = 0;
  681. syncingComments.value = false;
  682. ElMessage.info('同步已完成,请刷新页面查看结果');
  683. }
  684. }, 120000); // 2分钟超时
  685. }
  686. function cleanupWebSocket() {
  687. if (wsReconnectTimer) {
  688. clearTimeout(wsReconnectTimer);
  689. wsReconnectTimer = null;
  690. }
  691. if (syncTimeoutTimer) {
  692. clearTimeout(syncTimeoutTimer);
  693. syncTimeoutTimer = null;
  694. }
  695. if (ws) {
  696. ws.close();
  697. ws = null;
  698. }
  699. }
  700. async function syncAllComments() {
  701. if (!accounts.value.length) {
  702. ElMessage.warning('请先添加平台账号');
  703. return;
  704. }
  705. // 使用任务队列
  706. try {
  707. await request.post('/api/comments/sync');
  708. ElMessage.success('评论同步任务已创建,请在任务队列中查看进度');
  709. // 打开任务队列弹框
  710. taskStore.openDialog();
  711. } catch (error) {
  712. ElMessage.error((error as Error)?.message || '创建同步任务失败');
  713. }
  714. }
  715. function startSyncAnimation() {
  716. let dotCount = 0;
  717. syncTimer = setInterval(() => {
  718. dotCount = (dotCount + 1) % 4;
  719. syncDots.value = '.'.repeat(dotCount);
  720. // 只在没有收到 WebSocket 进度时才慢慢增加进度(作为备用)
  721. // 真实进度由 WebSocket 消息更新
  722. if (syncState.progress < 20 && syncState.step === 1) {
  723. // 连接平台阶段,缓慢增加
  724. syncState.progress += 1;
  725. }
  726. }, 500);
  727. }
  728. function stopSyncAnimation() {
  729. if (syncTimer) {
  730. clearInterval(syncTimer);
  731. syncTimer = null;
  732. }
  733. syncState.progress = 100;
  734. syncState.step = 3;
  735. }
  736. function closeSyncDialog() {
  737. showSyncDialog.value = false;
  738. stopSyncAnimation();
  739. }
  740. // #6072: 中断评论同步
  741. function stopCommentSync() {
  742. stopSyncAnimation();
  743. if (syncTimeoutTimer) {
  744. clearTimeout(syncTimeoutTimer);
  745. syncTimeoutTimer = null;
  746. }
  747. syncState.status = 'failed';
  748. syncState.error = '用户手动中断同步';
  749. syncingComments.value = false;
  750. ElMessage.info('已中断评论同步');
  751. }
  752. function viewAllComments() {
  753. closeSyncDialog();
  754. commentsWork.value = null; // 不筛选特定作品
  755. commentsPagination.page = 1;
  756. showCommentsDrawer.value = true;
  757. loadComments();
  758. }
  759. function openWorkDetail(work: Work) {
  760. currentWork.value = work;
  761. showDetailDialog.value = true;
  762. }
  763. function viewComments(work: Work) {
  764. showDetailDialog.value = false;
  765. commentsWork.value = work;
  766. commentsPagination.page = 1;
  767. showCommentsDrawer.value = true;
  768. loadComments();
  769. }
  770. async function deletePlatformWork(work: Work) {
  771. try {
  772. await ElMessageBox.confirm(
  773. '确定要从平台删除该作品吗?此操作不可恢复!',
  774. '删除确认',
  775. { type: 'warning' }
  776. );
  777. showDetailDialog.value = false;
  778. // 调用删除平台作品 API
  779. await request.post(`/api/works/${work.id}/delete-platform`);
  780. ElMessage.success('删除任务已创建,请在任务队列中查看进度');
  781. taskStore.openDialog();
  782. } catch {
  783. // 取消或错误
  784. }
  785. }
  786. async function loadComments() {
  787. commentsLoading.value = true;
  788. try {
  789. const params: Record<string, unknown> = {
  790. page: commentsPagination.page,
  791. pageSize: commentsPagination.pageSize,
  792. };
  793. // 如果有选中的作品,按作品筛选;否则查询所有评论
  794. if (commentsWork.value) {
  795. params.workId = commentsWork.value.id;
  796. }
  797. const result = await request.get('/api/comments', { params });
  798. comments.value = result.items || [];
  799. commentsPagination.total = result.total || 0;
  800. } catch {
  801. comments.value = [];
  802. } finally {
  803. commentsLoading.value = false;
  804. }
  805. }
  806. function openReplyDialog(comment: Comment) {
  807. replyTarget.value = comment;
  808. replyContent.value = '';
  809. showReplyDialog.value = true;
  810. }
  811. async function handleReply() {
  812. if (!replyTarget.value || !replyContent.value.trim()) {
  813. ElMessage.warning('请输入回复内容');
  814. return;
  815. }
  816. replying.value = true;
  817. try {
  818. await request.post('/api/comments/reply', {
  819. commentId: replyTarget.value.id,
  820. content: replyContent.value,
  821. });
  822. ElMessage.success('回复成功');
  823. showReplyDialog.value = false;
  824. loadComments();
  825. } catch {
  826. // 错误已处理
  827. } finally {
  828. replying.value = false;
  829. }
  830. }
  831. onMounted(() => {
  832. loadAccounts();
  833. loadWorks();
  834. loadStats();
  835. // WebSocket 连接改为在需要时才建立(点击同步评论按钮时)
  836. });
  837. onUnmounted(() => {
  838. stopSyncAnimation();
  839. cleanupWebSocket();
  840. });
  841. </script>
  842. <style lang="scss" scoped>
  843. @use '@/styles/variables.scss' as *;
  844. .page-header {
  845. display: flex;
  846. align-items: center;
  847. justify-content: space-between;
  848. margin-bottom: 20px;
  849. h2 { margin: 0; }
  850. .header-stats {
  851. display: flex;
  852. gap: 20px;
  853. color: $text-secondary;
  854. }
  855. }
  856. .filter-bar {
  857. display: flex;
  858. flex-wrap: wrap;
  859. gap: 12px;
  860. margin-bottom: 20px;
  861. }
  862. .works-grid {
  863. display: grid;
  864. grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  865. gap: 20px;
  866. min-height: 200px;
  867. }
  868. .work-card {
  869. background: #fff;
  870. border-radius: 8px;
  871. overflow: hidden;
  872. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  873. transition: all 0.3s;
  874. cursor: pointer;
  875. &:hover {
  876. box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  877. transform: translateY(-2px);
  878. }
  879. .work-cover {
  880. position: relative;
  881. width: 100%;
  882. padding-top: 56.25%; // 16:9
  883. background: #f0f0f0;
  884. img {
  885. position: absolute;
  886. top: 0;
  887. left: 0;
  888. width: 100%;
  889. height: 100%;
  890. object-fit: cover;
  891. }
  892. }
  893. .work-info {
  894. padding: 12px;
  895. .work-title {
  896. font-size: 14px;
  897. font-weight: 500;
  898. color: $text-primary;
  899. overflow: hidden;
  900. text-overflow: ellipsis;
  901. white-space: nowrap;
  902. margin-bottom: 8px;
  903. }
  904. .work-meta {
  905. display: flex;
  906. align-items: center;
  907. gap: 8px;
  908. margin-bottom: 8px;
  909. }
  910. .work-stats {
  911. display: flex;
  912. gap: 12px;
  913. font-size: 12px;
  914. color: $text-secondary;
  915. span {
  916. display: flex;
  917. align-items: center;
  918. gap: 4px;
  919. }
  920. }
  921. }
  922. .work-actions {
  923. padding: 8px 12px;
  924. border-top: 1px solid $border-lighter;
  925. text-align: right;
  926. }
  927. }
  928. .empty-state {
  929. grid-column: 1 / -1;
  930. padding: 60px 0;
  931. }
  932. .work-detail {
  933. display: flex;
  934. gap: 24px;
  935. .detail-left {
  936. flex-shrink: 0;
  937. width: 300px;
  938. .detail-cover {
  939. width: 100%;
  940. border-radius: 8px;
  941. overflow: hidden;
  942. background: #f0f0f0;
  943. img {
  944. width: 100%;
  945. display: block;
  946. }
  947. }
  948. }
  949. .detail-right {
  950. flex: 1;
  951. .detail-row {
  952. display: flex;
  953. align-items: center;
  954. margin-bottom: 12px;
  955. label {
  956. width: 80px;
  957. color: $text-secondary;
  958. }
  959. }
  960. .detail-stats {
  961. display: flex;
  962. gap: 20px;
  963. margin: 20px 0;
  964. padding: 16px;
  965. background: $bg-base;
  966. border-radius: 8px;
  967. .stat-item {
  968. text-align: center;
  969. .stat-value {
  970. font-size: 20px;
  971. font-weight: 600;
  972. color: $primary-color;
  973. }
  974. .stat-label {
  975. font-size: 12px;
  976. color: $text-secondary;
  977. margin-top: 4px;
  978. }
  979. }
  980. }
  981. .detail-description {
  982. label {
  983. display: block;
  984. color: $text-secondary;
  985. margin-bottom: 8px;
  986. }
  987. p {
  988. margin: 0;
  989. color: $text-regular;
  990. line-height: 1.6;
  991. }
  992. }
  993. }
  994. }
  995. // 评论抽屉样式
  996. .comments-drawer-header {
  997. display: flex;
  998. gap: 12px;
  999. .work-thumb {
  1000. width: 80px;
  1001. height: 45px;
  1002. object-fit: cover;
  1003. border-radius: 4px;
  1004. background: #f0f0f0;
  1005. }
  1006. .work-brief {
  1007. flex: 1;
  1008. .work-brief-title {
  1009. font-weight: 500;
  1010. margin-bottom: 4px;
  1011. overflow: hidden;
  1012. text-overflow: ellipsis;
  1013. white-space: nowrap;
  1014. }
  1015. .work-brief-meta {
  1016. display: flex;
  1017. align-items: center;
  1018. gap: 8px;
  1019. font-size: 12px;
  1020. color: $text-secondary;
  1021. }
  1022. }
  1023. }
  1024. .comments-list {
  1025. min-height: 200px;
  1026. }
  1027. .empty-comments {
  1028. padding: 40px 0;
  1029. }
  1030. .comment-item {
  1031. display: flex;
  1032. gap: 12px;
  1033. padding: 12px 0;
  1034. border-bottom: 1px solid $border-lighter;
  1035. &:last-child {
  1036. border-bottom: none;
  1037. }
  1038. .comment-body {
  1039. flex: 1;
  1040. min-width: 0;
  1041. .comment-header {
  1042. display: flex;
  1043. align-items: center;
  1044. gap: 8px;
  1045. margin-bottom: 6px;
  1046. .author-name {
  1047. font-weight: 500;
  1048. font-size: 14px;
  1049. }
  1050. .comment-time {
  1051. font-size: 12px;
  1052. color: $text-secondary;
  1053. }
  1054. }
  1055. .comment-text {
  1056. font-size: 14px;
  1057. line-height: 1.5;
  1058. color: $text-primary;
  1059. word-break: break-word;
  1060. }
  1061. .comment-actions {
  1062. display: flex;
  1063. align-items: center;
  1064. gap: 12px;
  1065. margin-top: 8px;
  1066. .like-count {
  1067. display: flex;
  1068. align-items: center;
  1069. gap: 4px;
  1070. font-size: 12px;
  1071. color: $text-secondary;
  1072. }
  1073. }
  1074. .reply-box {
  1075. margin-top: 8px;
  1076. padding: 8px 12px;
  1077. background: $bg-base;
  1078. border-radius: 4px;
  1079. font-size: 13px;
  1080. color: $text-regular;
  1081. }
  1082. }
  1083. }
  1084. .comments-pagination {
  1085. padding: 16px 0;
  1086. display: flex;
  1087. justify-content: center;
  1088. }
  1089. .reply-original {
  1090. margin-bottom: 16px;
  1091. padding: 12px;
  1092. background: $bg-base;
  1093. border-radius: 4px;
  1094. p {
  1095. margin: 8px 0 0;
  1096. }
  1097. }
  1098. // 同步对话框样式
  1099. .sync-status {
  1100. text-align: center;
  1101. padding: 20px 0;
  1102. .sync-animation {
  1103. margin-bottom: 16px;
  1104. }
  1105. .sync-text {
  1106. font-size: 18px;
  1107. font-weight: 500;
  1108. color: $text-primary;
  1109. margin-bottom: 8px;
  1110. &.success { color: #67c23a; }
  1111. &.error { color: #f56c6c; }
  1112. .sync-dots {
  1113. display: inline-block;
  1114. width: 24px;
  1115. text-align: left;
  1116. }
  1117. }
  1118. .sync-hint {
  1119. font-size: 13px;
  1120. color: $text-secondary;
  1121. margin: 12px 0;
  1122. }
  1123. .sync-steps {
  1124. display: flex;
  1125. justify-content: center;
  1126. gap: 24px;
  1127. margin-top: 16px;
  1128. span {
  1129. font-size: 13px;
  1130. color: $text-placeholder;
  1131. position: relative;
  1132. &.active {
  1133. color: $primary-color;
  1134. font-weight: 500;
  1135. }
  1136. &:not(:last-child)::after {
  1137. content: '→';
  1138. position: absolute;
  1139. right: -16px;
  1140. color: $text-placeholder;
  1141. }
  1142. }
  1143. }
  1144. .sync-result {
  1145. margin-top: 16px;
  1146. font-size: 14px;
  1147. color: $text-regular;
  1148. p {
  1149. margin: 4px 0;
  1150. }
  1151. strong {
  1152. color: $primary-color;
  1153. font-size: 20px;
  1154. }
  1155. }
  1156. .sync-error {
  1157. margin-top: 12px;
  1158. font-size: 13px;
  1159. color: $text-secondary;
  1160. }
  1161. }
  1162. </style>