ykt-team-wxapp/store/account.js
2026-01-29 11:42:56 +08:00

109 lines
3.0 KiB
JavaScript
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.

import { ref } from "vue";
import { defineStore } from "pinia";
import api from '@/utils/api';
import { toast } from '@/utils/widget';
import { initGlobalTIM, globalTimChatManager } from "@/utils/tim-chat.js";
const env = __VITE_ENV__;
export default defineStore("accountStore", () => {
const appid = env.MP_WX_APP_ID;
const account = ref(null);
const loading = ref(false)
const isIMInitialized = ref(false);
const openid = ref("");
async function login(phoneCode = '') {
if (loading.value) return;
loading.value = true;
try {
const { code } = await uni.login({
appid,
provider: "weixin",
scope: "snsapi_base",
});
if (code) {
const res = await api('wxAppLogin', {
phoneCode,
code,
});
loading.value = false
if (res.success && res.data && res.data.mobile) {
account.value = res.data;
openid.value = res.data.openid;
// 保存账户信息和 openId 到本地存储
uni.setStorageSync('account', res.data);
uni.setStorageSync('openid', res.data.openid);
initIMAfterLogin(openid.value)
return res.data
}
}
toast('登录失败,请重新登录');
} catch (e) {
toast('登录失败,请重新登录');
}
loading.value = false
}
async function initIMAfterLogin() {
if (isIMInitialized.value) {
return true;
}
try {
// 使用 openid 作为 userID 初始化 IM
const userID = openid.value || uni.getStorageSync('openid');
if (!userID) {
console.error('无法获取 openidIM 初始化失败');
return false;
}
console.log('开始初始化 IMuserID:', userID);
const success = await initGlobalTIM(userID);
if (!success) {
console.error('initGlobalTIM 返回失败');
return false;
}
// 验证 TIM 实例是否真正创建成功
if (!globalTimChatManager || !globalTimChatManager.tim) {
console.error('IM 初始化后 TIM 实例不存在');
return false;
}
isIMInitialized.value = true;
console.log('IM 初始化成功');
return true;
} catch (error) {
console.error('IM初始化失败:', error);
return false;
}
}
// 退出登录
async function logout() {
try {
// 退出腾讯IM
if (globalTimChatManager && globalTimChatManager.tim) {
console.log('开始退出腾讯IM');
await globalTimChatManager.destroy();
console.log('腾讯IM退出成功');
}
} catch (error) {
console.error('退出腾讯IM失败:', error);
}
// 清空账户信息
account.value = null;
openid.value = "";
isIMInitialized.value = false;
// 清除本地存储
uni.removeStorageSync('account');
uni.removeStorageSync('openid');
}
return { account, login, initIMAfterLogin, logout, openid, isIMInitialized }
})