index.vue 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548
  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: 160px"
  46. @change="handleFilterChange"
  47. >
  48. <el-option
  49. v-for="account in accountList"
  50. :key="account.id"
  51. :label="account.nickname"
  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. <!-- 排序统一按发布时间倒序,这里仅保留一个选项以避免误解 -->
  94. <el-select v-model="sortBy" style="width: 160px">
  95. <el-option label="按发布时间倒序排列" value="publish_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 }[]>([]);
  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. startDate.value = today.subtract(3, 'day').format('YYYY-MM-DD');
  585. endDate.value = today.format('YYYY-MM-DD');
  586. break;
  587. case 'last7days':
  588. startDate.value = today.subtract(7, 'day').format('YYYY-MM-DD');
  589. endDate.value = today.format('YYYY-MM-DD');
  590. break;
  591. case 'lastMonth':
  592. startDate.value = today.subtract(30, 'day').format('YYYY-MM-DD');
  593. endDate.value = today.format('YYYY-MM-DD');
  594. break;
  595. }
  596. handleQuery();
  597. }
  598. // 查询
  599. function handleQuery() {
  600. loadData();
  601. }
  602. // 平台/分组/日期/账号变更时重置页码并查询
  603. function handleFilterChange() {
  604. currentPage.value = 1;
  605. handleQuery();
  606. }
  607. // 搜索框防抖(300ms 后触发查询)
  608. let searchDebounceTimer: ReturnType<typeof setTimeout> | null = null;
  609. function handleSearchInput() {
  610. if (searchDebounceTimer) clearTimeout(searchDebounceTimer);
  611. searchDebounceTimer = setTimeout(() => {
  612. currentPage.value = 1;
  613. handleQuery();
  614. searchDebounceTimer = null;
  615. }, 300);
  616. }
  617. // 加载账号列表
  618. async function loadAccountList() {
  619. try {
  620. const res = await request.get('/api/accounts');
  621. // 新接口:request 已经解包,res 就是账号数组
  622. if (Array.isArray(res)) {
  623. accountList.value = res.map((a: any) => ({
  624. id: a.id,
  625. nickname: a.accountName || a.nickname || a.username,
  626. }));
  627. } else if ((res as any)?.data?.data) {
  628. // 兼容旧格式 { data: { data: [] } }
  629. accountList.value = (res as any).data.data.map((a: any) => ({
  630. id: a.id,
  631. nickname: a.accountName || a.nickname || a.username,
  632. }));
  633. }
  634. } catch (error) {
  635. console.error('加载账号列表失败:', error);
  636. }
  637. }
  638. // 加载分组列表
  639. async function loadGroups() {
  640. try {
  641. const res = await request.get('/api/accounts/groups');
  642. // 新接口:request 已经解包,res 就是分组数组
  643. if (Array.isArray(res)) {
  644. accountGroups.value = res as AccountGroup[];
  645. } else if ((res as any)?.data?.data) {
  646. // 兼容旧格式 { data: { data: [] } }
  647. accountGroups.value = (res as any).data.data || [];
  648. }
  649. } catch (error) {
  650. console.error('加载分组失败:', error);
  651. }
  652. }
  653. // 加载数据
  654. async function loadData() {
  655. const userId = authStore.user?.id;
  656. if (!userId) return;
  657. loading.value = true;
  658. try {
  659. const params: Record<string, any> = {
  660. startDate: startDate.value,
  661. endDate: endDate.value,
  662. page: currentPage.value,
  663. pageSize: pageSize.value,
  664. sortBy: sortBy.value,
  665. };
  666. if (selectedPlatform.value) {
  667. params.platform = selectedPlatform.value;
  668. }
  669. if (selectedAccounts.value.length > 0) {
  670. params.accountIds = selectedAccounts.value.join(',');
  671. }
  672. if (searchKeyword.value) {
  673. params.keyword = searchKeyword.value;
  674. }
  675. if (selectedGroup.value) {
  676. params.groupId = selectedGroup.value;
  677. }
  678. const data = await request.get('/api/work-day-statistics/works', {
  679. params,
  680. });
  681. if (data) {
  682. workList.value = (data.works || []) as WorkData[];
  683. totalWorks.value = data.total || 0;
  684. if (data.summary) {
  685. summaryData.value = {
  686. totalWorks: data.summary.totalWorks || 0,
  687. recommendCount: data.summary.recommendCount || 0,
  688. viewsCount: data.summary.viewsCount || 0,
  689. commentsCount: data.summary.commentsCount || 0,
  690. sharesCount: data.summary.sharesCount || 0,
  691. collectsCount: data.summary.collectsCount || 0,
  692. likesCount: data.summary.likesCount || 0,
  693. };
  694. }
  695. }
  696. } catch (error) {
  697. console.error('加载作品数据失败:', error);
  698. ElMessage.error('加载作品数据失败,请稍后重试');
  699. } finally {
  700. loading.value = false;
  701. }
  702. }
  703. // 格式化数字
  704. function formatNumber(num: number | null | undefined): string {
  705. if (num === null || num === undefined) return '0';
  706. if (num >= 10000) {
  707. return (num / 10000).toFixed(1) + '万';
  708. }
  709. return String(num);
  710. }
  711. function formatDurationSeconds(secLike: any): string {
  712. const s = Math.max(0, parseInt(String(secLike ?? '0'), 10) || 0);
  713. if (s >= 60) return `${Math.floor(s / 60)}分${s % 60}秒`;
  714. return `${s}秒`;
  715. }
  716. /** 平均观看时长:保留 2 位小数(非小红书口径) */
  717. function formatAvgWatchDurationSeconds(secLike: any): string {
  718. const s = Math.max(0, parseFloat(String(secLike ?? '0')) || 0);
  719. if (s >= 60) return `${Math.floor(s / 60)}分${(s % 60).toFixed(2)}秒`;
  720. return `${s.toFixed(2)}秒`;
  721. }
  722. /** 小红书平均观看时长:取整(秒) */
  723. function formatAvgWatchDurationSecondsInt(secLike: any): string {
  724. const s = Math.max(0, Math.round(parseFloat(String(secLike ?? '0')) || 0));
  725. if (s >= 60) return `${Math.floor(s / 60)}分${s % 60}秒`;
  726. return `${s}秒`;
  727. }
  728. function formatRate(rateLike: any): string {
  729. const raw = String(rateLike ?? '0').trim();
  730. if (!raw) return '0%';
  731. if (raw.includes('%')) return raw;
  732. const n = Number(raw);
  733. if (Number.isNaN(n)) return raw;
  734. // 兼容:有的入库是 0.12(表示 12%),有的是 12(表示 12%)
  735. const pct = n <= 1 ? n * 100 : n;
  736. return `${pct.toFixed(2).replace(/\.00$/, '')}%`;
  737. }
  738. function calcDetailRangeDatesFixed14Days(): { start: string; end: string } {
  739. const publish = dayjs(selectedWork.value?.publishTime);
  740. const platform = selectedWork.value?.platform;
  741. // 小红书:趋势固定「发布后 14 天(含发布日)」,与页面时间范围无关
  742. if (platform === 'xiaohongshu' && publish.isValid()) {
  743. const start = publish.startOf('day');
  744. const end = start.add(13, 'day'); // 发布日 + 13 天 = 共 14 天
  745. return { start: start.format('YYYY-MM-DD'), end: end.format('YYYY-MM-DD') };
  746. }
  747. const today = dayjs().startOf('day');
  748. // 抖音:作品详情趋势固定为「今天往回 30 天(含今天)」,与列表筛选无关;且不早于发布时间
  749. if (platform === 'douyin') {
  750. let end = today;
  751. let start = end.subtract(29, 'day'); // 近30天(含当天)
  752. if (publish.isValid() && publish.isAfter(start)) {
  753. start = publish.startOf('day');
  754. }
  755. return { start: start.format('YYYY-MM-DD'), end: end.format('YYYY-MM-DD') };
  756. }
  757. const end = dayjs(endDate.value || today);
  758. // 其他平台:保持原逻辑(以页面 endDate 为截止的近 14 天),且不早于发布时间
  759. const start14 = end.subtract(13, 'day'); // 近14天(含当天)
  760. const clampedStart = publish.isValid() && publish.isAfter(start14) ? publish.startOf('day') : start14;
  761. return { start: clampedStart.format('YYYY-MM-DD'), end: end.format('YYYY-MM-DD') };
  762. }
  763. interface MetricCardConfig {
  764. key?: TrendMetricKey;
  765. label: string;
  766. value: string;
  767. }
  768. const xhsMetricCards = computed<MetricCardConfig[]>(() => {
  769. const d = workDetailData.value;
  770. return [
  771. { key: 'exposureCount' as const, label: '曝光量', value: formatNumber(d.exposureCount || 0) },
  772. { key: 'playCount' as const, label: '播放(阅读)量', value: formatNumber(d.playCount || selectedWork.value?.viewsCount || 0) },
  773. { key: 'likeCount' as const, label: '点赞量', value: formatNumber(d.likeCount || selectedWork.value?.likesCount || 0) },
  774. { key: 'commentCount' as const, label: '评论量', value: formatNumber(d.commentCount || selectedWork.value?.commentsCount || 0) },
  775. { key: 'collectCount' as const, label: '收藏量', value: formatNumber(d.collectCount || selectedWork.value?.collectsCount || 0) },
  776. { key: 'shareCount' as const, label: '分享量', value: formatNumber(d.shareCount || selectedWork.value?.sharesCount || 0) },
  777. { key: 'coverClickRate' as const, label: '封面点击率', value: formatRate(d.coverClickRate) },
  778. { key: 'avgWatchDuration' as const, label: '平均观看时长', value: formatAvgWatchDurationSecondsInt(d.avgWatchDuration) },
  779. { key: 'completionRate' as const, label: '完播率', value: formatRate(d.completionRate) },
  780. { key: 'twoSecondExitRate' as const, label: '2s退出率', value: formatRate(d.twoSecondExitRate) },
  781. { key: 'fansIncrease' as const, label: '涨粉量', value: formatNumber(d.fansIncrease || 0) },
  782. ];
  783. });
  784. // 抖音:按照小红书样式展示已有字段(不包含曝光量,新增 5s 完播率与播放总时长)
  785. const douyinMetricCards = computed<MetricCardConfig[]>(() => {
  786. const d = workDetailData.value;
  787. const base = selectedWork.value;
  788. return [
  789. { key: 'playCount', label: '播放量', value: formatNumber(d.playCount || base?.viewsCount || 0) },
  790. { key: 'likeCount', label: '点赞量', value: formatNumber(d.likeCount || base?.likesCount || 0) },
  791. { key: 'commentCount', label: '评论量', value: formatNumber(d.commentCount || base?.commentsCount || 0) },
  792. { key: 'collectCount', label: '收藏量', value: formatNumber(d.collectCount || base?.collectsCount || 0) },
  793. { key: 'shareCount', label: '分享量', value: formatNumber(d.shareCount || base?.sharesCount || 0) },
  794. { key: 'fansIncrease', label: '涨粉量', value: formatNumber(d.fansIncrease || 0) },
  795. { label: '平均观看时长', value: formatAvgWatchDurationSeconds(d.avgWatchDuration) },
  796. { key: 'completionRate', label: '完播率', value: formatRate(d.completionRate) },
  797. { key: 'twoSecondExitRate', label: '2s退出率', value: formatRate(d.twoSecondExitRate) },
  798. // 5s 完播率仅为昨日快照,不参与趋势联动
  799. { label: '5s完播率', value: formatRate(d.completionRate5s) },
  800. ];
  801. });
  802. // 视频号:播放、点赞、评论、分享、收藏、关注数、涨粉量、平均观看时长、完播率、2s退出率
  803. const weixinMetricCards = computed<MetricCardConfig[]>(() => {
  804. const d = workDetailData.value;
  805. const base = selectedWork.value;
  806. return [
  807. { key: 'playCount', label: '播放量', value: formatNumber(d.playCount || base?.viewsCount || 0) },
  808. { key: 'likeCount', label: '点赞量', value: formatNumber(d.likeCount || base?.likesCount || 0) },
  809. { key: 'commentCount', label: '评论量', value: formatNumber(d.commentCount || base?.commentsCount || 0) },
  810. { key: 'shareCount', label: '分享量', value: formatNumber(d.shareCount || base?.sharesCount || 0) },
  811. { key: 'collectCount', label: '收藏量', value: formatNumber(d.collectCount || base?.collectsCount || 0) },
  812. { key: 'followCount', label: '关注数', value: formatNumber(d.followCount || 0) },
  813. // { key: 'fansIncrease', label: '涨粉量', value: formatNumber(d.fansIncrease || 0) },
  814. { label: '平均观看时长', value: formatAvgWatchDurationSeconds(d.avgWatchDuration) },
  815. { label: '完播率', value: formatRate(d.completionRate) },
  816. // { key: 'twoSecondExitRate', label: '2s退出率', value: formatRate(d.twoSecondExitRate) },
  817. ];
  818. });
  819. // 百家号:推荐量、播放(阅读)量、评论量、点赞量、收藏量、分享量、完播率、涨粉量
  820. const baijiahaoMetricCards = computed<MetricCardConfig[]>(() => {
  821. const d = workDetailData.value;
  822. const base = selectedWork.value;
  823. return [
  824. { label: '推荐量', value: formatNumber(d.recommendCount || 0) },
  825. { key: 'playCount' as const, label: '播放(阅读)量', value: formatNumber(d.playCount || base?.viewsCount || 0) },
  826. { key: 'commentCount' as const, label: '评论量', value: formatNumber(d.commentCount || base?.commentsCount || 0) },
  827. { key: 'likeCount' as const, label: '点赞量', value: formatNumber(d.likeCount || base?.likesCount || 0) },
  828. { key: 'collectCount' as const, label: '收藏量', value: formatNumber(d.collectCount || base?.collectsCount || 0) },
  829. { key: 'shareCount' as const, label: '分享量', value: formatNumber(d.shareCount || base?.sharesCount || 0) },
  830. { key: 'completionRate' as const, label: '完播率', value: formatRate(d.completionRate) },
  831. { key: 'fansIncrease' as const, label: '涨粉量', value: formatNumber(d.fansIncrease || 0) },
  832. ];
  833. });
  834. // 查看详情
  835. async function handleView(row: WorkData) {
  836. selectedWork.value = row;
  837. selectedWorkBase.value = null;
  838. activeTrendMetric.value = row.platform === 'xiaohongshu' ? 'exposureCount' : 'playCount';
  839. workStatsHistory.value = [];
  840. drawerVisible.value = true;
  841. activeTab.value = 'core';
  842. // [已注释] 视频号:点击详情时先同步每日数据(浏览器自动化 + CSV 导入)
  843. // if (row.platform === 'weixin_video') {
  844. // detailLoading.value = true;
  845. // try {
  846. // const syncRes = await request.post(`/api/work-day-statistics/sync-weixin-video/${row.id}`);
  847. // if (syncRes?.success && (syncRes?.data?.inserted > 0 || syncRes?.data?.updated > 0)) {
  848. // ElMessage.success(syncRes.message || `已同步 ${(syncRes.data?.inserted || 0) + (syncRes.data?.updated || 0)} 条日数据`);
  849. // }
  850. // } catch (e) {
  851. // console.warn('视频号日数据同步失败(可忽略):', e);
  852. // } finally {
  853. // detailLoading.value = false;
  854. // }
  855. // }
  856. // 先用列表行做“瞬时占位”(列表来自区间汇总,可能不等于 works 表累计值)
  857. workDetailData.value = {
  858. playCount: row.viewsCount || 0,
  859. exposureCount: 0,
  860. totalWatchDuration: '0秒',
  861. likeCount: row.likesCount || 0,
  862. commentCount: row.commentsCount || 0,
  863. collectCount: row.collectsCount || 0,
  864. shareCount: row.sharesCount || 0,
  865. fansIncrease: 0,
  866. followCount: 0,
  867. recommendCount: 0,
  868. coverClickRate: '0',
  869. avgWatchDuration: '0',
  870. completionRate: '0',
  871. twoSecondExitRate: '0',
  872. };
  873. // 1) 加载 works 表基础信息(标题、发布时间、累计播放/点赞等)
  874. await loadWorkBase(row.id);
  875. // 2) 加载 work_day_statistics 历史快照(用于“最新累计值”与趋势)
  876. await loadWorkDetail(row.id);
  877. }
  878. // 加载作品基础信息(works 表)
  879. async function loadWorkBase(workId: number) {
  880. try {
  881. const data = await request.get(`/api/works/${workId}`);
  882. if (!data) return;
  883. selectedWorkBase.value = data;
  884. // 基础信息补齐:以 works 表为准(如果 works 缺失字段则回退到列表行)
  885. if (selectedWork.value) {
  886. selectedWork.value = {
  887. ...selectedWork.value,
  888. title: data.title || selectedWork.value.title,
  889. publishTime: data.publishTime || selectedWork.value.publishTime,
  890. coverUrl: data.coverUrl || selectedWork.value.coverUrl,
  891. };
  892. }
  893. // 顶部卡片:按需求展示 works.yesterday_*(昨日快照)
  894. workDetailData.value = {
  895. playCount: toIntSafe(data.yesterdayPlayCount ?? 0),
  896. exposureCount: toIntSafe(data.yesterdayExposureCount ?? 0),
  897. totalWatchDuration: formatDurationSeconds(data.yesterdayTotalWatchDuration ?? 0),
  898. likeCount: toIntSafe(data.yesterdayLikeCount ?? 0),
  899. commentCount: toIntSafe(data.yesterdayCommentCount ?? 0),
  900. collectCount: toIntSafe(data.yesterdayCollectCount ?? 0),
  901. shareCount: toIntSafe(data.yesterdayShareCount ?? 0),
  902. fansIncrease: toIntSafe(data.yesterdayFansIncrease ?? 0),
  903. followCount: toIntSafe(data.yesterdayFollowCount ?? 0),
  904. recommendCount: toIntSafe(data.yesterdayRecommendCount ?? 0),
  905. coverClickRate: String(data.yesterdayCoverClickRate ?? '0'),
  906. avgWatchDuration: String(data.yesterdayAvgWatchDuration ?? '0'),
  907. completionRate: String(data.yesterdayCompletionRate ?? '0'),
  908. twoSecondExitRate: String(data.yesterdayTwoSecondExitRate ?? '0'),
  909. completionRate5s: String(data.yesterdayCompletionRate5s ?? '0'),
  910. };
  911. } catch (error) {
  912. // works 表请求失败不影响后续趋势展示
  913. console.warn('加载作品基础信息失败:', error);
  914. }
  915. }
  916. // 加载作品详情数据(历史统计数据)
  917. async function loadWorkDetail(workId: number) {
  918. detailLoading.value = true;
  919. try {
  920. // 趋势固定:近 14 天(按 work_day_statistics 日新增量口径)
  921. const { start: startDateStr, end: endDateStr } = calcDetailRangeDatesFixed14Days();
  922. // 调用接口获取该作品的历史统计数据(work_day_statistics 快照)
  923. const data = await request.get(`/api/work-day-statistics/work/${workId}`, {
  924. params: {
  925. // 注意:后端校验参数名为 startDate/endDate
  926. startDate: startDateStr,
  927. endDate: endDateStr,
  928. },
  929. });
  930. if (data && Array.isArray(data)) {
  931. const workStats = data;
  932. workStatsHistory.value = workStats;
  933. // 绘制趋势图(按天新增量)
  934. await nextTick();
  935. updatePlayTrendChart(workStats);
  936. }
  937. } catch (error) {
  938. console.error('加载作品详情失败:', error);
  939. ElMessage.error('加载作品详情失败,请稍后重试');
  940. } finally {
  941. detailLoading.value = false;
  942. }
  943. }
  944. // 更新播放量趋势图
  945. function updatePlayTrendChart(stats: Array<any>) {
  946. if (!playTrendChartRef.value) return;
  947. if (!playTrendChart) {
  948. playTrendChart = echarts.init(playTrendChartRef.value);
  949. }
  950. // 按日期排序
  951. const sortedStats = [...stats].sort((a, b) =>
  952. dayjs(a.recordDate).valueOf() - dayjs(b.recordDate).valueOf()
  953. );
  954. const dates = sortedStats.map(s => dayjs(s.recordDate).format('YYYY-MM-DD'));
  955. const metric = activeTrendMetric.value;
  956. const seriesName = trendTitle.value.replace('趋势', '');
  957. const isRateMetric =
  958. metric === 'coverClickRate' || metric === 'completionRate' || metric === 'twoSecondExitRate';
  959. const isDurationMetric = metric === 'avgWatchDuration' || metric === 'totalWatchDuration';
  960. const values = sortedStats.map((s) => {
  961. const v = s?.[metric];
  962. if (isRateMetric) {
  963. const raw = String(v ?? '0').trim();
  964. if (raw.includes('%')) return Number(raw.replace('%', '')) || 0;
  965. const n = Number(raw);
  966. if (Number.isNaN(n)) return 0;
  967. return n <= 1 ? n * 100 : n;
  968. }
  969. if (metric === 'avgWatchDuration') {
  970. return Math.max(0, Math.round(parseFloat(String(v ?? '0')) || 0));
  971. }
  972. if (metric === 'totalWatchDuration') {
  973. return Math.max(0, parseInt(String(v ?? '0'), 10) || 0);
  974. }
  975. return Number(v) || 0;
  976. });
  977. const option: echarts.EChartsOption = {
  978. tooltip: {
  979. trigger: 'axis',
  980. axisPointer: {
  981. type: 'cross',
  982. },
  983. formatter: (params: any) => {
  984. const arr = Array.isArray(params) ? params : [params];
  985. if (arr.length === 0) return '';
  986. const dateLabel = arr[0]?.axisValueLabel || arr[0]?.axisValue || '';
  987. const lines: string[] = [`${dateLabel}`];
  988. for (const p of arr) {
  989. const name = p?.seriesName ?? '';
  990. const val = typeof p?.data === 'number' ? p.data : Number(p?.data ?? 0);
  991. if (isRateMetric) {
  992. lines.push(`${name}:${(Number.isFinite(val) ? val : 0).toFixed(2).replace(/\.00$/, '')}%`);
  993. } else if (isDurationMetric) {
  994. lines.push(`${name}:${formatDurationSeconds(Number.isFinite(val) ? Math.round(val) : 0)}`);
  995. } else {
  996. lines.push(`${name}:${formatNumber(Number.isFinite(val) ? val : 0)}`);
  997. }
  998. }
  999. return lines.join('<br/>');
  1000. },
  1001. },
  1002. grid: {
  1003. left: '3%',
  1004. right: '4%',
  1005. bottom: '3%',
  1006. containLabel: true,
  1007. },
  1008. xAxis: {
  1009. type: 'category',
  1010. boundaryGap: false,
  1011. data: dates,
  1012. axisLabel: {
  1013. formatter: (value: string) => {
  1014. return dayjs(value).format('MM-DD');
  1015. },
  1016. },
  1017. },
  1018. yAxis: {
  1019. type: 'value',
  1020. axisLabel: {
  1021. formatter: (value: number) => {
  1022. if (isRateMetric) {
  1023. const n = Number.isFinite(value) ? value : 0;
  1024. return `${n.toFixed(2).replace(/\.00$/, '')}%`;
  1025. }
  1026. if (isDurationMetric) {
  1027. return formatDurationSeconds(Number.isFinite(value) ? Math.round(value) : 0);
  1028. }
  1029. if (value >= 10000) return (value / 10000).toFixed(1) + '万';
  1030. return String(value);
  1031. },
  1032. },
  1033. },
  1034. series: [
  1035. {
  1036. name: seriesName || '趋势',
  1037. type: 'line',
  1038. smooth: true,
  1039. data: values,
  1040. itemStyle: {
  1041. color: '#ff6b9d',
  1042. },
  1043. areaStyle: {
  1044. color: {
  1045. type: 'linear',
  1046. x: 0,
  1047. y: 0,
  1048. x2: 0,
  1049. y2: 1,
  1050. colorStops: [
  1051. { offset: 0, color: 'rgba(255, 107, 157, 0.3)' },
  1052. { offset: 1, color: 'rgba(255, 107, 157, 0.05)' },
  1053. ],
  1054. },
  1055. },
  1056. },
  1057. ],
  1058. };
  1059. playTrendChart.setOption(option, true);
  1060. }
  1061. // 监听弹窗关闭,清理图表
  1062. watch(drawerVisible, (visible) => {
  1063. if (!visible && playTrendChart) {
  1064. playTrendChart.dispose();
  1065. playTrendChart = null;
  1066. }
  1067. });
  1068. // 导出数据(按当前筛选条件导出作品列表)
  1069. async function handleExport() {
  1070. try {
  1071. const baseUrl = serverStore.currentServer?.url;
  1072. if (!baseUrl) {
  1073. ElMessage.error('未连接服务器');
  1074. return;
  1075. }
  1076. if (!authStore.accessToken) {
  1077. ElMessage.error('未连接服务器或未登录');
  1078. return;
  1079. }
  1080. const params = new URLSearchParams();
  1081. params.set('startDate', startDate.value);
  1082. params.set('endDate', endDate.value);
  1083. if (selectedPlatform.value) params.set('platform', selectedPlatform.value);
  1084. if (selectedAccounts.value.length > 0) params.set('accountIds', selectedAccounts.value.join(','));
  1085. if (selectedGroup.value) params.set('groupId', String(selectedGroup.value));
  1086. if (searchKeyword.value) params.set('keyword', searchKeyword.value);
  1087. params.set('sortBy', sortBy.value);
  1088. const url = `${baseUrl}/api/work-day-statistics/works/export?${params.toString()}`;
  1089. const doFetch = async (token: string) => {
  1090. return await fetch(url, {
  1091. method: 'GET',
  1092. headers: { Authorization: `Bearer ${token}` },
  1093. });
  1094. };
  1095. let resp = await doFetch(authStore.accessToken!);
  1096. if (resp.status === 401) {
  1097. const refreshed = await authStore.refreshAccessToken();
  1098. if (!refreshed || !authStore.accessToken) {
  1099. ElMessage.error('登录已过期,请重新登录');
  1100. return;
  1101. }
  1102. resp = await doFetch(authStore.accessToken!);
  1103. }
  1104. if (!resp.ok) {
  1105. const text = await resp.text().catch(() => '');
  1106. throw new Error(text || `导出失败,状态码:${resp.status}`);
  1107. }
  1108. const blob = await resp.blob();
  1109. const downloadUrl = window.URL.createObjectURL(blob);
  1110. const a = document.createElement('a');
  1111. a.href = downloadUrl;
  1112. a.download = `作品数据_${dayjs().format('YYYYMMDD_HHmmss')}.xlsx`;
  1113. document.body.appendChild(a);
  1114. a.click();
  1115. a.remove();
  1116. window.URL.revokeObjectURL(downloadUrl);
  1117. ElMessage.success('导出成功');
  1118. } catch (error: any) {
  1119. console.error('导出失败:', error);
  1120. ElMessage.error(error?.message || '导出失败');
  1121. }
  1122. }
  1123. onMounted(() => {
  1124. loadAccountList();
  1125. loadGroups();
  1126. loadData();
  1127. });
  1128. </script>
  1129. <style lang="scss" scoped>
  1130. @use '@/styles/variables.scss' as *;
  1131. .work-analytics {
  1132. .filter-bar {
  1133. display: flex;
  1134. align-items: center;
  1135. justify-content: space-between;
  1136. margin-bottom: 20px;
  1137. padding: 16px 20px;
  1138. background: #fff;
  1139. border-radius: $radius-lg;
  1140. box-shadow: $shadow-sm;
  1141. &.secondary {
  1142. margin-bottom: 16px;
  1143. padding: 12px 20px;
  1144. }
  1145. .filter-left {
  1146. display: flex;
  1147. align-items: center;
  1148. gap: 12px;
  1149. .filter-label {
  1150. font-size: 14px;
  1151. color: $text-regular;
  1152. }
  1153. .quick-btns {
  1154. display: flex;
  1155. gap: 8px;
  1156. }
  1157. }
  1158. }
  1159. .stats-row {
  1160. display: grid;
  1161. grid-template-columns: repeat(7, 1fr);
  1162. gap: 0;
  1163. margin-bottom: 20px;
  1164. background: #fff;
  1165. border-radius: $radius-lg;
  1166. box-shadow: $shadow-sm;
  1167. overflow: hidden;
  1168. .stat-card {
  1169. padding: 20px 16px;
  1170. display: flex;
  1171. align-items: center;
  1172. gap: 12px;
  1173. border-right: 1px solid #f0f0f0;
  1174. &:last-child {
  1175. border-right: none;
  1176. }
  1177. .stat-icon {
  1178. width: 36px;
  1179. height: 36px;
  1180. background: $primary-color-light;
  1181. border-radius: 8px;
  1182. display: flex;
  1183. align-items: center;
  1184. justify-content: center;
  1185. color: $primary-color;
  1186. flex-shrink: 0;
  1187. }
  1188. .stat-info {
  1189. .stat-label {
  1190. font-size: 12px;
  1191. color: $text-secondary;
  1192. margin-bottom: 4px;
  1193. white-space: nowrap;
  1194. }
  1195. .stat-value {
  1196. font-size: 20px;
  1197. font-weight: 600;
  1198. color: $text-primary;
  1199. }
  1200. }
  1201. }
  1202. }
  1203. .data-table {
  1204. background: #fff;
  1205. border-radius: $radius-lg;
  1206. box-shadow: $shadow-sm;
  1207. overflow: hidden;
  1208. .account-cell {
  1209. display: flex;
  1210. align-items: center;
  1211. gap: 8px;
  1212. .account-name {
  1213. font-weight: 500;
  1214. color: $text-primary;
  1215. }
  1216. }
  1217. .title-cell {
  1218. .work-title {
  1219. font-weight: 500;
  1220. color: $primary-color;
  1221. margin-bottom: 6px;
  1222. cursor: pointer;
  1223. &:hover {
  1224. text-decoration: underline;
  1225. }
  1226. }
  1227. .work-stats {
  1228. display: flex;
  1229. gap: 16px;
  1230. font-size: 12px;
  1231. color: $text-secondary;
  1232. .stat-item {
  1233. em {
  1234. font-style: normal;
  1235. color: $primary-color;
  1236. margin-left: 2px;
  1237. }
  1238. }
  1239. }
  1240. }
  1241. .publish-time {
  1242. font-size: 13px;
  1243. color: $text-secondary;
  1244. }
  1245. .pagination-wrapper {
  1246. padding: 16px 20px;
  1247. display: flex;
  1248. justify-content: flex-end;
  1249. }
  1250. }
  1251. }
  1252. :deep(.work-detail-dialog) {
  1253. .el-dialog__header {
  1254. padding-bottom: 0;
  1255. }
  1256. .el-dialog__body {
  1257. padding-top: 20px;
  1258. }
  1259. }
  1260. .work-detail {
  1261. .detail-header {
  1262. margin-bottom: 24px;
  1263. padding-bottom: 16px;
  1264. border-bottom: 1px solid #f0f0f0;
  1265. .work-title {
  1266. margin: 0 0 8px 0;
  1267. font-size: 18px;
  1268. font-weight: 600;
  1269. color: $text-primary;
  1270. }
  1271. .publish-time {
  1272. font-size: 14px;
  1273. color: $text-secondary;
  1274. }
  1275. }
  1276. .detail-tabs {
  1277. :deep(.el-tabs__header) {
  1278. margin-bottom: 24px;
  1279. }
  1280. :deep(.el-tabs__item) {
  1281. font-size: 15px;
  1282. font-weight: 500;
  1283. }
  1284. }
  1285. .core-data-content {
  1286. .traffic-data {
  1287. margin-bottom: 32px;
  1288. .section-title-row {
  1289. display: flex;
  1290. align-items: center;
  1291. justify-content: space-between;
  1292. gap: 12px;
  1293. margin-bottom: 16px;
  1294. }
  1295. .section-title {
  1296. margin: 0;
  1297. font-size: 16px;
  1298. font-weight: 600;
  1299. color: $text-primary;
  1300. }
  1301. .detail-range {
  1302. display: flex;
  1303. gap: 8px;
  1304. flex-wrap: wrap;
  1305. justify-content: flex-end;
  1306. }
  1307. .data-cards {
  1308. display: grid;
  1309. grid-template-columns: repeat(7, 1fr);
  1310. gap: 16px;
  1311. @media (max-width: 1400px) {
  1312. grid-template-columns: repeat(4, 1fr);
  1313. }
  1314. @media (max-width: 900px) {
  1315. grid-template-columns: repeat(3, 1fr);
  1316. }
  1317. @media (max-width: 600px) {
  1318. grid-template-columns: repeat(2, 1fr);
  1319. }
  1320. .data-card {
  1321. background: #f8fafc;
  1322. border-radius: 8px;
  1323. padding: 20px 16px;
  1324. text-align: center;
  1325. border: 1px solid #e5e7eb;
  1326. cursor: pointer;
  1327. &.highlight {
  1328. background: #fff5f7;
  1329. border-color: #ff6b9d;
  1330. .card-value {
  1331. color: #ff6b9d;
  1332. font-weight: 700;
  1333. }
  1334. }
  1335. .card-label {
  1336. font-size: 13px;
  1337. color: $text-secondary;
  1338. margin-bottom: 8px;
  1339. }
  1340. .card-value {
  1341. font-size: 24px;
  1342. font-weight: 600;
  1343. color: $text-primary;
  1344. line-height: 1.2;
  1345. }
  1346. }
  1347. }
  1348. }
  1349. .trend-section {
  1350. .section-title {
  1351. margin: 0 0 16px 0;
  1352. font-size: 16px;
  1353. font-weight: 600;
  1354. color: $text-primary;
  1355. }
  1356. }
  1357. }
  1358. }
  1359. @media (max-width: 1400px) {
  1360. .work-analytics {
  1361. .stats-row {
  1362. grid-template-columns: repeat(4, 1fr);
  1363. .stat-card {
  1364. &:nth-child(4) {
  1365. border-right: none;
  1366. }
  1367. &:nth-child(n+5) {
  1368. border-top: 1px solid #f0f0f0;
  1369. }
  1370. }
  1371. }
  1372. }
  1373. }
  1374. @media (max-width: 1200px) {
  1375. .work-analytics {
  1376. .filter-bar {
  1377. flex-direction: column;
  1378. align-items: flex-start;
  1379. gap: 12px;
  1380. .filter-left {
  1381. flex-wrap: wrap;
  1382. }
  1383. }
  1384. .stats-row {
  1385. grid-template-columns: repeat(3, 1fr);
  1386. .stat-card {
  1387. &:nth-child(3n) {
  1388. border-right: none;
  1389. }
  1390. &:nth-child(n+4) {
  1391. border-top: 1px solid #f0f0f0;
  1392. }
  1393. }
  1394. }
  1395. }
  1396. }
  1397. </style>