article-detail.vue 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. <template>
  2. <view class="detail-container">
  3. <view v-if="loading" class="loading-wrap">
  4. <view class="loading-spinner"></view>
  5. <text class="loading-text">加载中...</text>
  6. </view>
  7. <view v-else-if="error" class="error-wrap">
  8. <text class="error-icon">📄</text>
  9. <text class="error-text">{{ errorMsg }}</text>
  10. <button class="retry-btn" @click="loadDetail(articleId)">重新加载</button>
  11. </view>
  12. <template v-else-if="article">
  13. <scroll-view scroll-y class="content-scroll" @scrolltolower="onScrollToBottom">
  14. <image v-if="article.coverImage" class="detail-cover" :src="article.coverImage" mode="widthFix" />
  15. <text class="detail-title">{{ article.title }}</text>
  16. <view class="detail-meta">
  17. <text class="meta-author">{{ article.author || '浠艾福' }}</text>
  18. <text class="meta-sep">|</text>
  19. <text class="meta-date">{{ formatDate(article.publishedAt) }}</text>
  20. <text class="meta-sep">|</text>
  21. <text class="meta-readtime">{{ article.readTime || 3 }}分钟阅读</text>
  22. <text class="reading-time-badge" v-if="currentChildId && !readingCompleted">{{ formatReadingTime(readingSeconds) }}</text>
  23. <text class="reading-time-badge completed" v-else-if="currentChildId && readingCompleted">✅ 阅读完成</text>
  24. <text class="meta-sep" v-if="currentChildId">|</text>
  25. <text class="meta-readcount">{{ article.viewCount || 0 }}人阅读</text>
  26. </view>
  27. <view class="detail-category-row">
  28. <text class="detail-category">{{ article.categoryName || '' }}</text>
  29. </view>
  30. <view v-if="article.relatedDimensions" class="detail-dimensions">
  31. <view v-for="dim in parseDimensions(article)" :key="dim.code" class="dim-bar-item">
  32. <view class="dim-bar" :style="{ background: dim.color, width: dim.weight + '%' }"></view>
  33. <text class="dim-label">{{ dim.name }}</text>
  34. </view>
  35. </view>
  36. <view class="divider"></view>
  37. <view class="detail-body"><mp-html :content="article.content" :domain="config.API_BASE_URL" /></view>
  38. <!-- 评论区(已屏蔽) -->
  39. <view style="height: 200rpx;"></view>
  40. </scroll-view>
  41. <!-- 底部 -->
  42. <view class="detail-footer">
  43. <view class="share-btn" @click="generatePoster">
  44. <text class="share-btn-icon">🖼</text>
  45. <text class="share-btn-text">生成海报</text>
  46. </view>
  47. </view>
  48. </template>
  49. <ContentSharePoster :show="showPoster" :title="(article && article.title) || ''" :coverImage="(article && article.coverImage) || ''" :qrCodeBase64="posterQrCode || ''" typeLabel="好文推荐" :dimensionCode="posterDimension || ''" :summary="posterSummary || ''" :inviteText="posterInviteText || ''" @close="closePoster" />
  50. <!-- 浠宝答题弹窗 -->
  51. <view class="quiz-mask" v-if="showQuiz" @click="closeQuiz">
  52. <view class="quiz-dialog" @click.stop>
  53. <view class="quiz-mascot">
  54. <text class="mascot-icon">{{ mascotIcon }}</text>
  55. <text class="mascot-name">{{ mascotName }}</text>
  56. </view>
  57. <text class="quiz-intro">阅读完成!考考你三个问题~</text>
  58. <view class="quiz-question" v-for="(q, qi) in quizQuestions" :key="qi">
  59. <text class="q-title">问题{{ qi+1 }}: {{ q.question }}</text>
  60. <view class="q-options">
  61. <text v-for="(opt, oi) in q.options" :key="oi" class="q-option" :class="{ selected: quizAnswers[qi] === String.fromCharCode(65 + oi) }" @click="selectQuizAnswer(qi, oi)">{{ opt }}</text>
  62. </view>
  63. </view>
  64. <button class="quiz-submit" @click="submitQuiz">提交答案</button>
  65. </view>
  66. </view>
  67. <!-- 答题结果 -->
  68. <view class="result-mask" v-if="showResult">
  69. <view class="result-dialog">
  70. <text class="result-icon">{{ resultIcon }}</text>
  71. <text class="result-text">答对 {{ quizResult.correctCount }}/{{ quizResult.totalQuestions }} 题</text>
  72. <text class="result-energy">获得 {{ quizResult.earnedEnergy }} 能量 ⚡</text>
  73. <button class="result-btn" @click="closeResult">知道了</button>
  74. </view>
  75. </view>
  76. </view>
  77. </template>
  78. <script>
  79. import { getArticleDetail, reportReadingTime, getShareQrCode, completeArticleRead, generateQuiz, submitQuiz, getMyMembership } from '@/utils/api.js'
  80. import shareMixin from '../../components/share-mixin.js'
  81. import ContentSharePoster from '@/components/ContentSharePoster.vue'
  82. import MpHtml from '@/components/mp-html/mp-html.vue'
  83. import config from '@/config.js'
  84. export default {
  85. mixins: [shareMixin],
  86. components: { ContentSharePoster, MpHtml },
  87. data() {
  88. return {
  89. articleId: '', article: null, loading: true, error: false, errorMsg: '',
  90. readingSeconds: 0, lastReportedSeconds: 0, readingCompleted: false,
  91. isTimerRunning: false, timerHandle: null, syncHandle: null,
  92. currentChildId: null,
  93. showPoster: false, posterQrCode: '',
  94. posterDimension: '', posterSummary: '', posterInviteText: '',
  95. // 答题
  96. showQuiz: false, quizQuestions: [], quizAnswers: [], showResult: false, quizResult: {},
  97. mascotList: [{ icon: '🐶', name: '浠宝' }, { icon: '🐼', name: '福宝' }],
  98. mascotIcon: '🐶', mascotName: '浠宝'
  99. }
  100. },
  101. computed: {},
  102. onLoad(options) {
  103. this.mascotIcon = this.mascotList[Math.floor(Math.random() * 2)].icon
  104. this.mascotName = this.mascotList[Math.floor(Math.random() * 2)].name
  105. // 兼容旧分享链接:refCode / inviteCode 参数(shareMixin onLoad 也会处理,此处显式兜底)
  106. if (options && (options.refCode || options.inviteCode)) {
  107. this.autoBindInviteCode(options.refCode || options.inviteCode)
  108. }
  109. var aid = ''
  110. if (options && options.id) {
  111. aid = options.id
  112. } else if (options && options.scene) {
  113. try {
  114. var sceneDecoded = decodeURIComponent(options.scene)
  115. var idMatch = sceneDecoded.match(/id=(\d+)/)
  116. if (idMatch && idMatch[1]) aid = idMatch[1]
  117. var refMatch = sceneDecoded.match(/ref=([^&]+)/)
  118. if (refMatch && refMatch[1]) this.autoBindInviteCode(refMatch[1])
  119. } catch (e) {}
  120. }
  121. if (aid) { this.articleId = aid; this.loadDetail(aid) }
  122. else { this.error = true; this.errorMsg = '参数错误'; this.loading = false }
  123. this.currentChildId = uni.getStorageSync('currentChildId') || null
  124. },
  125. onShow() {
  126. var memberId = uni.getStorageSync('currentChildId')
  127. if (!this.article || this.error || !memberId) return
  128. this.startNewReadingSession()
  129. },
  130. onHide() { this.pauseReadingTimer() },
  131. onUnload() { this.pauseReadingTimer() },
  132. methods: {
  133. async loadDetail(id) {
  134. this.loading = true; this.error = false
  135. try {
  136. var res = await getArticleDetail({ id: id })
  137. if (res.code === 200 && res.data) {
  138. this.article = res.data
  139. this.article.coverImage = this.getImageUrl(this.article.coverImage)
  140. this.article.content = this.resolveContentUrls(this.article.content)
  141. this.setShareInfo('推荐阅读: ' + (res.data.title || ''), '/pages/article-center/article-detail?id=' + id)
  142. this.startReadingTimer()
  143. } else { this.error = true; this.errorMsg = '文章不存在或无权限查看' }
  144. } catch (e) { this.error = true; this.errorMsg = '加载失败' }
  145. finally { this.loading = false }
  146. },
  147. formatDate(d) { return d ? d.slice(0, 10) : '' },
  148. getImageUrl: function(path) {
  149. if (!path) return ''
  150. if (path.indexOf('http://') === 0 || path.indexOf('https://') === 0) return path
  151. return config.API_BASE_URL + path
  152. },
  153. resolveContentUrls: function(html) {
  154. if (!html) return html
  155. // 将富文本内容中的相对图片路径(/uploads/...)拼接为绝对 URL
  156. return html.replace(/(src|href)=["']\/(uploads\/[^"']+)/g, function(match, attr, path) {
  157. return attr + '="' + config.API_BASE_URL + '/' + path + '"'
  158. })
  159. },
  160. parseDimensions: function(article) {
  161. var dimMap = { body: { code: 'body', color: '#FF8C42', name: '身' }, mind: { code: 'mind', color: '#FF6B9D', name: '心' }, wisdom: { code: 'wisdom', color: '#6366F1', name: '智' }, action: { code: 'action', color: '#10B981', name: '行' }, wealth: { code: 'wealth', color: '#F59E0B', name: '富' } }
  162. var raw = article && article.relatedDimensions ? article.relatedDimensions.split(',').map(function(s) { return s.trim().toLowerCase() }) : []
  163. var weights = null
  164. if (article && article.dimensionWeights) try { var w = JSON.parse(article.dimensionWeights); if (w && typeof w === 'object') weights = w } catch (e) {}
  165. if (!weights) {
  166. var n = raw.filter(function(c) { return dimMap[c] }).length
  167. if (n > 0) { var base = Math.floor(100 / n); var rem = 100 - base * n; weights = {}; var i = 0; raw.forEach(function(c) { if (!dimMap[c]) return; weights[c] = i < rem ? base + 1 : base; i++ }) }
  168. }
  169. return raw.filter(function(c) { return dimMap[c] }).map(function(c) { return { code: dimMap[c].code, name: dimMap[c].name, color: dimMap[c].color, weight: (weights && weights[c]) ? weights[c] : 20 } })
  170. },
  171. getMainDimension: function() {
  172. var dims = this.article ? this.parseDimensions(this.article) : []
  173. var best = null
  174. var i
  175. for (i = 0; i < dims.length; i++) {
  176. if (!best || dims[i].weight > best.weight) best = dims[i]
  177. }
  178. return best ? best.code : ''
  179. },
  180. onScrollToBottom() {},
  181. startNewReadingSession: function() {
  182. // 每次进入文章详情页都从 0 开始新会话,时长不延续上一次
  183. this.readingSeconds = 0
  184. this.lastReportedSeconds = 0
  185. this.startReadingTimer()
  186. },
  187. startReadingTimer: function() {
  188. var memberId = uni.getStorageSync('currentChildId')
  189. if (!memberId) return
  190. if (this.isTimerRunning || this.readingCompleted) return
  191. this.isTimerRunning = true
  192. var self = this
  193. this.timerHandle = setInterval(function() { self.readingSeconds++ }, 1000)
  194. // 每 10 秒自动记录一次该用户已读时长
  195. this.syncHandle = setInterval(function() { self.reportReadingTime() }, 10000)
  196. },
  197. pauseReadingTimer: function() {
  198. if (!this.isTimerRunning) return
  199. this.isTimerRunning = false
  200. if (this.timerHandle) { clearInterval(this.timerHandle); this.timerHandle = null }
  201. if (this.syncHandle) { clearInterval(this.syncHandle); this.syncHandle = null }
  202. this.reportReadingTime()
  203. },
  204. async reportReadingTime() {
  205. var delta = this.readingSeconds - this.lastReportedSeconds
  206. if (delta <= 0) return
  207. this.lastReportedSeconds = this.readingSeconds
  208. var memberId = uni.getStorageSync('currentChildId')
  209. if (!memberId || !this.article) return
  210. reportReadingTime({ articleId: this.article.id, memberId: parseInt(memberId), durationSeconds: delta })
  211. // 达到阅读时长自动完成
  212. var targetSeconds = (this.article.readTime || 3) * 60
  213. if (!this.readingCompleted && this.readingSeconds >= targetSeconds) {
  214. this.readingCompleted = true
  215. this.pauseReadingTimer()
  216. try { await completeArticleRead({ articleId: this.article.id, memberId: parseInt(memberId), durationSeconds: this.readingSeconds }) } catch (e) {}
  217. uni.showToast({ title: '阅读完成 +5能量', icon: 'success' })
  218. // 弹出答题
  219. this.startQuiz()
  220. }
  221. },
  222. formatReadingTime: function(seconds) {
  223. if (seconds < 60) return '已读 ' + seconds + '秒'
  224. var min = Math.floor(seconds / 60); var sec = seconds % 60
  225. return '已读 ' + min + '分' + (sec > 0 ? sec + '秒' : '')
  226. },
  227. async generatePoster() {
  228. if (!this.articleId) return
  229. uni.showLoading({ title: '生成海报中...' })
  230. try {
  231. if (!this.referralCode) {
  232. await this.loadReferralCode()
  233. }
  234. var scene = 'id=' + this.articleId + (this.referralCode ? '&ref=' + this.referralCode : '')
  235. if (scene.length > 32) {
  236. scene = scene.substring(0, 32)
  237. }
  238. var res = await getShareQrCode('pages/article-center/article-detail', scene)
  239. if (res && res.data) {
  240. this.posterQrCode = res.data.qrCodeBase64 || ''
  241. this.posterDimension = this.getMainDimension()
  242. this.posterSummary = (this.article && this.article.summary) || ''
  243. this.posterInviteText = '「' + (uni.getStorageSync('nickname') || '好友') + '」邀请你一起阅读这篇文章'
  244. this.showPoster = true
  245. }
  246. } catch (e) { uni.showToast({ title: '生成失败', icon: 'none' }) }
  247. finally { uni.hideLoading() }
  248. },
  249. // 答题
  250. async startQuiz() {
  251. try {
  252. var memRes = await getMyMembership()
  253. if (memRes.data && memRes.data.memberLevel && memRes.data.memberLevel === 'FREE') {
  254. uni.showToast({ title: '浠宝/福宝答题是会员专属', icon: 'none' })
  255. setTimeout(function() { uni.navigateTo({ url: '/pages/membership/upgrade' }) }, 1500)
  256. return
  257. }
  258. var res = await generateQuiz({ articleId: this.articleId })
  259. if (res.code === 200 && res.data && res.data.length > 0) {
  260. this.quizQuestions = res.data
  261. this.quizAnswers = []
  262. this.showQuiz = true
  263. }
  264. } catch (e) {}
  265. },
  266. async submitQuiz() {
  267. var correct = 0
  268. for (var i = 0; i < this.quizQuestions.length; i++) {
  269. if (this.quizAnswers[i] === this.quizQuestions[i].answer) correct++
  270. }
  271. var memberId = uni.getStorageSync('currentChildId')
  272. try {
  273. var res = await submitQuiz({ correctCount: correct, memberId: parseInt(memberId || 0) })
  274. if (res.code === 200) {
  275. this.quizResult = res.data || { correctCount: correct, totalQuestions: 3, earnedEnergy: correct * 5 }
  276. this.showQuiz = false
  277. this.showResult = true
  278. }
  279. } catch (e) {}
  280. },
  281. closePoster: function() {
  282. this.showPoster = false
  283. },
  284. closeQuiz: function() {
  285. this.showQuiz = false
  286. },
  287. closeResult: function() {
  288. this.showResult = false
  289. },
  290. selectQuizAnswer: function(qi, oi) {
  291. this.quizAnswers[qi] = String.fromCharCode(65 + oi)
  292. }
  293. }
  294. }
  295. </script>
  296. <style scoped>
  297. .detail-container { min-height: 100vh; background: #fff; }
  298. .loading-wrap { display: flex; flex-direction: column; align-items: center; padding-top: 300rpx; }
  299. .loading-spinner { width: 60rpx; height: 60rpx; border: 4rpx solid #e0e0e0; border-top-color: #5B9BD5; border-radius: 50%; animation: spin 0.8s linear infinite; margin-bottom: 20rpx; }
  300. @keyframes spin { 0% { transform: rotate(0deg); } 360% { transform: rotate(360deg); } }
  301. .loading-text { font-size: 26rpx; color: #999; }
  302. .error-wrap { display: flex; flex-direction: column; align-items: center; padding-top: 300rpx; }
  303. .error-icon { font-size: 100rpx; margin-bottom: 24rpx; }
  304. .error-text { font-size: 28rpx; color: #999; margin-bottom: 30rpx; }
  305. .retry-btn { width: 240rpx; height: 72rpx; line-height: 72rpx; background: #5B9BD5; color: #fff; font-size: 28rpx; border-radius: 36rpx; text-align: center; border: none; }
  306. .content-scroll { height: calc(100vh - 120rpx); }
  307. .detail-cover { width: 100%; display: block; }
  308. .detail-title { display: block; font-size: 36rpx; font-weight: bold; color: #333; line-height: 1.4; padding: 30rpx 30rpx 0; }
  309. .detail-meta { display: flex; align-items: center; padding: 16rpx 30rpx 0; font-size: 22rpx; color: #999; flex-wrap: wrap; }
  310. .meta-author { color: #5B9BD5; }
  311. .meta-sep { margin: 0 12rpx; color: #ddd; }
  312. .reading-time-badge { margin-left: auto; font-size: 20rpx; color: #5B9BD5; background: rgba(91,155,213,0.08); padding: 4rpx 12rpx; border-radius: 20rpx; white-space: nowrap; }
  313. .reading-time-badge.completed { color: #10B981; background: rgba(16,185,129,0.1); }
  314. .meta-readcount {
  315. font-size: 20rpx;
  316. color: #bbb;
  317. }
  318. .detail-category-row { padding: 16rpx 30rpx 0; }
  319. .detail-category { display: inline-block; font-size: 20rpx; color: #5B9BD5; background: rgba(91,155,213,0.1); padding: 4rpx 16rpx; border-radius: 8rpx; }
  320. .detail-dimensions { padding: 16rpx 30rpx 0; display: flex; gap: 12rpx; }
  321. .dim-bar-item { flex: 1; }
  322. .dim-bar { height: 8rpx; border-radius: 4rpx; }
  323. .dim-label { font-size: 18rpx; color: #999; text-align: center; display: block; margin-top: 4rpx; }
  324. .divider { height: 1rpx; background: #eee; margin: 24rpx 30rpx; }
  325. .detail-body { padding: 0 30rpx; font-size: 28rpx; color: #444; line-height: 1.8; }
  326. .detail-footer { position: fixed; bottom: 0; left: 0; right: 0; background: #fff; padding: 20rpx 30rpx; display: flex; align-items: center; gap: 16rpx; box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.06); z-index: 10; }
  327. .share-btn { height: 72rpx; padding: 0 30rpx; background: linear-gradient(135deg, #F97316, #FB923C); border-radius: 36rpx; display: flex; align-items: center; justify-content: center; border: none; }
  328. .share-btn::after { border: none; }
  329. .share-btn-icon { font-size: 30rpx; margin-right: 8rpx; }
  330. .share-btn-text { font-size: 26rpx; color: #fff; font-weight: 600; }
  331. /* 答题弹窗 */
  332. .quiz-mask, .result-mask { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 999; display: flex; align-items: center; justify-content: center; }
  333. .quiz-dialog, .result-dialog { background: #fff; border-radius: 24rpx; width: 650rpx; padding: 32rpx; }
  334. .quiz-mascot { display: flex; align-items: center; justify-content: center; gap: 12rpx; margin-bottom: 16rpx; }
  335. .mascot-icon { font-size: 60rpx; }
  336. .mascot-name { font-size: 32rpx; font-weight: 700; color: #F97316; }
  337. .quiz-intro { text-align: center; font-size: 28rpx; color: #666; margin-bottom: 24rpx; }
  338. .quiz-question { margin-bottom: 20rpx; }
  339. .q-title { font-size: 26rpx; font-weight: 600; color: #333; margin-bottom: 12rpx; }
  340. .q-options { display: flex; flex-direction: column; gap: 8rpx; }
  341. .q-option { padding: 14rpx 20rpx; border: 2rpx solid #E5E7EB; border-radius: 12rpx; font-size: 24rpx; color: #333; }
  342. .q-option.selected { border-color: #F97316; background: #FFF7ED; color: #92400E; }
  343. .quiz-submit, .result-btn { width: 100%; padding: 20rpx; background: linear-gradient(135deg, #F97316, #FB923C); color: #fff; font-size: 28rpx; border-radius: 12rpx; border: none; margin-top: 20rpx; }
  344. .result-dialog { text-align: center; }
  345. .result-icon { font-size: 80rpx; }
  346. .result-text { font-size: 32rpx; font-weight: 700; color: #333; margin: 16rpx 0; }
  347. .result-energy { font-size: 28rpx; color: #F97316; }
  348. </style>