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 = (loginInfo) => {
  return TUILogin.login(loginInfo)
    .then((res: any) => {
      // 合并读取 storage 数据
      const link = uni.getStorageSync("link");
      const companyUserId = uni.getStorageSync("companyUserId");
      const recruitUserId = uni.getStorageSync("recruitUserId");
      const Identity = uni.getStorageSync("Identity");
      const postId = uni.getStorageSync("postId");
      const type = uni.getStorageSync("type");
      const shopUserId = uni.getStorageSync("shopUserId");
      const userLoginType = uni.getStorageSync("userLoginType");
      const userId = uni.getStorageSync("userId"); // 修复此处错误
      const userType = uni.getStorageSync("userType");
      // 异步保存用户信息
      uni.setStorage({
        key: "userInfo",
        data: JSON.stringify({
          ...loginInfo,
          TIMPush: undefined,
          pushConfig: {},
        }),
      });
      // 设置在线状态
      TUIUserService.switchUserStatus({ displayOnlineStatus: true });
      if (res.data) {
        const userTypeNum = parseInt(userLoginType);
        // 构建 conversationId
        // userTypeNum>0为商家向用户发  商家的IMID默认接收到的就是带ABC的ID
        // userTypeNum<=0时为用户像商家发 用户向商家发 需要进入商家的会话，商家的会话时商家的imID需要带ABCD
        // usertype:0 此房源为普通用户身份发布， 会话id中不带C，usertype:1 此房源为商家身份发布， 会话id中带C
        const conversationMap = {
          job: `C2C${userTypeNum > 0 ? recruitUserId : "A" + companyUserId}`,
          house: `C2C${userTypeNum > 0 ? shopUserId : userType > 0 ? "C" + shopUserId : shopUserId}`,
          homemaking: `C2C${userTypeNum > 0 ? shopUserId : "E" + shopUserId}`,
        };

        const conversationId = conversationMap[type];
        if (conversationId) {
          TUIConversationService.switchConversation(conversationId);
        }
        // 页面跳转逻辑
        if (link) {
          if (type === "job") {
            uni.redirectTo({
              url: `/TUIKit/components/TUIChat/index?companyUserId=${companyUserId}&recruitUserId=${recruitUserId}&postId=${postId}`,
            });
          } else {
            uni.redirectTo({
              url: `/TUIKit-${capitalize(type)}/components/TUIChat/index`,
            });
          }
        } else {
          handleRedirectBasedOnIdentity(Identity, loginInfo.userID);
        }
      }

      return res;
    })
    .catch((error) => {
      console.error("登录聊天失败", error);
      uni.showToast({ title: "登录失败，请重试", icon: "none" });
      throw error; // 抛出错误供上层处理
    });
};

// 封装跳转逻辑
const handleRedirectBasedOnIdentity = (identity, userID) => {
  const isJob = identity === "job";
  const isMerchant = /[ABCDEFGHIJKLMNO]/.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,
        });
      },
    });
  }
};
