113 lines
3.0 KiB
JavaScript
113 lines
3.0 KiB
JavaScript
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)
|
||
// IM 相关
|
||
const openid = ref("");
|
||
const isIMInitialized = ref(false);
|
||
// 医生信息
|
||
const doctorInfo = ref(null);
|
||
|
||
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) {
|
||
if (!res.data.mobile) {
|
||
const target = '/pages/login/login';
|
||
uni.redirectTo({ url: target });
|
||
return;
|
||
}
|
||
account.value = res.data;
|
||
openid.value = res.data.openid;
|
||
|
||
|
||
// 登录成功后初始化腾讯IM
|
||
try {
|
||
console.log('开始初始化腾讯IM,userID:', res.data.openid);
|
||
await initGlobalTIM(res.data.openid);
|
||
isIMInitialized.value = true;
|
||
console.log('腾讯IM初始化成功');
|
||
} catch (imError) {
|
||
console.error('腾讯IM初始化失败:', imError);
|
||
// IM初始化失败不影响登录流程
|
||
}
|
||
await getDoctorInfo(openid.value);
|
||
return res.data
|
||
}
|
||
}
|
||
toast('登录失败,请重新登录');
|
||
} catch (e) {
|
||
toast('登录失败,请重新登录');
|
||
}
|
||
loading.value = false
|
||
}
|
||
|
||
async function getDoctorInfo() {
|
||
try {
|
||
const res = await api('getCorpMemberData', {
|
||
weChatOpenId: account.value.openid,
|
||
});
|
||
if (res.success && res.data) {
|
||
doctorInfo.value = res.data;
|
||
}
|
||
} catch (e) {
|
||
console.error('获取医生信息失败:', e);
|
||
}
|
||
}
|
||
|
||
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;
|
||
doctorInfo.value = null;
|
||
}
|
||
|
||
return { account, openid, isIMInitialized, doctorInfo, login, getDoctorInfo, initIMAfterLogin, logout }
|
||
}) |