ertonglianxibiao/pages/download/download.js

151 lines
3.5 KiB
JavaScript

import { injectPage } from '@jdmini/api'
const { DATA_BASE_URL } = require('../../utils/config.js')
Page(injectPage({})({
data: {
dataBaseUrl: DATA_BASE_URL,
downloads: []
},
onShow() {
this.loadDownloads()
},
// 加载下载记录
loadDownloads() {
try {
const downloads = wx.getStorageSync('downloads') || []
// 格式化时间
const formattedDownloads = downloads.map(item => ({
...item,
downloadTimeStr: this.formatTime(item.downloadTime)
}))
this.setData({ downloads: formattedDownloads })
} catch (error) {
console.error('加载下载记录失败:', error)
}
},
// 格式化时间
formatTime(timestamp) {
const date = new Date(timestamp)
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
const hours = String(date.getHours()).padStart(2, '0')
const minutes = String(date.getMinutes()).padStart(2, '0')
return `${year}-${month}-${day} ${hours}:${minutes}`
},
// 打开文件
openFile(e) {
const index = e.currentTarget.dataset.index
const item = this.data.downloads[index]
if (item.filePath) {
// 尝试打开已保存的文件
wx.openDocument({
filePath: item.filePath,
fileType: 'pdf',
showMenu: true,
fail: (err) => {
console.error('打开文件失败:', err)
// 文件可能被删除,重新下载
this.redownload(item)
}
})
} else {
// 没有本地文件,重新下载
this.redownload(item)
}
},
// 重新下载
redownload(item) {
const pdfUrl = DATA_BASE_URL + item.pdfurl
wx.showLoading({
title: '加载中...',
mask: true
})
wx.downloadFile({
url: pdfUrl,
success: (res) => {
wx.hideLoading()
if (res.statusCode === 200) {
wx.openDocument({
filePath: res.tempFilePath,
fileType: 'pdf',
showMenu: true
})
}
},
fail: () => {
wx.hideLoading()
wx.showToast({
title: '加载失败',
icon: 'none'
})
}
})
},
// 删除下载记录
deleteItem(e) {
const index = e.currentTarget.dataset.index
const item = this.data.downloads[index]
wx.showModal({
title: '提示',
content: '确定删除此下载记录吗?',
success: (res) => {
if (res.confirm) {
// 删除本地文件
if (item.filePath) {
try {
const fs = wx.getFileSystemManager()
fs.unlinkSync(item.filePath)
} catch (error) {
console.log('删除文件失败或文件不存在')
}
}
// 更新记录
const downloads = this.data.downloads.filter((_, i) => i !== index)
this.setData({ downloads })
// 更新存储
const storageData = downloads.map(d => {
const { downloadTimeStr, ...rest } = d
return rest
})
wx.setStorageSync('downloads', storageData)
wx.showToast({
title: '已删除',
icon: 'success'
})
}
}
})
},
// 跳转详情
goDetail(e) {
const id = e.currentTarget.dataset.id
wx.navigateTo({
url: `/pages/detail/detail?id=${id}`
})
},
// 去浏览
goHome() {
wx.switchTab({
url: '/pages/index/index'
})
}
}))