dapaijizhang3/pages/index/index.js

292 lines
6.9 KiB
JavaScript
Raw Normal View History

2025-11-20 16:42:59 +08:00
import { injectPage ,onLoginReady } from '@jdmini/api'
import request from '../../utils/request'
Page(injectPage({})({
data: {
userInfo: null,
isLogin: false,
activeRooms: [],
recentRecords: [],
navbarHeight: 0,
showGuide: false,
guideSteps: [
{
selector: '.guide-create-btn',
title: '创建房间',
description: '点击这里可以创建一个新的牌局房间,邀请好友一起玩',
position: 'bottom',
padding: 12,
borderRadius: 16
},
{
selector: '.guide-join-btn',
title: '加入房间',
description: '输入房间号或使用扫码功能,快速加入好友的牌局',
position: 'bottom',
padding: 12,
borderRadius: 16
},
{
selector: '.guide-scan-btn',
title: '扫码进入',
description: '扫描房间二维码,即可立即进入牌局,非常方便!',
position: 'bottom',
padding: 8,
borderRadius: 12
}
]
},
onLoad() {
console.log('首页加载')
// 计算导航栏高度
const windowInfo = wx.getWindowInfo()
const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
const statusBarHeight = windowInfo.statusBarHeight
const menuButtonTop = menuButtonInfo.top
const navbarHeight = menuButtonInfo.bottom + (menuButtonTop - statusBarHeight)
this.setData({ navbarHeight })
// 加载用户信息(如果已登录)
// this.loadUserInfo()
},
onShow() {
// 每次显示页面时刷新用户信息和数据
onLoginReady(()=>{
this.loadUserInfo()
})
},
onReady() {
// 页面渲染完成后,检查是否需要显示引导
this.checkAndShowGuide()
},
// 检查并显示新用户引导
checkAndShowGuide() {
try {
const hasShownGuide = wx.getStorageSync('hasShownGuide')
if (!hasShownGuide) {
// 延迟显示引导,等待页面完全渲染
setTimeout(() => {
this.setData({ showGuide: true })
}, 500)
}
} catch (error) {
console.error('检查引导状态失败:', error)
}
},
// 引导完成回调
onGuideComplete() {
this.setData({ showGuide: false })
// 标记已显示过引导
try {
wx.setStorageSync('hasShownGuide', true)
} catch (error) {
console.error('保存引导状态失败:', error)
}
},
// 加载用户信息
async loadUserInfo() {
const app = getApp()
const userInfo = app.getUserInfo()
console.log(userInfo)
if (userInfo) {
// 已登录,从后端获取最新用户信息
try {
const data = await request.get('/auth/profile')
// 更新本地缓存
app.setUserInfo(data)
// 显示最新数据
this.setData({
userInfo: data,
isLogin: true
})
this.loadActiveRooms()
} catch (error) {
console.error('获取用户信息失败:', error)
// 如果获取失败,使用本地缓存数据
this.setData({
userInfo,
isLogin: true
})
this.loadActiveRooms()
}
} else {
// 未登录,显示登录按钮
this.setData({
userInfo: null,
isLogin: false,
activeRooms: []
})
}
},
// 检查是否登录,未登录则跳转
checkLoginAndNavigate() {
if (!this.data.isLogin) {
wx.navigateTo({
url: '/pages/login/login'
})
return false
}
return true
},
// 格式化时间
formatTime(timestamp) {
const date = new Date(timestamp * 1000)
const now = new Date()
const diff = now - date
// 小于1分钟
if (diff < 60000) {
return '刚刚'
}
// 小于1小时
if (diff < 3600000) {
return `${Math.floor(diff / 60000)}分钟前`
}
// 小于24小时
if (diff < 86400000) {
return `${Math.floor(diff / 3600000)}小时前`
}
// 小于7天
if (diff < 604800000) {
return `${Math.floor(diff / 86400000)}天前`
}
// 格式化为 月-日 时:分
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
const hour = String(date.getHours()).padStart(2, '0')
const minute = String(date.getMinutes()).padStart(2, '0')
return `${month}-${day} ${hour}:${minute}`
},
// 加载进行中的房间
async loadActiveRooms() {
if (!this.data.isLogin) return
try {
const data = await request.get('/rooms/my-sessions', {
status: 'active',
pageSize: 5
})
// 处理房间数据,添加格式化的时间
const rooms = (data.list || []).map(room => ({
...room,
create_time: this.formatTime(room.created_at)
}))
this.setData({
activeRooms: rooms
})
} catch (error) {
console.error('加载房间失败:', error)
}
},
// 进入个人资料页(登录/修改信息)
goToProfile() {
wx.navigateTo({
url: '/pages/login/login'
})
},
// 处理登录(保留兼容)
async handleLogin() {
this.goToProfile()
},
// 创建房间
createRoom() {
if (!this.checkLoginAndNavigate()) {
return
}
wx.navigateTo({
url: '/pages/game/create/create'
})
},
// 扫码进入房间
scanCode() {
if (!this.checkLoginAndNavigate()) {
return
}
wx.scanCode({
onlyFromCamera: false,
scanType: ['wxCode','qrCode'],
success: (res) => {
console.log('扫码结果:', res)
// 解析二维码内容
const result = res.path || res.result
// 检查是否是有效的路径(兼容带/和不带/的路径)
if (result.includes('pages/game/join/join?scene')) {
// 提取邀请码
//const match = result.split("%3D")
// console.log(match)
const match = result.match(/\%3D([A-Z0-9]+)/)
if (match && match[1]) {
const inviteCode = match[1]
// 跳转到加入页面
wx.navigateTo({
url: `/pages/game/join/join?code=${inviteCode}`
})
} else {
wx.showToast({
title: '无效的二维码',
icon: 'none'
})
}
} else {
wx.showToast({
title: '不是有效的房间二维码',
icon: 'none'
})
}
},
fail: (err) => {
console.error('扫码失败:', err)
if (err.errMsg !== 'scanCode:fail cancel') {
wx.showToast({
title: '扫码失败',
icon: 'none'
})
}
}
})
},
// 加入房间
joinRoom() {
if (!this.checkLoginAndNavigate()) {
return
}
wx.navigateTo({
url: '/pages/game/join/join'
})
},
// 进入房间详情
goToRoom(e) {
const id = e.currentTarget.dataset.id
wx.navigateTo({
url: `/pages/game/detail/detail?id=${id}`
})
}
}))