123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205 |
- import { TUILogin } from "@tencentcloud/tui-core";
- import {
- TUIUserService,
- TUIConversationService,
- TUIStore,
- StoreName,
- } from "@tencentcloud/chat-uikit-engine";
- import { TUIGlobal } from "@tencentcloud/universal-api";
- function capitalize(str: string): string {
- if (!str) return "";
- return str.charAt(0).toUpperCase() + str.slice(1);
- }
- export const loginChat = async (loginInfo) => {
- // 前置校验:确保必填参数存在
- if (!loginInfo?.userID || !loginInfo?.userSig) {
- const error = new Error("缺少userID或userSig");
- console.error("登录参数错误", error);
- uni.showToast({ title: "登录信息不完整", icon: "none" });
- throw error;
- }
- try {
- // 1. 先读取所有存储数据(同步操作前置)
- const [
- link,
- companyUserId,
- recruitUserId,
- Identity,
- postId,
- type,
- shopUserId,
- userLoginType,
- userId,
- ] = [
- "link",
- "companyUserId",
- "recruitUserId",
- "Identity",
- "postId",
- "type",
- "shopUserId",
- "userLoginType",
- "userId",
- ].map((key) => uni.getStorageSync(key));
- // 2. 执行登录(核心步骤,await确保完成)
- console.log("开始IM登录", loginInfo.userID);
- const res = await TUILogin.login(loginInfo);
- console.log("IM登录成功", res);
- // 3. 登录成功后再执行后续操作(确保登录状态就绪)
- // 3.1 保存用户信息(异步不阻塞主流程)
- uni.setStorage({
- key: "userInfo",
- data: JSON.stringify({
- ...loginInfo,
- TIMPush: undefined,
- pushConfig: {},
- }),
- });
- // 3.2 设置在线状态(确保服务已初始化)
- await TUIUserService.switchUserStatus({ displayOnlineStatus: true });
- console.log("用户在线状态设置完成");
- // 3.3 处理会话切换(类型校验+容错)
- if (type && ["job", "house", "homemaking"].includes(type)) {
- const userTypeNum = parseInt(userLoginType) || 0;
- // 会话ID构建(避免空值拼接)
- let conversationId;
- switch (type) {
- case "job":
- const jobTargetId = userTypeNum > 0 ? companyUserId : recruitUserId;
- conversationId = jobTargetId
- ? `C2C${userTypeNum > 0 ? "A" + jobTargetId : jobTargetId}`
- : "";
- break;
- case "house":
- const houseTargetId = userTypeNum > 0 ? shopUserId : userId;
- conversationId = houseTargetId
- ? `C2C${userTypeNum > 0 ? "C" + houseTargetId : houseTargetId}`
- : "";
- break;
- case "homemaking":
- const homeTargetId = userTypeNum > 0 ? shopUserId : userId;
- conversationId = homeTargetId
- ? `C2C${userTypeNum > 0 ? "E" + homeTargetId : homeTargetId}`
- : "";
- break;
- }
- // 切换会话(确保ID有效再执行)
- if (conversationId) {
- console.log("切换会话", conversationId);
- await TUIConversationService.switchConversation(conversationId);
- console.log("会话切换完成");
- } else {
- console.warn("未找到有效会话ID,跳过切换");
- }
- }
- // 3.4 页面跳转(确保IM初始化完成后再跳转)
- if (link) {
- console.log("跳转到单聊页面");
- if (type === "job") {
- uni.navigateTo({
- url: `/TUIKit/components/TUIChat/index?companyUserId=${companyUserId}&recruitUserId=${recruitUserId}&postId=${postId}`,
- });
- } else {
- uni.navigateTo({
- url: `/TUIKit-${capitalize(type)}/components/TUIChat/index`,
- });
- }
- } else {
- console.log("跳转到会话列表");
- handleRedirectBasedOnIdentity(Identity, loginInfo.userID);
- }
- return res;
- } catch (error) {
- // 集中捕获所有阶段的错误
- console.error("IM登录初始化失败", error);
- uni.showToast({ title: "IM初始化失败,请重试", icon: "none" });
- throw error; // 允许上层处理
- }
- };
- // 封装跳转逻辑(保持不变)
- const handleRedirectBasedOnIdentity = (identity, userID) => {
- const isJob = identity === "job";
- const isMerchant = /[CE]/.test(userID);
- const basePrefix = isJob ? "/TUIKit" : `/TUIKit-${capitalize(identity)}`;
- const suffixPath = isMerchant
- ? "/components/TUIConversation/merChantSideIndex"
- : "/components/TUIConversation/index";
- uni.reLaunch({
- url: `${basePrefix}${suffixPath}`,
- success: () => {
- uni.$emit("uikitLogin");
- },
- });
- };
- export const loginFromStorage = () => {
- uni?.getStorage({
- key: "userInfo",
- success: function (res) {
- if (res.data) {
- const loginInfo = {
- ...JSON.parse(res.data),
- };
- if (uni?.$TIMPush) {
- loginInfo.TIMPush = uni?.$TIMPush;
- loginInfo.pushConfig = {
- androidConfig: uni?.$TIMPushConfigs, // Android 推送配置,如不需要可传空。
- iOSConfig: {
- iOSBusinessID: "29064", // iOS 推送配置,如不需要可传空。
- },
- };
- }
- loginChat(loginInfo).catch(() => {
- uni?.removeStorage({
- key: "userInfo",
- });
- });
- }
- },
- });
- };
- export declare interface IEnterChatConfig {
- isLoginChat: boolean;
- conversationID: string;
- }
- export const openChat = (enterChatConfig: IEnterChatConfig) => {
- const { isLoginChat = false, conversationID = "" } = enterChatConfig || {};
- const chatPath = "/TUIKit/components/TUIChat/index";
- const currentConversationID = TUIStore.getData(
- StoreName.CONV,
- "currentConversationID"
- );
- if (!isLoginChat || !conversationID) {
- return;
- }
- if (!currentConversationID) {
- TUIConversationService.switchConversation(conversationID);
- uni?.navigateTo({
- url: chatPath,
- });
- } else if (currentConversationID !== conversationID) {
- uni.navigateBack({
- delta: 1,
- success: () => {
- TUIConversationService.switchConversation(conversationID);
- uni?.navigateTo({
- url: chatPath,
- });
- },
- });
- }
- };
|