import dayjs from 'dayjs'; // 下载并打开文档 function downloadFileAndOpen(url) { wx.downloadFile({ url: url, success: function (res) { wx.hideLoading(); const filePath = res.tempFilePath; wx.openDocument({ filePath: filePath, success: function (res) { const time = dayjs().format(); wx.setStorage({ key: url, data: { filePath, time }, }); }, }); }, }); } // 打开office文档 function openDoc(url) { wx.showLoading({ title: '加载中', icom: 'none', mask: true, }); wx.getStorage({ key: url, success: res => { wx.hideLoading(); const { filePath, time } = res.data; // console.log(filePath, time); if (filePath && time) { const now = dayjs(); const past = dayjs(time); const diffDay = now.diff(past, 'day'); // console.log('diffDay:', diffDay); if (diffDay > 2) { downloadFileAndOpen(url); } else { wx.openDocument({ filePath: filePath, fail: err => { downloadFileAndOpen(url); }, }); } } else { downloadFileAndOpen(url); } }, fail: err => { downloadFileAndOpen(url); }, }); } const FILETYPE = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf']; function getSuffix(path) { return path.substring(path.lastIndexOf('.') + 1); } function isOfficeFile(path) { const suffix = getSuffix(path); return FILETYPE.indexOf(suffix) != -1; } export { openDoc, isOfficeFile, getSuffix };