loginChat.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. import { TUILogin } from "@tencentcloud/tui-core";
  2. import {
  3. TUIUserService,
  4. TUIConversationService,
  5. TUIStore,
  6. StoreName,
  7. } from "@tencentcloud/chat-uikit-engine";
  8. import { TUIGlobal } from "@tencentcloud/universal-api";
  9. function capitalize(str: string): string {
  10. if (!str) return "";
  11. return str.charAt(0).toUpperCase() + str.slice(1);
  12. }
  13. export const loginChat = async (loginInfo) => {
  14. // 前置校验:确保必填参数存在
  15. if (!loginInfo?.userID || !loginInfo?.userSig) {
  16. const error = new Error("缺少userID或userSig");
  17. console.error("登录参数错误", error);
  18. uni.showToast({ title: "登录信息不完整", icon: "none" });
  19. throw error;
  20. }
  21. try {
  22. // 1. 先读取所有存储数据(同步操作前置)
  23. const [
  24. link,
  25. companyUserId,
  26. recruitUserId,
  27. Identity,
  28. postId,
  29. type,
  30. shopUserId,
  31. userLoginType,
  32. userId,
  33. ] = [
  34. "link",
  35. "companyUserId",
  36. "recruitUserId",
  37. "Identity",
  38. "postId",
  39. "type",
  40. "shopUserId",
  41. "userLoginType",
  42. "userId",
  43. ].map((key) => uni.getStorageSync(key));
  44. // 2. 执行登录(核心步骤,await确保完成)
  45. console.log("开始IM登录", loginInfo.userID);
  46. const res = await TUILogin.login(loginInfo);
  47. console.log("IM登录成功", res);
  48. // 3. 登录成功后再执行后续操作(确保登录状态就绪)
  49. // 3.1 保存用户信息(异步不阻塞主流程)
  50. uni.setStorage({
  51. key: "userInfo",
  52. data: JSON.stringify({
  53. ...loginInfo,
  54. TIMPush: undefined,
  55. pushConfig: {},
  56. }),
  57. });
  58. // 3.2 设置在线状态(确保服务已初始化)
  59. await TUIUserService.switchUserStatus({ displayOnlineStatus: true });
  60. console.log("用户在线状态设置完成");
  61. // 3.3 处理会话切换(类型校验+容错)
  62. if (type && ["job", "house", "homemaking"].includes(type)) {
  63. const userTypeNum = parseInt(userLoginType) || 0;
  64. // 会话ID构建(避免空值拼接)
  65. let conversationId;
  66. switch (type) {
  67. case "job":
  68. const jobTargetId = userTypeNum > 0 ? companyUserId : recruitUserId;
  69. conversationId = jobTargetId
  70. ? `C2C${userTypeNum > 0 ? "A" + jobTargetId : jobTargetId}`
  71. : "";
  72. break;
  73. case "house":
  74. const houseTargetId = userTypeNum > 0 ? shopUserId : userId;
  75. conversationId = houseTargetId
  76. ? `C2C${userTypeNum > 0 ? "C" + houseTargetId : houseTargetId}`
  77. : "";
  78. break;
  79. case "homemaking":
  80. const homeTargetId = userTypeNum > 0 ? shopUserId : userId;
  81. conversationId = homeTargetId
  82. ? `C2C${userTypeNum > 0 ? "E" + homeTargetId : homeTargetId}`
  83. : "";
  84. break;
  85. }
  86. // 切换会话(确保ID有效再执行)
  87. if (conversationId) {
  88. console.log("切换会话", conversationId);
  89. await TUIConversationService.switchConversation(conversationId);
  90. console.log("会话切换完成");
  91. } else {
  92. console.warn("未找到有效会话ID,跳过切换");
  93. }
  94. }
  95. // 3.4 页面跳转(确保IM初始化完成后再跳转)
  96. if (link) {
  97. console.log("跳转到单聊页面");
  98. if (type === "job") {
  99. uni.navigateTo({
  100. url: `/TUIKit/components/TUIChat/index?companyUserId=${companyUserId}&recruitUserId=${recruitUserId}&postId=${postId}`,
  101. });
  102. } else {
  103. uni.navigateTo({
  104. url: `/TUIKit-${capitalize(type)}/components/TUIChat/index`,
  105. });
  106. }
  107. } else {
  108. console.log("跳转到会话列表");
  109. handleRedirectBasedOnIdentity(Identity, loginInfo.userID);
  110. }
  111. return res;
  112. } catch (error) {
  113. // 集中捕获所有阶段的错误
  114. console.error("IM登录初始化失败", error);
  115. uni.showToast({ title: "IM初始化失败,请重试", icon: "none" });
  116. throw error; // 允许上层处理
  117. }
  118. };
  119. // 封装跳转逻辑(保持不变)
  120. const handleRedirectBasedOnIdentity = (identity, userID) => {
  121. const isJob = identity === "job";
  122. const isMerchant = /[CE]/.test(userID);
  123. const basePrefix = isJob ? "/TUIKit" : `/TUIKit-${capitalize(identity)}`;
  124. const suffixPath = isMerchant
  125. ? "/components/TUIConversation/merChantSideIndex"
  126. : "/components/TUIConversation/index";
  127. uni.reLaunch({
  128. url: `${basePrefix}${suffixPath}`,
  129. success: () => {
  130. uni.$emit("uikitLogin");
  131. },
  132. });
  133. };
  134. export const loginFromStorage = () => {
  135. uni?.getStorage({
  136. key: "userInfo",
  137. success: function (res) {
  138. if (res.data) {
  139. const loginInfo = {
  140. ...JSON.parse(res.data),
  141. };
  142. if (uni?.$TIMPush) {
  143. loginInfo.TIMPush = uni?.$TIMPush;
  144. loginInfo.pushConfig = {
  145. androidConfig: uni?.$TIMPushConfigs, // Android 推送配置,如不需要可传空。
  146. iOSConfig: {
  147. iOSBusinessID: "29064", // iOS 推送配置,如不需要可传空。
  148. },
  149. };
  150. }
  151. loginChat(loginInfo).catch(() => {
  152. uni?.removeStorage({
  153. key: "userInfo",
  154. });
  155. });
  156. }
  157. },
  158. });
  159. };
  160. export declare interface IEnterChatConfig {
  161. isLoginChat: boolean;
  162. conversationID: string;
  163. }
  164. export const openChat = (enterChatConfig: IEnterChatConfig) => {
  165. const { isLoginChat = false, conversationID = "" } = enterChatConfig || {};
  166. const chatPath = "/TUIKit/components/TUIChat/index";
  167. const currentConversationID = TUIStore.getData(
  168. StoreName.CONV,
  169. "currentConversationID"
  170. );
  171. if (!isLoginChat || !conversationID) {
  172. return;
  173. }
  174. if (!currentConversationID) {
  175. TUIConversationService.switchConversation(conversationID);
  176. uni?.navigateTo({
  177. url: chatPath,
  178. });
  179. } else if (currentConversationID !== conversationID) {
  180. uni.navigateBack({
  181. delta: 1,
  182. success: () => {
  183. TUIConversationService.switchConversation(conversationID);
  184. uni?.navigateTo({
  185. url: chatPath,
  186. });
  187. },
  188. });
  189. }
  190. };