index.vue 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553
  1. <template>
  2. <div class="work-analytics">
  3. <!-- 顶部筛选栏 -->
  4. <div class="filter-bar">
  5. <div class="filter-left">
  6. <span class="filter-label">开始时间</span>
  7. <el-date-picker
  8. v-model="startDate"
  9. type="date"
  10. placeholder="选择日期"
  11. format="YYYY-MM-DD"
  12. value-format="YYYY-MM-DD"
  13. style="width: 140px"
  14. :disabled-date="(date: Date) => endDate ? date > new Date(endDate) : false"
  15. @change="handleFilterChange"
  16. />
  17. <span class="filter-label">结束时间</span>
  18. <el-date-picker
  19. v-model="endDate"
  20. type="date"
  21. placeholder="选择日期"
  22. format="YYYY-MM-DD"
  23. value-format="YYYY-MM-DD"
  24. style="width: 140px"
  25. :disabled-date="(date: Date) => startDate ? date < new Date(startDate) : false"
  26. @change="handleFilterChange"
  27. />
  28. <div class="quick-btns">
  29. <el-button
  30. v-for="btn in quickDateBtns"
  31. :key="btn.value"
  32. :type="activeQuickBtn === btn.value ? 'primary' : 'default'"
  33. size="small"
  34. @click="handleQuickDate(btn.value)"
  35. >
  36. {{ btn.label }}
  37. </el-button>
  38. </div>
  39. <el-select
  40. v-model="selectedAccounts"
  41. multiple
  42. collapse-tags
  43. collapse-tags-tooltip
  44. placeholder="选择账号"
  45. style="width: 200px"
  46. @change="handleFilterChange"
  47. >
  48. <el-option
  49. v-for="account in accountList"
  50. :key="account.id"
  51. :label="`${account.nickname} (${getPlatformName(account.platform)})`"
  52. :value="account.id"
  53. />
  54. </el-select>
  55. </div>
  56. <div class="filter-right">
  57. <el-button @click="handleExport">导出数据</el-button>
  58. </div>
  59. </div>
  60. <!-- 统计卡片 -->
  61. <div class="stats-row">
  62. <div class="stat-card" v-for="(item, index) in summaryStats" :key="index">
  63. <div class="stat-icon">
  64. <el-icon :size="18"><component :is="item.icon" /></el-icon>
  65. </div>
  66. <div class="stat-info">
  67. <div class="stat-label">{{ item.label }}</div>
  68. <div class="stat-value">{{ item.value }}</div>
  69. </div>
  70. </div>
  71. </div>
  72. <!-- 第二行筛选 -->
  73. <div class="filter-bar secondary">
  74. <div class="filter-left">
  75. <el-select v-model="selectedGroup" placeholder="全部" clearable style="width: 120px" @change="handleFilterChange">
  76. <el-option label="全部" value="" />
  77. <el-option
  78. v-for="group in accountGroups"
  79. :key="group.id"
  80. :label="group.name"
  81. :value="group.id"
  82. />
  83. </el-select>
  84. <el-select v-model="selectedPlatform" placeholder="全部平台" clearable style="width: 120px" @change="handleFilterChange">
  85. <el-option label="全部平台" value="" />
  86. <el-option
  87. v-for="platform in availablePlatforms"
  88. :key="platform.value"
  89. :label="platform.label"
  90. :value="platform.value"
  91. />
  92. </el-select>
  93. <el-select v-model="sortBy" style="width: 200px" @change="handleFilterChange">
  94. <el-option label="按发布时间倒序排列" value="publish_desc" />
  95. <el-option label="按播放量倒序排列" value="views_desc" />
  96. </el-select>
  97. <el-input
  98. v-model="searchKeyword"
  99. placeholder="请输入要搜索的作品标题"
  100. clearable
  101. style="width: 240px"
  102. @input="handleSearchInput"
  103. @clear="handleFilterChange"
  104. @keyup.enter="handleFilterChange"
  105. >
  106. <template #prefix>
  107. <el-icon><Search /></el-icon>
  108. </template>
  109. </el-input>
  110. </div>
  111. </div>
  112. <!-- 数据表格 -->
  113. <div class="data-table">
  114. <el-table :data="workList" v-loading="loading" stripe>
  115. <el-table-column label="账号" width="150">
  116. <template #default="{ row }">
  117. <div class="account-cell">
  118. <el-avatar :size="32" :src="row.accountAvatar">
  119. {{ row.accountName?.[0] }}
  120. </el-avatar>
  121. <span class="account-name">{{ row.accountName }}</span>
  122. </div>
  123. </template>
  124. </el-table-column>
  125. <el-table-column label="平台" width="100" align="center">
  126. <template #default="{ row }">
  127. <el-tag size="small" :type="getPlatformTagType(row.platform)">
  128. {{ getPlatformName(row.platform) }}
  129. </el-tag>
  130. </template>
  131. </el-table-column>
  132. <el-table-column label="标题" min-width="300">
  133. <template #default="{ row }">
  134. <div class="title-cell">
  135. <div class="work-title">{{ row.title }}</div>
  136. <div class="work-stats">
  137. <!-- 推荐暂不展示
  138. <span class="stat-item">推荐 <em>{{ row.recommendCount ?? '--' }}</em></span>
  139. -->
  140. <span class="stat-item">播放 <em>{{ row.viewsCount ?? 0 }}</em></span>
  141. <span class="stat-item">评论 <em>{{ row.commentsCount ?? 0 }}</em></span>
  142. <span class="stat-item">分享 <em>{{ row.sharesCount ?? 0 }}</em></span>
  143. <span class="stat-item">收藏 <em>{{ row.collectsCount ?? 0 }}</em></span>
  144. <span class="stat-item">点赞 <em>{{ row.likesCount ?? 0 }}</em></span>
  145. </div>
  146. </div>
  147. </template>
  148. </el-table-column>
  149. <!-- 类型列暂时不展示
  150. <el-table-column prop="workType" label="类型" width="80" align="center">
  151. <template #default="{ row }">
  152. <span>{{ row.workType || '动态' }}</span>
  153. </template>
  154. </el-table-column>
  155. -->
  156. <el-table-column prop="publishTime" label="发布时间" width="160" align="center">
  157. <template #default="{ row }">
  158. <span class="publish-time">{{ formatTime(row.publishTime) }}</span>
  159. </template>
  160. </el-table-column>
  161. <el-table-column label="操作" width="100" align="center" fixed="right">
  162. <template #default="{ row }">
  163. <el-button type="primary" link @click="handleView(row)">
  164. 查看
  165. </el-button>
  166. </template>
  167. </el-table-column>
  168. </el-table>
  169. <!-- 分页 -->
  170. <div class="pagination-wrapper">
  171. <el-pagination
  172. v-model:current-page="currentPage"
  173. :page-size="pageSize"
  174. :total="totalWorks"
  175. layout="total, prev, pager, next"
  176. @current-change="handleQuery"
  177. />
  178. </div>
  179. </div>
  180. <!-- 作品详情弹窗 -->
  181. <el-dialog
  182. v-model="drawerVisible"
  183. title="作品详情"
  184. width="80%"
  185. :close-on-click-modal="false"
  186. destroy-on-close
  187. class="work-detail-dialog"
  188. >
  189. <div v-if="selectedWork" class="work-detail">
  190. <!-- 标题和发布时间 -->
  191. <div class="detail-header">
  192. <h3 class="work-title">{{ selectedWork.title }}</h3>
  193. <div class="publish-time">{{ formatTime(selectedWork.publishTime) }}</div>
  194. </div>
  195. <!-- 标签页 -->
  196. <el-tabs v-model="activeTab" class="detail-tabs">
  197. <!-- 核心数据标签页 -->
  198. <el-tab-pane label="核心数据" name="core">
  199. <div class="core-data-content">
  200. <!-- 流量数据卡片 -->
  201. <div class="traffic-data">
  202. <div class="section-title-row">
  203. <h4 class="section-title">流量数据</h4>
  204. </div>
  205. <div class="data-cards">
  206. <!-- 小红书:指标更多 + 支持点选联动趋势图 -->
  207. <template v-if="selectedWork.platform === 'xiaohongshu'">
  208. <div
  209. v-for="item in xhsMetricCards"
  210. :key="item.key"
  211. class="data-card"
  212. :class="{ highlight: activeTrendMetric === item.key }"
  213. role="button"
  214. tabindex="0"
  215. @click="setTrendMetric(item.key)"
  216. @keyup.enter="setTrendMetric(item.key)"
  217. >
  218. <div class="card-label">{{ item.label }}</div>
  219. <div class="card-value">{{ item.value }}</div>
  220. </div>
  221. </template>
  222. <!-- 抖音:按小红书样式展示可用字段 -->
  223. <template v-else-if="selectedWork.platform === 'douyin'">
  224. <div
  225. v-for="item in douyinMetricCards"
  226. :key="item.label"
  227. class="data-card"
  228. :class="{ highlight: item.key && activeTrendMetric === item.key }"
  229. role="button"
  230. tabindex="0"
  231. @click="item.key && setTrendMetric(item.key)"
  232. @keyup.enter="item.key && setTrendMetric(item.key)"
  233. >
  234. <div class="card-label">{{ item.label }}</div>
  235. <div class="card-value">{{ item.value }}</div>
  236. </div>
  237. </template>
  238. <!-- 视频号:播放、点赞、评论、分享、收藏、关注数、涨粉量、平均观看时长、完播率、2s退出率 -->
  239. <template v-else-if="selectedWork.platform === 'weixin_video'">
  240. <div
  241. v-for="item in weixinMetricCards"
  242. :key="item.label"
  243. class="data-card"
  244. :class="{ highlight: item.key && activeTrendMetric === item.key }"
  245. role="button"
  246. tabindex="0"
  247. @click="item.key && setTrendMetric(item.key)"
  248. @keyup.enter="item.key && setTrendMetric(item.key)"
  249. >
  250. <div class="card-label">{{ item.label }}</div>
  251. <div class="card-value">{{ item.value }}</div>
  252. </div>
  253. </template>
  254. <!-- 百家号:推荐量、播放(阅读)量、评论量、点赞量、收藏量、分享量、完播率、涨粉量 -->
  255. <template v-else-if="selectedWork.platform === 'baijiahao'">
  256. <div
  257. v-for="item in baijiahaoMetricCards"
  258. :key="item.key || item.label"
  259. class="data-card"
  260. :class="{ highlight: item.key && activeTrendMetric === item.key }"
  261. role="button"
  262. tabindex="0"
  263. @click="item.key && setTrendMetric(item.key)"
  264. @keyup.enter="item.key && setTrendMetric(item.key)"
  265. >
  266. <div class="card-label">{{ item.label }}</div>
  267. <div class="card-value">{{ item.value }}</div>
  268. </div>
  269. </template>
  270. <!-- 其他平台:保持原口径 -->
  271. <template v-else>
  272. <div
  273. class="data-card highlight"
  274. role="button"
  275. tabindex="0"
  276. @click="setTrendMetric('playCount')"
  277. @keyup.enter="setTrendMetric('playCount')"
  278. >
  279. <div class="card-label">播放量</div>
  280. <div class="card-value">{{ formatNumber(workDetailData.playCount || 0) }}</div>
  281. </div>
  282. <div
  283. class="data-card"
  284. role="button"
  285. tabindex="0"
  286. @click="setTrendMetric('totalWatchDuration')"
  287. @keyup.enter="setTrendMetric('totalWatchDuration')"
  288. >
  289. <div class="card-label">播放总时长</div>
  290. <div class="card-value">{{ workDetailData.totalWatchDuration || '0秒' }}</div>
  291. </div>
  292. <div
  293. class="data-card"
  294. role="button"
  295. tabindex="0"
  296. @click="setTrendMetric('likeCount')"
  297. @keyup.enter="setTrendMetric('likeCount')"
  298. >
  299. <div class="card-label">点赞量</div>
  300. <div class="card-value">{{ formatNumber(workDetailData.likeCount || 0) }}</div>
  301. </div>
  302. <div
  303. class="data-card"
  304. role="button"
  305. tabindex="0"
  306. @click="setTrendMetric('commentCount')"
  307. @keyup.enter="setTrendMetric('commentCount')"
  308. >
  309. <div class="card-label">评论量</div>
  310. <div class="card-value">{{ formatNumber(workDetailData.commentCount || 0) }}</div>
  311. </div>
  312. <div
  313. class="data-card"
  314. role="button"
  315. tabindex="0"
  316. @click="setTrendMetric('collectCount')"
  317. @keyup.enter="setTrendMetric('collectCount')"
  318. >
  319. <div class="card-label">收藏量</div>
  320. <div class="card-value">{{ formatNumber(workDetailData.collectCount || 0) }}</div>
  321. </div>
  322. <div
  323. class="data-card"
  324. role="button"
  325. tabindex="0"
  326. @click="setTrendMetric('shareCount')"
  327. @keyup.enter="setTrendMetric('shareCount')"
  328. >
  329. <div class="card-label">分享量</div>
  330. <div class="card-value">{{ formatNumber(workDetailData.shareCount || 0) }}</div>
  331. </div>
  332. <div
  333. class="data-card"
  334. role="button"
  335. tabindex="0"
  336. @click="setTrendMetric('fansIncrease')"
  337. @keyup.enter="setTrendMetric('fansIncrease')"
  338. >
  339. <div class="card-label">涨粉量</div>
  340. <div class="card-value">{{ formatNumber(workDetailData.fansIncrease || 0) }}</div>
  341. </div>
  342. </template>
  343. </div>
  344. </div>
  345. <!-- 播放量趋势 -->
  346. <div class="trend-section">
  347. <h4 class="section-title">{{ trendTitle }}</h4>
  348. <div ref="playTrendChartRef" style="height: 300px" v-loading="detailLoading"></div>
  349. </div>
  350. </div>
  351. </el-tab-pane>
  352. </el-tabs>
  353. </div>
  354. </el-dialog>
  355. </div>
  356. </template>
  357. <script setup lang="ts">
  358. import { ref, computed, onMounted, watch, nextTick } from 'vue';
  359. import { Search, Picture, Document, View, ChatDotRound, Share, Star, Pointer } from '@element-plus/icons-vue';
  360. import { PLATFORMS, AVAILABLE_PLATFORM_TYPES } from '@media-manager/shared';
  361. import type { PlatformType } from '@media-manager/shared';
  362. import { useAuthStore } from '@/stores/auth';
  363. import { useServerStore } from '@/stores/server';
  364. import { ElMessage } from 'element-plus';
  365. import dayjs from 'dayjs';
  366. import request from '@/api/request';
  367. import * as echarts from 'echarts';
  368. const authStore = useAuthStore();
  369. const serverStore = useServerStore();
  370. const loading = ref(false);
  371. // 日期筛选
  372. const startDate = ref(dayjs().subtract(30, 'day').format('YYYY-MM-DD'));
  373. const endDate = ref(dayjs().format('YYYY-MM-DD'));
  374. const activeQuickBtn = ref('lastMonth');
  375. // 快捷日期按钮
  376. const quickDateBtns = [
  377. { label: '近三天', value: 'last3days' },
  378. { label: '近七天', value: 'last7days' },
  379. { label: '近一个月', value: 'lastMonth' },
  380. ];
  381. // 账号选择(带平台信息,便于同名账号区分)
  382. const selectedAccounts = ref<number[]>([]);
  383. const accountList = ref<{ id: number; nickname: string; platform: PlatformType }[]>([]);
  384. // 分组和平台筛选
  385. const selectedGroup = ref<number | ''>('');
  386. const selectedPlatform = ref<PlatformType | ''>('');
  387. const sortBy = ref('publish_desc');
  388. const searchKeyword = ref('');
  389. // 分组列表
  390. interface AccountGroup {
  391. id: number;
  392. name: string;
  393. }
  394. const accountGroups = ref<AccountGroup[]>([]);
  395. // 可用平台(统一配置:小红书、抖音、视频号、百家号)
  396. const availablePlatforms = computed(() => {
  397. return AVAILABLE_PLATFORM_TYPES.map(key => ({
  398. value: key,
  399. label: PLATFORMS[key].name,
  400. }));
  401. });
  402. // 分页
  403. const currentPage = ref(1);
  404. // 默认每页 15 条
  405. const pageSize = ref(15);
  406. const totalWorks = ref(0);
  407. // 汇总统计
  408. const summaryData = ref({
  409. totalWorks: 0,
  410. recommendCount: 0,
  411. viewsCount: 0,
  412. commentsCount: 0,
  413. sharesCount: 0,
  414. collectsCount: 0,
  415. likesCount: 0,
  416. });
  417. // 统计卡片数据
  418. const summaryStats = computed(() => [
  419. { label: '作品总数', value: summaryData.value.totalWorks, icon: Document },
  420. // { label: '推荐量', value: summaryData.value.recommendCount, icon: Pointer },
  421. { label: '播放(阅读)量', value: summaryData.value.viewsCount, icon: View },
  422. { label: '评论量', value: summaryData.value.commentsCount, icon: ChatDotRound },
  423. { label: '分享量', value: summaryData.value.sharesCount, icon: Share },
  424. { label: '收藏量', value: summaryData.value.collectsCount, icon: Star },
  425. { label: '点赞量', value: summaryData.value.likesCount, icon: Pointer },
  426. ]);
  427. // 作品数据
  428. interface WorkData {
  429. id: number;
  430. title: string;
  431. coverUrl: string;
  432. content: string;
  433. platform: PlatformType;
  434. accountId: number;
  435. accountName: string;
  436. accountAvatar: string;
  437. workType: string;
  438. publishTime: string;
  439. recommendCount: number | null;
  440. viewsCount: number;
  441. commentsCount: number;
  442. sharesCount: number;
  443. collectsCount: number;
  444. likesCount: number;
  445. }
  446. const workList = ref<WorkData[]>([]);
  447. // 详情弹窗相关
  448. const drawerVisible = ref(false);
  449. const selectedWork = ref<WorkData | null>(null);
  450. // 作品基础信息(来自 works 表 /api/works/:id)
  451. const selectedWorkBase = ref<any | null>(null);
  452. const activeTab = ref('core');
  453. const detailLoading = ref(false);
  454. // 作品详情数据
  455. interface WorkDetailData {
  456. playCount: number;
  457. exposureCount: number;
  458. totalWatchDuration: string;
  459. likeCount: number;
  460. commentCount: number;
  461. collectCount: number;
  462. shareCount: number;
  463. fansIncrease: number;
  464. followCount: number; // 视频号:关注数
  465. recommendCount: number; // 百家号等:推荐量
  466. coverClickRate: string;
  467. avgWatchDuration: string;
  468. completionRate: string;
  469. twoSecondExitRate: string;
  470. // 抖音:5s 完播率(仅昨日快照,无趋势)
  471. completionRate5s: string;
  472. }
  473. const workDetailData = ref<WorkDetailData>({
  474. playCount: 0,
  475. exposureCount: 0,
  476. totalWatchDuration: '0秒',
  477. likeCount: 0,
  478. commentCount: 0,
  479. collectCount: 0,
  480. shareCount: 0,
  481. fansIncrease: 0,
  482. followCount: 0,
  483. recommendCount: 0,
  484. coverClickRate: '0',
  485. avgWatchDuration: '0',
  486. completionRate: '0',
  487. twoSecondExitRate: '0',
  488. completionRate5s: '0',
  489. });
  490. // 播放量趋势图
  491. const playTrendChartRef = ref<HTMLElement>();
  492. let playTrendChart: echarts.ECharts | null = null;
  493. type TrendMetricKey =
  494. | 'exposureCount'
  495. | 'playCount'
  496. | 'likeCount'
  497. | 'commentCount'
  498. | 'collectCount'
  499. | 'shareCount'
  500. | 'coverClickRate'
  501. | 'avgWatchDuration'
  502. | 'completionRate'
  503. | 'twoSecondExitRate'
  504. | 'fansIncrease'
  505. | 'followCount'
  506. | 'totalWatchDuration';
  507. const activeTrendMetric = ref<TrendMetricKey>('playCount');
  508. const workStatsHistory = ref<any[]>([]);
  509. function toIntSafe(v: any): number {
  510. const n = Number(String(v ?? '0').replace(/[^\d.-]/g, ''));
  511. if (!Number.isFinite(n)) return 0;
  512. return Math.max(0, Math.trunc(n));
  513. }
  514. const trendTitle = computed(() => {
  515. if (!selectedWork.value) return '趋势';
  516. if (selectedWork.value.platform !== 'xiaohongshu') {
  517. const map: Record<TrendMetricKey, string> = {
  518. playCount: '播放(阅读)量趋势',
  519. totalWatchDuration: '播放总时长趋势',
  520. likeCount: '点赞量趋势',
  521. commentCount: '评论量趋势',
  522. collectCount: '收藏量趋势',
  523. shareCount: '分享量趋势',
  524. fansIncrease: '涨粉量趋势',
  525. followCount: '关注量趋势',
  526. exposureCount: '曝光量趋势',
  527. coverClickRate: '封面点击率趋势',
  528. avgWatchDuration: '平均观看时长趋势',
  529. completionRate: '完播率趋势',
  530. twoSecondExitRate: '2s退出率趋势',
  531. };
  532. return map[activeTrendMetric.value] || '趋势';
  533. }
  534. const map: Record<TrendMetricKey, string> = {
  535. exposureCount: '曝光量趋势',
  536. playCount: '播放(阅读)量趋势',
  537. likeCount: '点赞量趋势',
  538. commentCount: '评论量趋势',
  539. collectCount: '收藏量趋势',
  540. shareCount: '分享量趋势',
  541. coverClickRate: '封面点击率趋势',
  542. avgWatchDuration: '平均观看时长趋势',
  543. completionRate: '完播率趋势',
  544. twoSecondExitRate: '2s退出率趋势',
  545. fansIncrease: '涨粉量趋势',
  546. followCount: '关注量趋势',
  547. totalWatchDuration: '播放总时长趋势',
  548. };
  549. return map[activeTrendMetric.value] || '趋势';
  550. });
  551. function setTrendMetric(key: TrendMetricKey) {
  552. activeTrendMetric.value = key;
  553. if (workStatsHistory.value.length > 0) {
  554. updatePlayTrendChart(workStatsHistory.value);
  555. }
  556. }
  557. function getPlatformName(platform: PlatformType) {
  558. return PLATFORMS[platform]?.name || platform;
  559. }
  560. function getPlatformTagType(platform: PlatformType) {
  561. const typeMap: Record<string, 'primary' | 'success' | 'warning' | 'danger' | 'info'> = {
  562. douyin: 'danger',
  563. xiaohongshu: 'danger',
  564. bilibili: 'primary',
  565. kuaishou: 'warning',
  566. weixin: 'success',
  567. };
  568. return typeMap[platform] || 'info';
  569. }
  570. function formatTime(time: string) {
  571. if (!time) return '-';
  572. const d = dayjs(time);
  573. if (!d.isValid()) return time;
  574. const nowYear = dayjs().year();
  575. // 今年:01-22 10:22,往年:2025-12-22 10:22
  576. return d.year() === nowYear ? d.format('MM-DD HH:mm') : d.format('YYYY-MM-DD HH:mm');
  577. }
  578. // 快捷日期选择
  579. function handleQuickDate(type: string) {
  580. activeQuickBtn.value = type;
  581. const today = dayjs();
  582. switch (type) {
  583. case 'last3days':
  584. // 从昨天往前推3天(今天数据往往未统计)
  585. startDate.value = today.subtract(2, 'day').format('YYYY-MM-DD');
  586. endDate.value = today.subtract(1, 'day').format('YYYY-MM-DD');
  587. break;
  588. case 'last7days':
  589. // 从昨天往前推7天
  590. startDate.value = today.subtract(6, 'day').format('YYYY-MM-DD');
  591. endDate.value = today.subtract(1, 'day').format('YYYY-MM-DD');
  592. break;
  593. case 'lastMonth':
  594. // 从昨天往前推30天
  595. startDate.value = today.subtract(29, 'day').format('YYYY-MM-DD');
  596. endDate.value = today.subtract(1, 'day').format('YYYY-MM-DD');
  597. break;
  598. }
  599. handleQuery();
  600. }
  601. // 查询
  602. function handleQuery() {
  603. loadData();
  604. }
  605. // 平台/分组/日期/账号变更时重置页码并查询
  606. function handleFilterChange() {
  607. currentPage.value = 1;
  608. handleQuery();
  609. }
  610. // 搜索框防抖(300ms 后触发查询)
  611. let searchDebounceTimer: ReturnType<typeof setTimeout> | null = null;
  612. function handleSearchInput() {
  613. if (searchDebounceTimer) clearTimeout(searchDebounceTimer);
  614. searchDebounceTimer = setTimeout(() => {
  615. currentPage.value = 1;
  616. handleQuery();
  617. searchDebounceTimer = null;
  618. }, 300);
  619. }
  620. // 加载账号列表
  621. async function loadAccountList() {
  622. try {
  623. const res = await request.get('/api/accounts');
  624. // 新接口:request 已经解包,res 就是账号数组
  625. if (Array.isArray(res)) {
  626. accountList.value = res.map((a: any) => ({
  627. id: a.id,
  628. nickname: a.accountName || a.nickname || a.username,
  629. platform: a.platform as PlatformType,
  630. }));
  631. } else if ((res as any)?.data?.data) {
  632. // 兼容旧格式 { data: { data: [] } }
  633. accountList.value = (res as any).data.data.map((a: any) => ({
  634. id: a.id,
  635. nickname: a.accountName || a.nickname || a.username,
  636. platform: a.platform as PlatformType,
  637. }));
  638. }
  639. } catch (error) {
  640. console.error('加载账号列表失败:', error);
  641. }
  642. }
  643. // 加载分组列表
  644. async function loadGroups() {
  645. try {
  646. const res = await request.get('/api/accounts/groups');
  647. // 新接口:request 已经解包,res 就是分组数组
  648. if (Array.isArray(res)) {
  649. accountGroups.value = res as AccountGroup[];
  650. } else if ((res as any)?.data?.data) {
  651. // 兼容旧格式 { data: { data: [] } }
  652. accountGroups.value = (res as any).data.data || [];
  653. }
  654. } catch (error) {
  655. console.error('加载分组失败:', error);
  656. }
  657. }
  658. // 加载数据
  659. async function loadData() {
  660. const userId = authStore.user?.id;
  661. if (!userId) return;
  662. loading.value = true;
  663. try {
  664. const params: Record<string, any> = {
  665. startDate: startDate.value,
  666. endDate: endDate.value,
  667. page: currentPage.value,
  668. pageSize: pageSize.value,
  669. sortBy: sortBy.value,
  670. };
  671. if (selectedPlatform.value) {
  672. params.platform = selectedPlatform.value;
  673. }
  674. if (selectedAccounts.value.length > 0) {
  675. params.accountIds = selectedAccounts.value.join(',');
  676. }
  677. if (searchKeyword.value) {
  678. params.keyword = searchKeyword.value;
  679. }
  680. if (selectedGroup.value) {
  681. params.groupId = selectedGroup.value;
  682. }
  683. const data = await request.get('/api/work-day-statistics/works', {
  684. params,
  685. });
  686. if (data) {
  687. workList.value = (data.works || []) as WorkData[];
  688. totalWorks.value = data.total || 0;
  689. if (data.summary) {
  690. summaryData.value = {
  691. totalWorks: data.summary.totalWorks || 0,
  692. recommendCount: data.summary.recommendCount || 0,
  693. viewsCount: data.summary.viewsCount || 0,
  694. commentsCount: data.summary.commentsCount || 0,
  695. sharesCount: data.summary.sharesCount || 0,
  696. collectsCount: data.summary.collectsCount || 0,
  697. likesCount: data.summary.likesCount || 0,
  698. };
  699. }
  700. }
  701. } catch (error) {
  702. console.error('加载作品数据失败:', error);
  703. ElMessage.error('加载作品数据失败,请稍后重试');
  704. } finally {
  705. loading.value = false;
  706. }
  707. }
  708. // 格式化数字
  709. function formatNumber(num: number | null | undefined): string {
  710. if (num === null || num === undefined) return '0';
  711. if (num >= 10000) {
  712. return (num / 10000).toFixed(1) + '万';
  713. }
  714. return String(num);
  715. }
  716. function formatDurationSeconds(secLike: any): string {
  717. const s = Math.max(0, parseInt(String(secLike ?? '0'), 10) || 0);
  718. if (s >= 60) return `${Math.floor(s / 60)}分${s % 60}秒`;
  719. return `${s}秒`;
  720. }
  721. /** 平均观看时长:保留 2 位小数(非小红书口径) */
  722. function formatAvgWatchDurationSeconds(secLike: any): string {
  723. const s = Math.max(0, parseFloat(String(secLike ?? '0')) || 0);
  724. if (s >= 60) return `${Math.floor(s / 60)}分${(s % 60).toFixed(2)}秒`;
  725. return `${s.toFixed(2)}秒`;
  726. }
  727. /** 小红书平均观看时长:取整(秒) */
  728. function formatAvgWatchDurationSecondsInt(secLike: any): string {
  729. const s = Math.max(0, Math.round(parseFloat(String(secLike ?? '0')) || 0));
  730. if (s >= 60) return `${Math.floor(s / 60)}分${s % 60}秒`;
  731. return `${s}秒`;
  732. }
  733. function formatRate(rateLike: any): string {
  734. const raw = String(rateLike ?? '0').trim();
  735. if (!raw) return '0%';
  736. if (raw.includes('%')) return raw;
  737. const n = Number(raw);
  738. if (Number.isNaN(n)) return raw;
  739. // 兼容:有的入库是 0.12(表示 12%),有的是 12(表示 12%)
  740. const pct = n <= 1 ? n * 100 : n;
  741. return `${pct.toFixed(2).replace(/\.00$/, '')}%`;
  742. }
  743. function calcDetailRangeDatesFixed14Days(): { start: string; end: string } {
  744. const publish = dayjs(selectedWork.value?.publishTime);
  745. const platform = selectedWork.value?.platform;
  746. // 小红书:趋势固定「发布后 14 天(含发布日)」,与页面时间范围无关
  747. if (platform === 'xiaohongshu' && publish.isValid()) {
  748. const start = publish.startOf('day');
  749. const end = start.add(13, 'day'); // 发布日 + 13 天 = 共 14 天
  750. return { start: start.format('YYYY-MM-DD'), end: end.format('YYYY-MM-DD') };
  751. }
  752. const today = dayjs().startOf('day');
  753. // 抖音:作品详情趋势固定为「今天往回 30 天(含今天)」,与列表筛选无关;且不早于发布时间
  754. if (platform === 'douyin') {
  755. let end = today;
  756. let start = end.subtract(29, 'day'); // 近30天(含当天)
  757. if (publish.isValid() && publish.isAfter(start)) {
  758. start = publish.startOf('day');
  759. }
  760. return { start: start.format('YYYY-MM-DD'), end: end.format('YYYY-MM-DD') };
  761. }
  762. const end = dayjs(endDate.value || today);
  763. // 其他平台:保持原逻辑(以页面 endDate 为截止的近 14 天),且不早于发布时间
  764. const start14 = end.subtract(13, 'day'); // 近14天(含当天)
  765. const clampedStart = publish.isValid() && publish.isAfter(start14) ? publish.startOf('day') : start14;
  766. return { start: clampedStart.format('YYYY-MM-DD'), end: end.format('YYYY-MM-DD') };
  767. }
  768. interface MetricCardConfig {
  769. key?: TrendMetricKey;
  770. label: string;
  771. value: string;
  772. }
  773. const xhsMetricCards = computed<MetricCardConfig[]>(() => {
  774. const d = workDetailData.value;
  775. return [
  776. { key: 'exposureCount' as const, label: '曝光量', value: formatNumber(d.exposureCount || 0) },
  777. { key: 'playCount' as const, label: '播放(阅读)量', value: formatNumber(d.playCount || selectedWork.value?.viewsCount || 0) },
  778. { key: 'likeCount' as const, label: '点赞量', value: formatNumber(d.likeCount || selectedWork.value?.likesCount || 0) },
  779. { key: 'commentCount' as const, label: '评论量', value: formatNumber(d.commentCount || selectedWork.value?.commentsCount || 0) },
  780. { key: 'collectCount' as const, label: '收藏量', value: formatNumber(d.collectCount || selectedWork.value?.collectsCount || 0) },
  781. { key: 'shareCount' as const, label: '分享量', value: formatNumber(d.shareCount || selectedWork.value?.sharesCount || 0) },
  782. { key: 'coverClickRate' as const, label: '封面点击率', value: formatRate(d.coverClickRate) },
  783. { key: 'avgWatchDuration' as const, label: '平均观看时长', value: formatAvgWatchDurationSecondsInt(d.avgWatchDuration) },
  784. { key: 'completionRate' as const, label: '完播率', value: formatRate(d.completionRate) },
  785. { key: 'twoSecondExitRate' as const, label: '2s退出率', value: formatRate(d.twoSecondExitRate) },
  786. { key: 'fansIncrease' as const, label: '涨粉量', value: formatNumber(d.fansIncrease || 0) },
  787. ];
  788. });
  789. // 抖音:按照小红书样式展示已有字段(不包含曝光量,新增 5s 完播率与播放总时长)
  790. const douyinMetricCards = computed<MetricCardConfig[]>(() => {
  791. const d = workDetailData.value;
  792. const base = selectedWork.value;
  793. return [
  794. { key: 'playCount', label: '播放量', value: formatNumber(d.playCount || base?.viewsCount || 0) },
  795. { key: 'likeCount', label: '点赞量', value: formatNumber(d.likeCount || base?.likesCount || 0) },
  796. { key: 'commentCount', label: '评论量', value: formatNumber(d.commentCount || base?.commentsCount || 0) },
  797. { key: 'collectCount', label: '收藏量', value: formatNumber(d.collectCount || base?.collectsCount || 0) },
  798. { key: 'shareCount', label: '分享量', value: formatNumber(d.shareCount || base?.sharesCount || 0) },
  799. { key: 'fansIncrease', label: '涨粉量', value: formatNumber(d.fansIncrease || 0) },
  800. { key: 'completionRate', label: '完播率', value: formatRate(d.completionRate) },
  801. { key: 'twoSecondExitRate', label: '2s退出率', value: formatRate(d.twoSecondExitRate) },
  802. // 5s 完播率仅为昨日快照,不参与趋势联动
  803. { label: '5s完播率', value: formatRate(d.completionRate5s) },
  804. { label: '平均观看时长', value: formatAvgWatchDurationSeconds(d.avgWatchDuration) },
  805. ];
  806. });
  807. // 视频号:播放、点赞、评论、分享、收藏、关注数、涨粉量、平均观看时长、完播率、2s退出率
  808. const weixinMetricCards = computed<MetricCardConfig[]>(() => {
  809. const d = workDetailData.value;
  810. const base = selectedWork.value;
  811. return [
  812. { key: 'playCount', label: '播放量', value: formatNumber(d.playCount || base?.viewsCount || 0) },
  813. { key: 'likeCount', label: '点赞量', value: formatNumber(d.likeCount || base?.likesCount || 0) },
  814. { key: 'commentCount', label: '评论量', value: formatNumber(d.commentCount || base?.commentsCount || 0) },
  815. { key: 'shareCount', label: '分享量', value: formatNumber(d.shareCount || base?.sharesCount || 0) },
  816. { key: 'collectCount', label: '收藏量', value: formatNumber(d.collectCount || base?.collectsCount || 0) },
  817. { key: 'followCount', label: '关注数', value: formatNumber(d.followCount || 0) },
  818. // { key: 'fansIncrease', label: '涨粉量', value: formatNumber(d.fansIncrease || 0) },
  819. { label: '平均观看时长', value: formatAvgWatchDurationSeconds(d.avgWatchDuration) },
  820. { label: '完播率', value: formatRate(d.completionRate) },
  821. // { key: 'twoSecondExitRate', label: '2s退出率', value: formatRate(d.twoSecondExitRate) },
  822. ];
  823. });
  824. // 百家号:推荐量、播放(阅读)量、评论量、点赞量、收藏量、分享量、完播率、涨粉量
  825. const baijiahaoMetricCards = computed<MetricCardConfig[]>(() => {
  826. const d = workDetailData.value;
  827. const base = selectedWork.value;
  828. return [
  829. { label: '推荐量', value: formatNumber(d.recommendCount || 0) },
  830. { key: 'playCount' as const, label: '播放(阅读)量', value: formatNumber(d.playCount || base?.viewsCount || 0) },
  831. { key: 'commentCount' as const, label: '评论量', value: formatNumber(d.commentCount || base?.commentsCount || 0) },
  832. { key: 'likeCount' as const, label: '点赞量', value: formatNumber(d.likeCount || base?.likesCount || 0) },
  833. { key: 'collectCount' as const, label: '收藏量', value: formatNumber(d.collectCount || base?.collectsCount || 0) },
  834. { key: 'shareCount' as const, label: '分享量', value: formatNumber(d.shareCount || base?.sharesCount || 0) },
  835. { key: 'completionRate' as const, label: '完播率', value: formatRate(d.completionRate) },
  836. { key: 'fansIncrease' as const, label: '涨粉量', value: formatNumber(d.fansIncrease || 0) },
  837. ];
  838. });
  839. // 查看详情
  840. async function handleView(row: WorkData) {
  841. selectedWork.value = row;
  842. selectedWorkBase.value = null;
  843. activeTrendMetric.value = row.platform === 'xiaohongshu' ? 'exposureCount' : 'playCount';
  844. workStatsHistory.value = [];
  845. drawerVisible.value = true;
  846. activeTab.value = 'core';
  847. // [已注释] 视频号:点击详情时先同步每日数据(浏览器自动化 + CSV 导入)
  848. // if (row.platform === 'weixin_video') {
  849. // detailLoading.value = true;
  850. // try {
  851. // const syncRes = await request.post(`/api/work-day-statistics/sync-weixin-video/${row.id}`);
  852. // if (syncRes?.success && (syncRes?.data?.inserted > 0 || syncRes?.data?.updated > 0)) {
  853. // ElMessage.success(syncRes.message || `已同步 ${(syncRes.data?.inserted || 0) + (syncRes.data?.updated || 0)} 条日数据`);
  854. // }
  855. // } catch (e) {
  856. // console.warn('视频号日数据同步失败(可忽略):', e);
  857. // } finally {
  858. // detailLoading.value = false;
  859. // }
  860. // }
  861. // 先用列表行做“瞬时占位”(列表来自区间汇总,可能不等于 works 表累计值)
  862. workDetailData.value = {
  863. playCount: row.viewsCount || 0,
  864. exposureCount: 0,
  865. totalWatchDuration: '0秒',
  866. likeCount: row.likesCount || 0,
  867. commentCount: row.commentsCount || 0,
  868. collectCount: row.collectsCount || 0,
  869. shareCount: row.sharesCount || 0,
  870. fansIncrease: 0,
  871. followCount: 0,
  872. recommendCount: 0,
  873. coverClickRate: '0',
  874. avgWatchDuration: '0',
  875. completionRate: '0',
  876. twoSecondExitRate: '0',
  877. };
  878. // 1) 加载 works 表基础信息(标题、发布时间、累计播放/点赞等)
  879. await loadWorkBase(row.id);
  880. // 2) 加载 work_day_statistics 历史快照(用于“最新累计值”与趋势)
  881. await loadWorkDetail(row.id);
  882. }
  883. // 加载作品基础信息(works 表)
  884. async function loadWorkBase(workId: number) {
  885. try {
  886. const data = await request.get(`/api/works/${workId}`);
  887. if (!data) return;
  888. selectedWorkBase.value = data;
  889. // 基础信息补齐:以 works 表为准(如果 works 缺失字段则回退到列表行)
  890. if (selectedWork.value) {
  891. selectedWork.value = {
  892. ...selectedWork.value,
  893. title: data.title || selectedWork.value.title,
  894. publishTime: data.publishTime || selectedWork.value.publishTime,
  895. coverUrl: data.coverUrl || selectedWork.value.coverUrl,
  896. };
  897. }
  898. // 顶部卡片:按需求展示 works.yesterday_*(昨日快照)
  899. workDetailData.value = {
  900. playCount: toIntSafe(data.yesterdayPlayCount ?? 0),
  901. exposureCount: toIntSafe(data.yesterdayExposureCount ?? 0),
  902. totalWatchDuration: formatDurationSeconds(data.yesterdayTotalWatchDuration ?? 0),
  903. likeCount: toIntSafe(data.yesterdayLikeCount ?? 0),
  904. commentCount: toIntSafe(data.yesterdayCommentCount ?? 0),
  905. collectCount: toIntSafe(data.yesterdayCollectCount ?? 0),
  906. shareCount: toIntSafe(data.yesterdayShareCount ?? 0),
  907. fansIncrease: toIntSafe(data.yesterdayFansIncrease ?? 0),
  908. followCount: toIntSafe(data.yesterdayFollowCount ?? 0),
  909. recommendCount: toIntSafe(data.yesterdayRecommendCount ?? 0),
  910. coverClickRate: String(data.yesterdayCoverClickRate ?? '0'),
  911. avgWatchDuration: String(data.yesterdayAvgWatchDuration ?? '0'),
  912. completionRate: String(data.yesterdayCompletionRate ?? '0'),
  913. twoSecondExitRate: String(data.yesterdayTwoSecondExitRate ?? '0'),
  914. completionRate5s: String(data.yesterdayCompletionRate5s ?? '0'),
  915. };
  916. } catch (error) {
  917. // works 表请求失败不影响后续趋势展示
  918. console.warn('加载作品基础信息失败:', error);
  919. }
  920. }
  921. // 加载作品详情数据(历史统计数据)
  922. async function loadWorkDetail(workId: number) {
  923. detailLoading.value = true;
  924. try {
  925. // 趋势固定:近 14 天(按 work_day_statistics 日新增量口径)
  926. const { start: startDateStr, end: endDateStr } = calcDetailRangeDatesFixed14Days();
  927. // 调用接口获取该作品的历史统计数据(work_day_statistics 快照)
  928. const data = await request.get(`/api/work-day-statistics/work/${workId}`, {
  929. params: {
  930. // 注意:后端校验参数名为 startDate/endDate
  931. startDate: startDateStr,
  932. endDate: endDateStr,
  933. },
  934. });
  935. if (data && Array.isArray(data)) {
  936. const workStats = data;
  937. workStatsHistory.value = workStats;
  938. // 绘制趋势图(按天新增量)
  939. await nextTick();
  940. updatePlayTrendChart(workStats);
  941. }
  942. } catch (error) {
  943. console.error('加载作品详情失败:', error);
  944. ElMessage.error('加载作品详情失败,请稍后重试');
  945. } finally {
  946. detailLoading.value = false;
  947. }
  948. }
  949. // 更新播放量趋势图
  950. function updatePlayTrendChart(stats: Array<any>) {
  951. if (!playTrendChartRef.value) return;
  952. if (!playTrendChart) {
  953. playTrendChart = echarts.init(playTrendChartRef.value);
  954. }
  955. // 按日期排序
  956. const sortedStats = [...stats].sort((a, b) =>
  957. dayjs(a.recordDate).valueOf() - dayjs(b.recordDate).valueOf()
  958. );
  959. const dates = sortedStats.map(s => dayjs(s.recordDate).format('YYYY-MM-DD'));
  960. const metric = activeTrendMetric.value;
  961. const seriesName = trendTitle.value.replace('趋势', '');
  962. const isRateMetric =
  963. metric === 'coverClickRate' || metric === 'completionRate' || metric === 'twoSecondExitRate';
  964. const isDurationMetric = metric === 'avgWatchDuration' || metric === 'totalWatchDuration';
  965. const values = sortedStats.map((s) => {
  966. const v = s?.[metric];
  967. if (isRateMetric) {
  968. const raw = String(v ?? '0').trim();
  969. if (raw.includes('%')) return Number(raw.replace('%', '')) || 0;
  970. const n = Number(raw);
  971. if (Number.isNaN(n)) return 0;
  972. return n <= 1 ? n * 100 : n;
  973. }
  974. if (metric === 'avgWatchDuration') {
  975. return Math.max(0, Math.round(parseFloat(String(v ?? '0')) || 0));
  976. }
  977. if (metric === 'totalWatchDuration') {
  978. return Math.max(0, parseInt(String(v ?? '0'), 10) || 0);
  979. }
  980. return Number(v) || 0;
  981. });
  982. const option: echarts.EChartsOption = {
  983. tooltip: {
  984. trigger: 'axis',
  985. axisPointer: {
  986. type: 'cross',
  987. },
  988. formatter: (params: any) => {
  989. const arr = Array.isArray(params) ? params : [params];
  990. if (arr.length === 0) return '';
  991. const dateLabel = arr[0]?.axisValueLabel || arr[0]?.axisValue || '';
  992. const lines: string[] = [`${dateLabel}`];
  993. for (const p of arr) {
  994. const name = p?.seriesName ?? '';
  995. const val = typeof p?.data === 'number' ? p.data : Number(p?.data ?? 0);
  996. if (isRateMetric) {
  997. lines.push(`${name}:${(Number.isFinite(val) ? val : 0).toFixed(2).replace(/\.00$/, '')}%`);
  998. } else if (isDurationMetric) {
  999. lines.push(`${name}:${formatDurationSeconds(Number.isFinite(val) ? Math.round(val) : 0)}`);
  1000. } else {
  1001. lines.push(`${name}:${formatNumber(Number.isFinite(val) ? val : 0)}`);
  1002. }
  1003. }
  1004. return lines.join('<br/>');
  1005. },
  1006. },
  1007. grid: {
  1008. left: '3%',
  1009. right: '4%',
  1010. bottom: '3%',
  1011. containLabel: true,
  1012. },
  1013. xAxis: {
  1014. type: 'category',
  1015. boundaryGap: false,
  1016. data: dates,
  1017. axisLabel: {
  1018. formatter: (value: string) => {
  1019. return dayjs(value).format('MM-DD');
  1020. },
  1021. },
  1022. },
  1023. yAxis: {
  1024. type: 'value',
  1025. axisLabel: {
  1026. formatter: (value: number) => {
  1027. if (isRateMetric) {
  1028. const n = Number.isFinite(value) ? value : 0;
  1029. return `${n.toFixed(2).replace(/\.00$/, '')}%`;
  1030. }
  1031. if (isDurationMetric) {
  1032. return formatDurationSeconds(Number.isFinite(value) ? Math.round(value) : 0);
  1033. }
  1034. if (value >= 10000) return (value / 10000).toFixed(1) + '万';
  1035. return String(value);
  1036. },
  1037. },
  1038. },
  1039. series: [
  1040. {
  1041. name: seriesName || '趋势',
  1042. type: 'line',
  1043. smooth: true,
  1044. data: values,
  1045. itemStyle: {
  1046. color: '#ff6b9d',
  1047. },
  1048. areaStyle: {
  1049. color: {
  1050. type: 'linear',
  1051. x: 0,
  1052. y: 0,
  1053. x2: 0,
  1054. y2: 1,
  1055. colorStops: [
  1056. { offset: 0, color: 'rgba(255, 107, 157, 0.3)' },
  1057. { offset: 1, color: 'rgba(255, 107, 157, 0.05)' },
  1058. ],
  1059. },
  1060. },
  1061. },
  1062. ],
  1063. };
  1064. playTrendChart.setOption(option, true);
  1065. }
  1066. // 监听弹窗关闭,清理图表
  1067. watch(drawerVisible, (visible) => {
  1068. if (!visible && playTrendChart) {
  1069. playTrendChart.dispose();
  1070. playTrendChart = null;
  1071. }
  1072. });
  1073. // 导出数据(按当前筛选条件导出作品列表)
  1074. async function handleExport() {
  1075. try {
  1076. const baseUrl = serverStore.currentServer?.url;
  1077. if (!baseUrl) {
  1078. ElMessage.error('未连接服务器');
  1079. return;
  1080. }
  1081. if (!authStore.accessToken) {
  1082. ElMessage.error('未连接服务器或未登录');
  1083. return;
  1084. }
  1085. const params = new URLSearchParams();
  1086. params.set('startDate', startDate.value);
  1087. params.set('endDate', endDate.value);
  1088. if (selectedPlatform.value) params.set('platform', selectedPlatform.value);
  1089. if (selectedAccounts.value.length > 0) params.set('accountIds', selectedAccounts.value.join(','));
  1090. if (selectedGroup.value) params.set('groupId', String(selectedGroup.value));
  1091. if (searchKeyword.value) params.set('keyword', searchKeyword.value);
  1092. params.set('sortBy', sortBy.value);
  1093. const url = `${baseUrl}/api/work-day-statistics/works/export?${params.toString()}`;
  1094. const doFetch = async (token: string) => {
  1095. return await fetch(url, {
  1096. method: 'GET',
  1097. headers: { Authorization: `Bearer ${token}` },
  1098. });
  1099. };
  1100. let resp = await doFetch(authStore.accessToken!);
  1101. if (resp.status === 401) {
  1102. const refreshed = await authStore.refreshAccessToken();
  1103. if (!refreshed || !authStore.accessToken) {
  1104. ElMessage.error('登录已过期,请重新登录');
  1105. return;
  1106. }
  1107. resp = await doFetch(authStore.accessToken!);
  1108. }
  1109. if (!resp.ok) {
  1110. const text = await resp.text().catch(() => '');
  1111. throw new Error(text || `导出失败,状态码:${resp.status}`);
  1112. }
  1113. const blob = await resp.blob();
  1114. const downloadUrl = window.URL.createObjectURL(blob);
  1115. const a = document.createElement('a');
  1116. a.href = downloadUrl;
  1117. a.download = `作品数据_${dayjs().format('YYYYMMDD_HHmmss')}.xlsx`;
  1118. document.body.appendChild(a);
  1119. a.click();
  1120. a.remove();
  1121. window.URL.revokeObjectURL(downloadUrl);
  1122. ElMessage.success('导出成功');
  1123. } catch (error: any) {
  1124. console.error('导出失败:', error);
  1125. ElMessage.error(error?.message || '导出失败');
  1126. }
  1127. }
  1128. onMounted(() => {
  1129. loadAccountList();
  1130. loadGroups();
  1131. loadData();
  1132. });
  1133. </script>
  1134. <style lang="scss" scoped>
  1135. @use '@/styles/variables.scss' as *;
  1136. .work-analytics {
  1137. .filter-bar {
  1138. display: flex;
  1139. align-items: center;
  1140. justify-content: space-between;
  1141. margin-bottom: 20px;
  1142. padding: 16px 20px;
  1143. background: #fff;
  1144. border-radius: $radius-lg;
  1145. box-shadow: $shadow-sm;
  1146. &.secondary {
  1147. margin-bottom: 16px;
  1148. padding: 12px 20px;
  1149. }
  1150. .filter-left {
  1151. display: flex;
  1152. align-items: center;
  1153. gap: 12px;
  1154. .filter-label {
  1155. font-size: 14px;
  1156. color: $text-regular;
  1157. }
  1158. .quick-btns {
  1159. display: flex;
  1160. gap: 8px;
  1161. }
  1162. }
  1163. }
  1164. .stats-row {
  1165. display: grid;
  1166. grid-template-columns: repeat(7, 1fr);
  1167. gap: 0;
  1168. margin-bottom: 20px;
  1169. background: #fff;
  1170. border-radius: $radius-lg;
  1171. box-shadow: $shadow-sm;
  1172. overflow: hidden;
  1173. .stat-card {
  1174. padding: 20px 16px;
  1175. display: flex;
  1176. align-items: center;
  1177. gap: 12px;
  1178. border-right: 1px solid #f0f0f0;
  1179. &:last-child {
  1180. border-right: none;
  1181. }
  1182. .stat-icon {
  1183. width: 36px;
  1184. height: 36px;
  1185. background: $primary-color-light;
  1186. border-radius: 8px;
  1187. display: flex;
  1188. align-items: center;
  1189. justify-content: center;
  1190. color: $primary-color;
  1191. flex-shrink: 0;
  1192. }
  1193. .stat-info {
  1194. .stat-label {
  1195. font-size: 12px;
  1196. color: $text-secondary;
  1197. margin-bottom: 4px;
  1198. white-space: nowrap;
  1199. }
  1200. .stat-value {
  1201. font-size: 20px;
  1202. font-weight: 600;
  1203. color: $text-primary;
  1204. }
  1205. }
  1206. }
  1207. }
  1208. .data-table {
  1209. background: #fff;
  1210. border-radius: $radius-lg;
  1211. box-shadow: $shadow-sm;
  1212. overflow: hidden;
  1213. .account-cell {
  1214. display: flex;
  1215. align-items: center;
  1216. gap: 8px;
  1217. .account-name {
  1218. font-weight: 500;
  1219. color: $text-primary;
  1220. }
  1221. }
  1222. .title-cell {
  1223. .work-title {
  1224. font-weight: 500;
  1225. color: $primary-color;
  1226. margin-bottom: 6px;
  1227. cursor: pointer;
  1228. &:hover {
  1229. text-decoration: underline;
  1230. }
  1231. }
  1232. .work-stats {
  1233. display: flex;
  1234. gap: 16px;
  1235. font-size: 12px;
  1236. color: $text-secondary;
  1237. .stat-item {
  1238. em {
  1239. font-style: normal;
  1240. color: $primary-color;
  1241. margin-left: 2px;
  1242. }
  1243. }
  1244. }
  1245. }
  1246. .publish-time {
  1247. font-size: 13px;
  1248. color: $text-secondary;
  1249. }
  1250. .pagination-wrapper {
  1251. padding: 16px 20px;
  1252. display: flex;
  1253. justify-content: flex-end;
  1254. }
  1255. }
  1256. }
  1257. :deep(.work-detail-dialog) {
  1258. .el-dialog__header {
  1259. padding-bottom: 0;
  1260. }
  1261. .el-dialog__body {
  1262. padding-top: 20px;
  1263. }
  1264. }
  1265. .work-detail {
  1266. .detail-header {
  1267. margin-bottom: 24px;
  1268. padding-bottom: 16px;
  1269. border-bottom: 1px solid #f0f0f0;
  1270. .work-title {
  1271. margin: 0 0 8px 0;
  1272. font-size: 18px;
  1273. font-weight: 600;
  1274. color: $text-primary;
  1275. }
  1276. .publish-time {
  1277. font-size: 14px;
  1278. color: $text-secondary;
  1279. }
  1280. }
  1281. .detail-tabs {
  1282. :deep(.el-tabs__header) {
  1283. margin-bottom: 24px;
  1284. }
  1285. :deep(.el-tabs__item) {
  1286. font-size: 15px;
  1287. font-weight: 500;
  1288. }
  1289. }
  1290. .core-data-content {
  1291. .traffic-data {
  1292. margin-bottom: 32px;
  1293. .section-title-row {
  1294. display: flex;
  1295. align-items: center;
  1296. justify-content: space-between;
  1297. gap: 12px;
  1298. margin-bottom: 16px;
  1299. }
  1300. .section-title {
  1301. margin: 0;
  1302. font-size: 16px;
  1303. font-weight: 600;
  1304. color: $text-primary;
  1305. }
  1306. .detail-range {
  1307. display: flex;
  1308. gap: 8px;
  1309. flex-wrap: wrap;
  1310. justify-content: flex-end;
  1311. }
  1312. .data-cards {
  1313. display: grid;
  1314. grid-template-columns: repeat(7, 1fr);
  1315. gap: 16px;
  1316. @media (max-width: 1400px) {
  1317. grid-template-columns: repeat(4, 1fr);
  1318. }
  1319. @media (max-width: 900px) {
  1320. grid-template-columns: repeat(3, 1fr);
  1321. }
  1322. @media (max-width: 600px) {
  1323. grid-template-columns: repeat(2, 1fr);
  1324. }
  1325. .data-card {
  1326. background: #f8fafc;
  1327. border-radius: 8px;
  1328. padding: 20px 16px;
  1329. text-align: center;
  1330. border: 1px solid #e5e7eb;
  1331. cursor: pointer;
  1332. &.highlight {
  1333. background: #fff5f7;
  1334. border-color: #ff6b9d;
  1335. .card-value {
  1336. color: #ff6b9d;
  1337. font-weight: 700;
  1338. }
  1339. }
  1340. .card-label {
  1341. font-size: 13px;
  1342. color: $text-secondary;
  1343. margin-bottom: 8px;
  1344. }
  1345. .card-value {
  1346. font-size: 24px;
  1347. font-weight: 600;
  1348. color: $text-primary;
  1349. line-height: 1.2;
  1350. }
  1351. }
  1352. }
  1353. }
  1354. .trend-section {
  1355. .section-title {
  1356. margin: 0 0 16px 0;
  1357. font-size: 16px;
  1358. font-weight: 600;
  1359. color: $text-primary;
  1360. }
  1361. }
  1362. }
  1363. }
  1364. @media (max-width: 1400px) {
  1365. .work-analytics {
  1366. .stats-row {
  1367. grid-template-columns: repeat(4, 1fr);
  1368. .stat-card {
  1369. &:nth-child(4) {
  1370. border-right: none;
  1371. }
  1372. &:nth-child(n+5) {
  1373. border-top: 1px solid #f0f0f0;
  1374. }
  1375. }
  1376. }
  1377. }
  1378. }
  1379. @media (max-width: 1200px) {
  1380. .work-analytics {
  1381. .filter-bar {
  1382. flex-direction: column;
  1383. align-items: flex-start;
  1384. gap: 12px;
  1385. .filter-left {
  1386. flex-wrap: wrap;
  1387. }
  1388. }
  1389. .stats-row {
  1390. grid-template-columns: repeat(3, 1fr);
  1391. .stat-card {
  1392. &:nth-child(3n) {
  1393. border-right: none;
  1394. }
  1395. &:nth-child(n+4) {
  1396. border-top: 1px solid #f0f0f0;
  1397. }
  1398. }
  1399. }
  1400. }
  1401. }
  1402. </style>