import { ref } from "vue"; import { defineStore } from "pinia"; import api from '@/utils/api'; import { toast } from '@/utils/widget'; import { getInitIMPromise, clearInitIMPromise } 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 mobile = ref(uni.getStorageSync('user_mobile') || ''); async function login(phoneCode = '') { if (loading.value) return; loading.value = true; try { const { code } = await uni.login({ appid, provider: "weixin", scope: "snsapi_base", }); console.log('logincode: ', code) if (code) { const res = await api('wxAppLogin', { phoneCode, code, }); loading.value = false console.log(res) if (res.success && res.data && res.data.mobile) { account.value = res.data; openid.value = res.data.openid || res.data.openId || res.data.userId || ""; isIMInitialized.value = false; clearInitIMPromise(); // 存储手机号 if (res.data.mobile) { mobile.value = res.data.mobile; uni.setStorageSync('user_mobile', res.data.mobile); } return res.data } } toast('登录失败,请重新登录'); } catch (e) { toast('登录失败,请重新登录'); } loading.value = false } /** * 登录后初始化 IM(供聊天页调用) * @param {string} userID - IM userID(通常用 openid/openId) */ async function initIMAfterLogin(userID) { const uid = userID || openid.value; if (!uid) { toast("缺少 openid,无法初始化IM"); return false; } try { await getInitIMPromise(uid, true); isIMInitialized.value = true; return true; } catch (e) { isIMInitialized.value = false; return false; } } return { account, openid, isIMInitialized, mobile, login, initIMAfterLogin } })