2026-01-20 19:36:49 +08:00
|
|
|
import { ref } from "vue";
|
|
|
|
|
import { defineStore } from "pinia";
|
|
|
|
|
import api from '@/utils/api';
|
|
|
|
|
import { toast } from '@/utils/widget';
|
2026-01-28 13:38:05 +08:00
|
|
|
import { initGlobalTIM, globalTimChatManager } from "@/utils/tim-chat.js";
|
2026-01-20 19:36:49 +08:00
|
|
|
const env = __VITE_ENV__;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export default defineStore("accountStore", () => {
|
|
|
|
|
const appid = env.MP_WX_APP_ID;
|
|
|
|
|
const account = ref(null);
|
|
|
|
|
const loading = ref(false)
|
2026-01-28 13:38:05 +08:00
|
|
|
const isIMInitialized = ref(false);
|
|
|
|
|
const openid = ref("");
|
2026-01-20 19:36:49 +08:00
|
|
|
async function login(phoneCode = '') {
|
2026-01-28 13:38:05 +08:00
|
|
|
|
2026-01-20 19:36:49 +08:00
|
|
|
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;
|
2026-01-28 13:38:05 +08:00
|
|
|
openid.value = res.data.openid;
|
|
|
|
|
initIMAfterLogin(openid.value)
|
2026-01-20 19:36:49 +08:00
|
|
|
return res.data
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
toast('登录失败,请重新登录');
|
|
|
|
|
} catch (e) {
|
|
|
|
|
toast('登录失败,请重新登录');
|
|
|
|
|
}
|
|
|
|
|
loading.value = false
|
|
|
|
|
}
|
|
|
|
|
|
2026-01-28 13:38:05 +08:00
|
|
|
async function initIMAfterLogin(userID) {
|
|
|
|
|
if (isIMInitialized.value) {
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
try {
|
|
|
|
|
await initGlobalTIM(userID);
|
|
|
|
|
isIMInitialized.value = true;
|
|
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return { account, login, initIMAfterLogin, logout, openid, isIMInitialized }
|
2026-01-20 19:36:49 +08:00
|
|
|
})
|