ykt-team-wxapp/store/account.js

199 lines
6.4 KiB
JavaScript
Raw Normal View History

2026-09-20 15:16:14 +08:00
import { ref, watch } from "vue";
2026-01-20 19:36:49 +08:00
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-02-11 09:51:02 +08:00
import { globalUnreadListenerManager } from "@/utils/global-unread-listener.js";
2026-09-22 17:07:16 +08:00
import { isSh6CorpId, normalizeCorpId, normalizeCorpIdFields, resolveApiContext } from "@/utils/api-base-config";
import { setMiniappSessionRefresher } from "@/utils/http";
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-02-04 09:16:36 +08:00
const externalUserId = ref('');
2026-09-02 17:52:13 +08:00
const externalUserIdMap = ref({});
2026-04-14 16:17:40 +08:00
const teams = ref([]);
const teamsPromise = ref(null);
2026-01-28 13:38:05 +08:00
2026-09-22 17:07:16 +08:00
function hasValidMiniappSession() {
if (!isSh6CorpId(resolveApiContext().corpId)) return true;
const token = uni.getStorageSync("miniappSessionToken");
const expiresAt = Number(uni.getStorageSync("miniappSessionExpiresAt"));
return Boolean(token && (!expiresAt || expiresAt > Date.now() + 30 * 1000));
}
2026-06-25 09:58:57 +08:00
async function login(phoneCode = '', options = {}) {
2026-01-20 19:36:49 +08:00
if (loading.value) return;
2026-09-22 17:07:16 +08:00
if (account.value && account.value.mobile && !options.forceVerify && hasValidMiniappSession()) {
2026-04-30 17:55:34 +08:00
return account.value
}
2026-01-20 19:36:49 +08:00
loading.value = true;
try {
const { code } = await uni.login({
appid,
provider: "weixin",
scope: "snsapi_base",
});
if (code) {
const res = await api('wxAppLogin', {
2026-02-04 09:16:36 +08:00
appId: appid,
2026-01-20 19:36:49 +08:00
phoneCode,
2026-02-09 17:09:00 +08:00
code
2026-01-20 19:36:49 +08:00
});
loading.value = false
2026-02-10 11:08:00 +08:00
if (res.success && res.data) {
2026-09-22 17:07:16 +08:00
const { sessionToken, sessionExpiresAt, sessionKey, ...safeAccount } = res.data;
if (sessionToken) {
uni.setStorageSync("miniappSessionToken", sessionToken);
uni.setStorageSync("miniappSessionExpiresAt", sessionExpiresAt || 0);
}
const normalizedAccount = normalizeCorpIdFields(safeAccount);
account.value = normalizedAccount;
openid.value = normalizedAccount.openid;
2026-02-04 09:16:36 +08:00
2026-01-29 11:42:56 +08:00
// 保存账户信息和 openId 到本地存储
uni.setStorageSync('account', normalizedAccount);
uni.setStorageSync('openid', normalizedAccount.openid);
2026-02-04 09:16:36 +08:00
2026-04-14 16:17:40 +08:00
// initIMAfterLogin(openid.value)
return normalizedAccount
2026-07-30 10:09:25 +08:00
} else {
account.value = null;
openid.value = '';
uni.removeStorageSync('account');
uni.removeStorageSync('openid');
return
2026-01-20 19:36:49 +08:00
}
}
2026-06-25 09:58:57 +08:00
if (!options.silent) toast('登录失败,请重新登录');
2026-01-20 19:36:49 +08:00
} catch (e) {
2026-06-25 09:58:57 +08:00
if (!options.silent) toast('登录失败,请重新登录');
2026-01-20 19:36:49 +08:00
}
loading.value = false
}
2026-01-28 16:20:19 +08:00
async function initIMAfterLogin() {
2026-01-28 13:38:05 +08:00
if (isIMInitialized.value) {
return true;
}
try {
2026-01-29 11:42:56 +08:00
// 使用 openid 作为 userID 初始化 IM
const userID = openid.value || uni.getStorageSync('openid');
if (!userID) {
2026-02-09 09:18:33 +08:00
console.log('未获取到有效的 userId,跳过 IM 初始化');
2026-01-29 11:42:56 +08:00
return false;
}
2026-02-04 09:16:36 +08:00
2026-01-29 11:42:56 +08:00
console.log('开始初始化 IM,userID:', userID);
const success = await initGlobalTIM(userID);
2026-02-04 09:16:36 +08:00
2026-01-29 11:42:56 +08:00
if (!success) {
2026-02-09 09:18:33 +08:00
console.log('initGlobalTIM 返回失败,跳过 IM 初始化');
2026-01-29 11:42:56 +08:00
return false;
}
2026-02-04 09:16:36 +08:00
2026-01-29 11:42:56 +08:00
// 验证 TIM 实例是否真正创建成功
if (!globalTimChatManager || !globalTimChatManager.tim) {
2026-02-09 09:18:33 +08:00
console.log('IM 初始化后 TIM 实例不存在,跳过 IM 初始化');
2026-01-29 11:42:56 +08:00
return false;
}
2026-02-04 09:16:36 +08:00
2026-01-28 13:38:05 +08:00
isIMInitialized.value = true;
2026-01-29 11:42:56 +08:00
console.log('IM 初始化成功');
2026-04-14 16:17:40 +08:00
2026-02-11 09:51:02 +08:00
// IM 初始化成功后,设置全局未读消息监听
2026-02-12 12:04:57 +08:00
// globalUnreadListenerManager.setup();
2026-04-14 16:17:40 +08:00
2026-01-28 13:38:05 +08:00
return true;
} catch (error) {
2026-02-09 09:18:33 +08:00
console.log('IM初始化异常,跳过 IM 初始化:', error.message);
2026-01-28 13:38:05 +08:00
return false;
}
}
// 退出登录
async function logout() {
try {
// 退出腾讯IM
if (globalTimChatManager && globalTimChatManager.tim) {
console.log('开始退出腾讯IM');
await globalTimChatManager.destroy();
console.log('腾讯IM退出成功');
}
2026-04-14 16:17:40 +08:00
2026-02-11 09:51:02 +08:00
// 清除全局未读监听
if (globalUnreadListenerManager.isInitialized) {
2026-02-12 12:04:57 +08:00
// globalUnreadListenerManager.destroy();
2026-02-11 09:51:02 +08:00
}
2026-01-28 13:38:05 +08:00
} catch (error) {
console.error('退出腾讯IM失败:', error);
}
// 清空账户信息
account.value = null;
2026-09-22 17:07:16 +08:00
uni.removeStorageSync("miniappSessionToken");
uni.removeStorageSync("miniappSessionExpiresAt");
2026-01-28 13:38:05 +08:00
openid.value = "";
isIMInitialized.value = false;
2026-02-04 09:16:36 +08:00
2026-01-29 11:42:56 +08:00
// 清除本地存储
uni.removeStorageSync('account');
uni.removeStorageSync('openid');
2026-04-14 16:17:40 +08:00
2026-02-11 09:51:02 +08:00
// 清除 tabBar 徽章
uni.removeTabBarBadge({
index: 1
});
2026-01-28 13:38:05 +08:00
}
2026-04-14 16:17:40 +08:00
async function searchTeams() {
const res = await api('getWxappRelateTeams', { openid: account.value.openid });
teams.value = res && Array.isArray(res.data) ? normalizeCorpIdFields(res.data) : [];
2026-04-14 16:17:40 +08:00
return teams.value;
}
async function getTeams() {
if (!teamsPromise.value) {
teamsPromise.value = searchTeams();
}
await teamsPromise.value;
teamsPromise.value = null;
return teams.value;
}
2026-02-09 17:31:16 +08:00
async function getExternalUserId(corpId) {
const normalizedCorpId = normalizeCorpId(corpId);
2026-02-04 09:16:36 +08:00
const unionid = account.value?.unionid;
const openid = account.value?.openid;
2026-09-02 17:52:13 +08:00
const miniAppId = account.value?.openid;
if (!(normalizedCorpId && unionid && openid)) {
2026-07-30 10:09:25 +08:00
externalUserId.value = '';
return
};
2026-09-02 17:52:13 +08:00
const key = `${normalizedCorpId}_${unionid}_${openid}_${miniAppId}`;
if (externalUserIdMap.value[key]) {
return externalUserIdMap.value[key]
}
2026-08-10 15:29:18 +08:00
const res = await api('getUnionidToExternalUserid', { unionid, openid, corpId: normalizedCorpId, miniAppId }, false);
const id = res && res.success && typeof res.data === 'string' && res.data.trim() ? res.data.trim() : '';
externalUserId.value = id;
2026-09-02 17:52:13 +08:00
if (id) {
externalUserIdMap.value[key] = id;
}
2026-06-04 10:56:39 +08:00
return id;
2026-02-04 09:16:36 +08:00
}
2026-04-14 16:17:40 +08:00
watch(openid, (n, o) => {
if (n && !o) {
getTeams();
}
}, { immediate: true })
2026-09-22 17:07:16 +08:00
setMiniappSessionRefresher(() => login('', { forceVerify: true, silent: true }));
return { account, teams, login, hasValidMiniappSession, initIMAfterLogin, logout, openid, isIMInitialized, externalUserId, getExternalUserId, getTeams }
})