ertonglianxibiao/pages/detail/detail.js

389 lines
10 KiB
JavaScript
Raw Normal View History

2026-01-14 15:33:15 +08:00
import { injectPage } from '@jdmini/api'
const { getWorksheetDetail, checkPoints, deductPoints } = require('../../utils/api.js')
const { DATA_BASE_URL } = require('../../utils/config.js')
Page(injectPage({})({
data: {
dataBaseUrl: DATA_BASE_URL,
id: null,
detail: {},
recommended: [],
loading: false,
downloadedPath: ''
},
onLoad(options) {
if (options.id) {
this.setData({ id: Number(options.id) })
this.loadDetail()
}
},
onShareAppMessage() {
const userId = wx.getStorageSync('userId')
let path = `/pages/detail/detail?id=${this.data.id}`
// 携带邀请人ID
if (userId) {
path += `&inviter=${userId}`
}
return {
title: this.data.detail.title || '儿童练习表',
path: path,
imageUrl: DATA_BASE_URL + this.data.detail.coverurl
}
},
// 加载详情
async loadDetail() {
try {
this.setData({ loading: true })
const res = await getWorksheetDetail(this.data.id)
if (res.success) {
// 设置导航栏标题
wx.setNavigationBarTitle({
title: res.data.detail.title || '练习表详情'
})
this.setData({
detail: res.data.detail || {},
recommended: res.data.recommended || [],
loading: false
})
}
} catch (error) {
console.error('加载详情失败:', error)
this.setData({ loading: false })
wx.showToast({
title: '加载失败',
icon: 'none'
})
}
},
// 预览封面大图
previewImage() {
const url = DATA_BASE_URL + this.data.detail.coverurl
wx.previewImage({
current: url,
urls: [url]
})
},
// 预览PDF
previewPdf() {
const pdfUrl = DATA_BASE_URL + this.data.detail.pdfurl
wx.showLoading({
title: '加载中...',
mask: true
})
// 先下载PDF文件
wx.downloadFile({
url: pdfUrl,
success: (res) => {
wx.hideLoading()
if (res.statusCode === 200) {
// 打开PDF文档
wx.openDocument({
filePath: res.tempFilePath,
fileType: 'pdf',
showMenu: true,
success: () => {
console.log('PDF打开成功')
},
fail: (err) => {
console.error('打开PDF失败:', err)
wx.showToast({
title: '打开失败',
icon: 'none'
})
}
})
}
},
fail: (err) => {
wx.hideLoading()
console.error('下载PDF失败:', err)
wx.showToast({
title: '加载失败',
icon: 'none'
})
}
})
},
// 检查是否已下载过
hasDownloaded(worksheetId) {
const downloads = wx.getStorageSync('downloads') || []
return downloads.some(d => d.id === worksheetId)
},
// 下载PDF
async downloadPdf() {
// 1. 检查是否登录
const userId = wx.getStorageSync('userId')
if (!userId) {
wx.showModal({
title: '提示',
content: '请先登录后再下载',
confirmText: '去登录',
cancelText: '取消',
success: (res) => {
if (res.confirm) {
// 保存返回信息
wx.setStorageSync('returnTo', {
type: 'navigateTo',
url: `/pages/detail/detail?id=${this.data.id}`
})
wx.navigateTo({
url: '/pages/login/login'
})
}
}
})
return
}
// 2. 检查是否已下载过(已下载过的不扣积分)
const alreadyDownloaded = this.hasDownloaded(this.data.id)
// 3. 如果未下载过,检查积分
if (!alreadyDownloaded) {
try {
const pointsRes = await checkPoints(userId)
if (!pointsRes.success || !pointsRes.data.canDownload) {
wx.showModal({
title: '积分不足',
content: `下载需要 ${pointsRes.data?.costPoints || 1} 积分,您当前积分为 ${pointsRes.data?.points || 0}。分享小程序可获得积分!`,
confirmText: '去分享',
cancelText: '取消',
success: (res) => {
if (res.confirm) {
// 触发分享
this.shareToGetPoints()
}
}
})
return
}
} catch (error) {
console.error('检查积分失败:', error)
wx.showToast({
title: '网络错误',
icon: 'none'
})
return
}
}
// 4. 开始下载
const pdfUrl = DATA_BASE_URL + this.data.detail.pdfurl
const title = this.data.detail.e_title || this.data.detail.title || 'worksheet'
const fileName = `${title}.pdf`
wx.showLoading({
title: '下载中...',
mask: true
})
try {
let remainingPoints = null
// 只有首次下载才扣积分
if (!alreadyDownloaded) {
const deductRes = await deductPoints(userId, this.data.id)
if (!deductRes.success) {
wx.hideLoading()
wx.showToast({
title: deductRes.message || '扣除积分失败',
icon: 'none'
})
return
}
remainingPoints = deductRes.data.remainingPoints
}
// 下载文件
wx.downloadFile({
url: pdfUrl,
success: (res) => {
wx.hideLoading()
if (res.statusCode === 200) {
const tempFilePath = res.tempFilePath
// 保存到本地
const fs = wx.getFileSystemManager()
const savedPath = `${wx.env.USER_DATA_PATH}/${fileName}`
fs.saveFile({
tempFilePath: tempFilePath,
filePath: savedPath,
success: (saveRes) => {
this.setData({ downloadedPath: saveRes.savedFilePath })
// 保存下载记录
this.saveDownloadRecord()
// 根据是否是首次下载显示不同提示
let content = '文件已保存,是否立即打开?'
if (!alreadyDownloaded && remainingPoints !== null) {
content = `文件已保存消耗1积分剩余${remainingPoints}积分。是否立即打开?`
} else if (alreadyDownloaded) {
content = '文件已保存(已购买,无需扣分)。是否立即打开?'
}
wx.showModal({
title: '下载成功',
content: content,
confirmText: '打开',
cancelText: '稍后',
success: (modalRes) => {
if (modalRes.confirm) {
wx.openDocument({
filePath: saveRes.savedFilePath,
fileType: 'pdf',
showMenu: true
})
}
}
})
},
fail: (err) => {
console.error('保存文件失败:', err)
// 如果保存失败,直接打开临时文件
wx.showModal({
title: '下载成功',
content: '是否立即打开?',
confirmText: '打开',
cancelText: '稍后',
success: (modalRes) => {
if (modalRes.confirm) {
wx.openDocument({
filePath: tempFilePath,
fileType: 'pdf',
showMenu: true
})
}
}
})
}
})
}
},
fail: (err) => {
wx.hideLoading()
console.error('下载失败:', err)
wx.showToast({
title: '下载失败',
icon: 'none'
})
}
})
} catch (error) {
wx.hideLoading()
console.error('下载失败:', error)
}
},
// 分享获取积分
shareToGetPoints() {
wx.showToast({
title: '点击右上角分享给好友',
icon: 'none',
duration: 2000
})
},
// 保存下载记录
saveDownloadRecord() {
try {
const downloads = wx.getStorageSync('downloads') || []
const record = {
id: this.data.id,
title: this.data.detail.title,
e_title: this.data.detail.e_title,
coverurl: this.data.detail.coverurl,
pdfurl: this.data.detail.pdfurl,
category_name: this.data.detail.category_name,
downloadTime: Date.now(),
filePath: this.data.downloadedPath
}
// 检查是否已存在
const existIndex = downloads.findIndex(d => d.id === record.id)
if (existIndex > -1) {
downloads[existIndex] = record
} else {
downloads.unshift(record)
}
// 最多保存100条
if (downloads.length > 100) {
downloads.pop()
}
wx.setStorageSync('downloads', downloads)
} catch (error) {
console.error('保存下载记录失败:', error)
}
},
// 打印PDF
printPdf() {
const pdfUrl = DATA_BASE_URL + this.data.detail.pdfurl
wx.showLoading({
title: '准备打印...',
mask: true
})
// 先下载PDF
wx.downloadFile({
url: pdfUrl,
success: (res) => {
wx.hideLoading()
if (res.statusCode === 200) {
// 微信小程序没有直接打印API引导用户通过打开文档后使用系统打印
wx.openDocument({
filePath: res.tempFilePath,
fileType: 'pdf',
showMenu: true,
success: () => {
wx.showToast({
title: '请点击右上角菜单进行打印',
icon: 'none',
duration: 3000
})
},
fail: (err) => {
console.error('打开PDF失败:', err)
wx.showToast({
title: '打开失败',
icon: 'none'
})
}
})
}
},
fail: (err) => {
wx.hideLoading()
console.error('下载失败:', err)
wx.showToast({
title: '加载失败',
icon: 'none'
})
}
})
},
// 跳转到其他详情
goDetail(e) {
const id = e.currentTarget.dataset.id
wx.redirectTo({
url: `/pages/detail/detail?id=${id}`
})
}
}))