// pages/collection/index.js const API = require('../../utils/api.js'); Page({ data: { qrCodes: [], // 二维码数据 invitees: [], // 邀请者列表 isAdmin: false, // 是否为管理员 activeFilter: 'all', // 当前激活的筛选条件 sidebarVisible: false, // 侧边栏是否可见 expandedIndex: -1, // 当前展开的二维码索引 searchKeyword: '' // 搜索关键词 }, onLoad: function (options) { // 页面加载时的初始化逻辑 console.log('二维码合集页面加载,options:', options); // 检查是否是通过内部按钮进入的 if (!options.from || options.from !== 'internal') { console.log('非内部进入,重定向到首页'); wx.redirectTo({ url: '/pages/index/index' }); return; } // 加载二维码合集 this.loadQrCollection(); }, onShow: function () { // 页面显示时重新加载数据 this.loadQrCollection(); }, // 加载用户信息 loadUserInfo: function () { return new Promise((resolve, reject) => { // 从本地存储获取用户信息 const userInfo = wx.getStorageSync('userInfo') || {}; // 获取电话号码信息 const phoneNumber = userInfo.phoneNumber || wx.getStorageSync('phoneNumber') || ''; // 如果有电话号码,查询personnel表获取详细信息 if (phoneNumber) { // 使用全局缓存方法获取业务员信息 const appInstance = getApp(); appInstance.getPersonnelInfo(phoneNumber).then(res => { console.log('查询personnel表结果:', res); if (res && res.success && res.data && res.data.length > 0) { const personnelInfo = res.data[0]; // 更新用户信息 const updatedUserInfo = { name: personnelInfo.name || userInfo.name || userInfo.userName || '微信用户', phoneNumber: phoneNumber, projectName: personnelInfo.projectName || '' }; // 存储到本地存储 wx.setStorageSync('userInfo', updatedUserInfo); resolve(updatedUserInfo); } else { // 如果查询失败,使用本地存储的用户信息 const fallbackUserInfo = { name: userInfo.name || userInfo.userName || '微信用户', phoneNumber: phoneNumber, projectName: userInfo.projectName || '' }; resolve(fallbackUserInfo); } }).catch(err => { console.error('查询personnel表失败:', err); // 如果查询失败,使用本地存储的用户信息 const fallbackUserInfo = { name: userInfo.name || userInfo.userName || '微信用户', phoneNumber: phoneNumber, projectName: userInfo.projectName || '' }; resolve(fallbackUserInfo); }); } else { // 如果没有电话号码,使用本地存储的用户信息 const fallbackUserInfo = { name: userInfo.name || userInfo.userName || '微信用户', phoneNumber: phoneNumber, projectName: userInfo.projectName || '' }; resolve(fallbackUserInfo); } }); }, // 将UTC时间转换为北京时间 convertToBeijingTime: function (utcTime) { if (!utcTime) return '未知'; // 创建Date对象 const date = new Date(utcTime); // 转换为北京时间(UTC+8) const beijingTime = new Date(date.getTime() + 8 * 60 * 60 * 1000); // 格式化时间 const year = beijingTime.getFullYear(); const month = String(beijingTime.getMonth() + 1).padStart(2, '0'); const day = String(beijingTime.getDate()).padStart(2, '0'); const hours = String(beijingTime.getHours()).padStart(2, '0'); const minutes = String(beijingTime.getMinutes()).padStart(2, '0'); const seconds = String(beijingTime.getSeconds()).padStart(2, '0'); return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; }, // 处理二维码数据,转换时间为北京时间 processQrCodes: function (qrCodes) { return qrCodes.map(qrCode => { const newQrCode = { ...qrCode }; // 转换创建时间 if (newQrCode.createdAt) { newQrCode.createdAt = this.convertToBeijingTime(newQrCode.createdAt); } // 转换签发日期 if (newQrCode.issueDate) { newQrCode.issueDate = this.convertToBeijingTime(newQrCode.issueDate); } return newQrCode; }); }, // 加载二维码合集 loadQrCollection: function () { this.loadUserInfo().then(user => { try { // 构建请求参数 let params = {}; if (user) { params.userName = user.name; params.phoneNumber = user.phoneNumber; params.projectName = user.projectName; } console.log('加载二维码合集,用户信息:', user); // 从服务器获取二维码合集 API.getQrCollection(params).then(res => { console.log('获取二维码合集结果:', res); if (res && res.success) { // 动态生成筛选按钮 if (res.isAdmin && res.invitees && res.invitees.length > 0) { this.setData({ isAdmin: res.isAdmin, invitees: res.invitees }); } if (res.qrCodes && res.qrCodes.length > 0) { // 处理二维码数据,转换时间为北京时间 const processedQrCodes = this.processQrCodes(res.qrCodes); // 渲染二维码合集 this.setData({ qrCodes: processedQrCodes }); } else { // 显示空状态 this.setData({ qrCodes: [] }); } } else { // 显示错误状态 wx.showToast({ title: '加载失败,请稍后重试', icon: 'none', duration: 2000 }); } }).catch(err => { console.error('获取二维码合集失败:', err); wx.showToast({ title: '加载失败,请稍后重试', icon: 'none', duration: 2000 }); }); } catch (error) { console.error('获取二维码合集失败:', error); wx.showToast({ title: '加载失败,请稍后重试', icon: 'none', duration: 2000 }); } }); }, // 打开筛选侧边栏 openSidebar: function () { this.setData({ sidebarVisible: true }); }, // 关闭筛选侧边栏 closeSidebar: function () { this.setData({ sidebarVisible: false }); }, // 切换展开/收起状态 toggleSection: function (e) { const index = e.currentTarget.dataset.index; this.setData({ expandedIndex: this.data.expandedIndex === index ? -1 : index }); }, // 切换筛选条件 switchFilter: function (e) { const filter = e.currentTarget.dataset.filter; this.setData({ activeFilter: filter }); this.filterQrCodes(filter, null, this.data.searchKeyword); }, // 按邀请者筛选 filterByInviter: function (e) { const filter = e.currentTarget.dataset.filter; const inviterName = e.currentTarget.dataset.inviter; this.setData({ activeFilter: filter }); this.filterQrCodes(filter, inviterName, this.data.searchKeyword); this.closeSidebar(); }, // 搜索输入事件 onSearchInput: function (e) { const searchKeyword = e.detail.value; this.setData({ searchKeyword: searchKeyword }); this.filterQrCodes(this.data.activeFilter, null, searchKeyword); }, // 筛选二维码 filterQrCodes: function (filter, inviterName, searchKeyword = '') { this.loadUserInfo().then(user => { // 构建请求参数 let params = {}; if (user) { params.userName = user.name; params.phoneNumber = user.phoneNumber; params.projectName = user.projectName; } console.log('筛选二维码,用户信息:', user); // 重新加载并筛选二维码 API.getQrCollection(params).then(res => { if (res && res.success && res.qrCodes && res.qrCodes.length > 0) { // 处理二维码数据,转换时间为北京时间 let filteredQrCodes = this.processQrCodes(res.qrCodes); if (filter === 'me' && user) { // 筛选当前用户自己的二维码 filteredQrCodes = filteredQrCodes.filter(qrCode => qrCode.inviter === user.name ); } else if (filter.startsWith('invitee_') && inviterName) { // 筛选特定邀请者的二维码 filteredQrCodes = filteredQrCodes.filter(qrCode => qrCode.inviter === inviterName ); } // 搜索功能 if (searchKeyword) { const keyword = searchKeyword.toLowerCase(); filteredQrCodes = filteredQrCodes.filter(qrCode => { return ( (qrCode.phoneNumber && qrCode.phoneNumber.toLowerCase().includes(keyword)) || (qrCode.company && qrCode.company.toLowerCase().includes(keyword)) ); }); // 添加高亮效果 filteredQrCodes = filteredQrCodes.map(qrCode => { const newQrCode = { ...qrCode }; if (newQrCode.company && newQrCode.company.toLowerCase().includes(keyword)) { const regex = new RegExp(`(${keyword})`, 'gi'); newQrCode.company = newQrCode.company.replace(regex, '$1'); } if (newQrCode.phoneNumber && newQrCode.phoneNumber.toLowerCase().includes(keyword)) { const regex = new RegExp(`(${keyword})`, 'gi'); newQrCode.phoneNumber = newQrCode.phoneNumber.replace(regex, '$1'); } return newQrCode; }); } this.setData({ qrCodes: filteredQrCodes }); } }).catch(error => { console.error('筛选二维码失败:', error); }); }); }, // 返回上一页 goBack: function () { wx.navigateBack({ delta: 1 }); }, // 跳转到生成邀请二维码页面 goToGenerate: function () { wx.redirectTo({ url: '/pages/qrcode/index?from=internal' }); }, // 图片加载成功事件 onImageLoad: function () { console.log('二维码图片加载成功'); }, // 图片加载失败事件 onImageError: function (e) { console.error('二维码图片加载失败:', e); wx.showToast({ title: '二维码图片加载失败', icon: 'none', duration: 2000 }); }, // 长按保存图片 longPressSaveImage: function (e) { const index = e.currentTarget.dataset.index; const qrCode = this.data.qrCodes[index]; if (!qrCode) { wx.showToast({ title: '暂无二维码数据', icon: 'none', duration: 2000 }); return; } // 显示确认对话框 wx.showModal({ title: '保存图片', content: '确定要保存此二维码图片吗?', success: (res) => { if (res.confirm) { // 确保当前二维码项是展开状态 if (this.data.expandedIndex !== index) { this.setData({ expandedIndex: index }); } // 延迟执行,确保元素已渲染完成 setTimeout(() => { this.saveQrCodeImage(index); }, 500); } } }); }, // 保存二维码项为图片 saveQrCodeImage: function (index) { const qrCode = this.data.qrCodes[index]; if (!qrCode) { wx.showToast({ title: '暂无二维码数据', icon: 'none', duration: 2000 }); return; } // 获取屏幕宽度 const screenWidth = wx.getSystemInfoSync().windowWidth; const canvasWidth = screenWidth; const canvasHeight = 280; // 进一步调整高度,确保内容紧凑 // 创建canvas上下文 const ctx = wx.createCanvasContext('saveCanvas'); // 清除canvas ctx.clearRect(0, 0, canvasWidth, canvasHeight); // 设置背景色 ctx.setFillStyle('#ffffff'); ctx.fillRect(0, 0, canvasWidth, canvasHeight); // 绘制公司名称(居中) ctx.setFontSize(18); ctx.setFillStyle('#333333'); ctx.setTextAlign('center'); ctx.fillText(qrCode.company || '未知', canvasWidth / 2, 40); // 绘制电话号码和创建时间(居中) ctx.setFontSize(14); ctx.setFillStyle('#666666'); ctx.setTextAlign('center'); ctx.fillText((qrCode.phoneNumber || '未知') + ' / ' + (qrCode.createdAt || '未知'), canvasWidth / 2, 70); // 绘制二维码图片(居中) const qrCodeUrl = qrCode.qrCodeUrl || `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(qrCode.url)}`; // 先下载二维码图片 wx.downloadFile({ url: qrCodeUrl, success: (res) => { if (res.statusCode === 200) { const qrSize = 140; // 调整二维码大小 const qrX = (canvasWidth - qrSize) / 2; const qrY = 90; // 绘制二维码图片到canvas ctx.drawImage(res.tempFilePath, qrX, qrY, qrSize, qrSize); // 绘制邀请人信息(二维码正下方,居中) ctx.setFontSize(14); ctx.setFillStyle('#333333'); ctx.setTextAlign('center'); ctx.fillText('邀请人: ' + (qrCode.inviter || '未知'), canvasWidth / 2, qrY + qrSize + 20); ctx.fillText('职位: ' + (qrCode.inviterProjectName || '无职位'), canvasWidth / 2, qrY + qrSize + 40); // 绘制完成 ctx.draw(false, () => { // 将canvas转换为临时文件 wx.canvasToTempFilePath({ canvasId: 'saveCanvas', width: canvasWidth, height: canvasHeight, destWidth: canvasWidth * 2, destHeight: canvasHeight * 2, success: (result) => { // 保存到相册 wx.saveImageToPhotosAlbum({ filePath: result.tempFilePath, success: () => { wx.showToast({ title: '图片保存成功', icon: 'success', duration: 2000 }); }, fail: (err) => { console.error('保存图片失败:', err); wx.showToast({ title: '保存图片失败', icon: 'none', duration: 2000 }); } }); }, fail: (err) => { console.error('转换图片失败:', err); wx.showToast({ title: '转换图片失败', icon: 'none', duration: 2000 }); } }); }); } }, fail: (err) => { console.error('下载二维码图片失败:', err); wx.showToast({ title: '下载图片失败', icon: 'none', duration: 2000 }); } }); } });