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) => {
    let link = uni.getStorageSync("link");
    let companyUserId = uni.getStorageSync("companyUserId");
    let recruitUserId = uni.getStorageSync("recruitUserId");

    let Identity = uni.getStorageSync("Identity");
    let postId = uni.getStorageSync("postId");
    let type = uni.getStorageSync("type");

    if (type == "job" && recruitUserId) {
      TUIUserService.switchUserStatus({ displayOnlineStatus: true });
      TUIConversationService.switchConversation(`C2C${recruitUserId}`);
    }else if (type == "house" ) {
      TUIUserService.switchUserStatus({ displayOnlineStatus: true });
      TUIConversationService.switchConversation(`C2C${recruitUserId}`);
    }
    uni?.setStorage({
      key: "userInfo",
      data: JSON.stringify({
        ...loginInfo,
        TIMPush: undefined,
        pushConfig: {},
      }),
    });
    //跳转单聊
    if (link) {
      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?companyUserId=${companyUserId}&recruitUserId=${recruitUserId}&postId=${postId}`,
        });
      }
    }
    //跳转列表
    else {
      if (Identity == "job") {
        if (loginInfo.userID.includes("A")) {
          //求职
          uni?.reLaunch({
            url: "/TUIKit/components/TUIConversation/merChantSideIndex",
            success: () => {
              uni?.$emit("uikitLogin", res);
            },
          });
        } else {
          uni?.reLaunch({
            url: "/TUIKit/components/TUIConversation/index",
            success: () => {
              uni?.$emit("uikitLogin", res);
            },
          });
        }
      } else if (Identity == "house") {
        if (loginInfo.userID.includes("C")) {
          //房产
          uni?.reLaunch({
            url: "/TUIKit-House/components/TUIConversation/merChantSideIndex",
            success: () => {
              uni?.$emit("uikitLogin", res);
            },
          });
        } else {
          uni?.reLaunch({
            url: "/TUIKit-House/components/TUIConversation/index",
            success: () => {
              uni?.$emit("uikitLogin", res);
            },
          });
        }
      }
    }

    return res;
  });
};

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,
        });
      },
    });
  }
};
