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); 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(); 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, login, initIMAfterLogin } })