import { defineStore } from "pinia";
import { ref } from "vue";
import { generateUserSig, updateHlwDoctor, getHlwDoctorList } from "@/api/hlw";
import { TUILogin } from "@tencentcloud/tui-core";
import Server from "../TUIKit/server";
import { memberStore } from "@/store/member";
import TUIChatEngine, { TUIStore, StoreName } from "@tencentcloud/chat-uikit-engine";
import { ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { tagsStore } from "@/store/tags";

export const useImStore = defineStore("im", () => {
  const router = useRouter();
  const { clear } = tagsStore()

  function imLogin(type) {
    const doctorNo = sessionStorage.getItem("doctorNo");
    return new Promise(async (resolve, reject) => {
      if (doctorNo) {
        try {
          // if (type === "online") updateHlwDoctorOnlineStatus("online");
          const { data } = await generateUserSig({ userId: doctorNo });
          const userSig = data.data;
          if (TUILogin.getContext().chat) TUILogin.logout();
          TUILogin.login({
            SDKAppID: data.sdkAppId,
            userID: doctorNo,
            userSig: userSig,
            useUploadPlugin: true,
            framework: "vue3",
          })
            .then(() => {
              resolve();
            })
            .catch((error) => {
              console.error("IM登录失败", error);
              reject(error);
            });
        } catch (error) {
          console.error("IM登录失败", error);
          reject(error);
        }
      } else {
        reject(new Error("SDKAppID or doctorNo is missing"));
      }
    });
  }

  async function imSDkInit() {
    const TUIChatKit = new Server();
    TUIChatKit.init();
  }

  async function imLogout() {
    await updateHlwDoctorOnlineStatus("offline");
    const { TUILogin } = await import("@tencentcloud/tui-core");
    if (TUILogin.getContext().chat) {
      TUILogin.logout()
        .then(() => {
          console.log("IM退出成功");
        })
        .catch((error) => {
          console.error("IM退出失败", error);
        });
    }
  }

  async function updateHlwDoctorOnlineStatus(newOnlineStatus) {
    await updateHlwDoctor({
      doctorNo: sessionStorage.getItem("doctorNo"),
      params: {
        onlineStatus: newOnlineStatus,
      },
    });
  }

  let onNetStateChange = function (state) {
    if (state === "disconnected") {
      ElMessageBox.alert("当前网络不可用, 请检查网络连接情况");
    }
  };

  // 医生IM 断开重新连接
  async function kickedOutWatch() {
    console.log("开始监听IM断开事件");
    TUIStore.watch(StoreName.USER, {
      kickedOut: onKickedOut,
      netStateChange: onNetStateChange,
    });
  }

  // 取消监听
  async function cancelKickedOutWatch() {
    console.log("取消监听IM断开事件");
    TUIStore.unwatch(StoreName.USER, {
      kickedOut: onKickedOut,
    });
  }

  function onKickedOut(state) {
    if (state === "multipleAccount") {
      // 提示被踢下线
      ElMessageBox.confirm("您的账号在其他设备登录，您已被踢下线", "提示", {
        confirmButtonText: "确定",
        type: "warning",
        showClose: false,
        showCancelButton: false,
        closeOnClickModal: false,
        closeOnPressEscape: false,
      }).then(async () => {
        onLogout();
      });
    }
  }

  // 退出登录
  async function onLogout() {
    if (!sessionStorage.getItem("doctorNo")) return;
    await imLogout();
    router.replace({ name: "LOGIN" });
    memberStore().setLogined("unlogin");
    clear()
  }

  return { imLogin, imSDkInit, imLogout, cancelKickedOutWatch, kickedOutWatch, onLogout, updateHlwDoctorOnlineStatus };
});
