2026-01-19 18:52:18 +08:00
|
|
|
|
import { ref } from "vue";
|
|
|
|
|
|
import { defineStore } from "pinia";
|
|
|
|
|
|
import api from '@/utils/api';
|
|
|
|
|
|
import { toast } from '@/utils/widget';
|
2026-01-20 13:21:50 +08:00
|
|
|
|
import { getInitIMPromise, clearInitIMPromise } from "@/utils/tim-chat.js";
|
2026-01-19 18:52:18 +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-20 13:21:50 +08:00
|
|
|
|
// IM 相关
|
|
|
|
|
|
const openid = ref("");
|
|
|
|
|
|
const isIMInitialized = ref(false);
|
2026-01-19 18:52:18 +08:00
|
|
|
|
|
|
|
|
|
|
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;
|
2026-01-20 13:21:50 +08:00
|
|
|
|
// 兼容不同字段名
|
|
|
|
|
|
openid.value = res.data.openid || res.data.openId || res.data.userId || "";
|
|
|
|
|
|
isIMInitialized.value = false;
|
|
|
|
|
|
clearInitIMPromise();
|
2026-01-19 18:52:18 +08:00
|
|
|
|
return res.data
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
toast('登录失败,请重新登录');
|
|
|
|
|
|
} catch (e) {
|
|
|
|
|
|
toast('登录失败,请重新登录');
|
|
|
|
|
|
}
|
|
|
|
|
|
loading.value = false
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-01-20 13:21:50 +08:00
|
|
|
|
/**
|
|
|
|
|
|
* 登录后初始化 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 }
|
2026-01-19 18:52:18 +08:00
|
|
|
|
})
|