pet/App.vue

163 lines
4.3 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<script>
import { wxLogin } from '@/http/api/auth.js'
import { WebSocketManager } from '@/utils/websocket.js'
export default {
onLaunch: function() {
console.log('App Launch')
this.initApp()
},
onShow: function() {
console.log('App Show')
},
onHide: function() {
console.log('App Hide')
},
methods: {
// 应用初始化
async initApp() {
console.log('应用初始化开始')
await this.checkAutoLogin()
},
// 等待HTTP配置初始化
async waitForHttpInit() {
// 等待uni.$u.http可用
let retryCount = 0
const maxRetries = 10
while (!uni.$u || !uni.$u.http) {
if (retryCount >= maxRetries) {
throw new Error('HTTP配置初始化超时')
}
await new Promise(resolve => setTimeout(resolve, 100))
retryCount++
}
console.log('HTTP配置初始化完成')
},
// 检查自动登录
async checkAutoLogin() {
try {
// 检查本地是否有有效token
const token = uni.getStorageSync('token')
if (token) {
// 已有token初始化WebSocket连接
await this.initWebSocketConnection(token)
return
}
// 等待HTTP配置初始化完成
await this.waitForHttpInit()
// 获取微信登录code
const loginRes = await new Promise((resolve, reject) => {
uni.login({
success: resolve,
fail: (error) => {
console.warn('微信登录失败:', error)
// 不reject而是resolve一个空对象避免阻止应用启动
resolve({ code: null, error })
}
})
})
if (loginRes.code) {
// 调用后端登录接口
const result = await uni.$u.http.post('/wechat/user/mini/login', {
code: loginRes.code
}, {
custom: {
loading: false,
toast: false,
auth: false
}
})
if (result && result.token) {
// 用户已授权过手机号,保存登录信息
await this.saveLoginData(result)
} else {
// 用户未授权手机号保存微信登录code供后续使用
this.saveWxCode(loginRes.code)
}
}
} catch (error) {
// 静默处理错误,不影响应用正常启动
console.error('自动登录失败:', error)
}
},
// 保存登录数据
async saveLoginData(result) {
uni.setStorageSync('token', result.token)
if (result.refreshToken) {
uni.setStorageSync('refreshToken', result.refreshToken)
}
if (result.userInfo) {
uni.setStorageSync('wxUserInfo', result.userInfo)
uni.setStorageSync('userInfo', result.userInfo)
}
// 设置登录状态
const loginStep = result.userInfo && result.userInfo.profileCompleted
? 'profile_completed'
: 'phone_authed'
uni.setStorageSync('loginStep', loginStep)
// 初始化WebSocket连接
await this.initWebSocketConnection(result.token)
},
// 保存微信code
saveWxCode(code) {
uni.setStorageSync('wxLoginCode', code)
uni.setStorageSync('loginDate', new Date().toISOString())
uni.setStorageSync('loginStep', 'wx_logged')
},
// 初始化WebSocket连接
async initWebSocketConnection(token) {
try {
console.log('🔌 开始初始化WebSocket连接, token:', token ? '已提供' : '未提供')
const wsManager = WebSocketManager.getInstance()
// 获取连接信息用于调试
const connectionInfo = wsManager.getConnectionInfo()
console.log('📊 WebSocket连接信息:', connectionInfo)
// 建立WebSocket连接
const connected = await wsManager.connect(token)
if (connected) {
console.log('✅ WebSocket连接初始化成功')
// 添加连接状态监听
wsManager.addEventListener('onClose', () => {
console.log('❌ WebSocket连接已断开')
})
wsManager.addEventListener('onError', (error) => {
console.error('🚨 WebSocket连接错误:', error)
})
wsManager.addEventListener('onOpen', () => {
console.log('🎉 WebSocket连接已建立')
})
} else {
console.warn('⚠️ WebSocket连接初始化失败将使用HTTP降级方案')
}
} catch (error) {
console.error('💥 WebSocket连接初始化异常:', error)
}
}
}
}
</script>
<style lang="scss">
/*每个页面公共css */
@import "@/uni_modules/uview-next/index.scss";
</style>