"use strict";
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
const Vue = require("vue");
const TUIRoomEngine = require("@tencentcloud/tuiroom-engine-js");
const useRoomEngine = require("./useRoomEngine.js");
const Message = require("../components/common/base/Message/Message.js");
const message = require("../constants/message.js");
const room = require("../stores/room.js");
const pinia = require("pinia");
const index = require("../locales/index.js");
const index$1 = require("../utils/common/logger/index.js");
const basic = require("../stores/basic.js");
const index$2 = require("../components/common/base/Notification/index.js");
const environment = require("../utils/environment.js");
const roomEngine = useRoomEngine.default();
function useMasterApplyControl() {
  const roomStore = room.useRoomStore();
  const basicStore = basic.useBasicStore();
  const { applyToAnchorList } = pinia.storeToRefs(roomStore);
  const { showApplyUserList } = pinia.storeToRefs(basicStore);
  const { t } = index.useI18n();
  let notification;
  const applyToAnchorUserIdList = Vue.computed(
    () => applyToAnchorList.value.map((item) => item.userId)
  );
  const applyToAnchorUserCount = Vue.computed(() => applyToAnchorList.value.length);
  function onRequestReceived(eventInfo) {
    const { requestAction, requestId, userId, timestamp } = eventInfo.request;
    if (requestAction === TUIRoomEngine.TUIRequestAction.kRequestToTakeSeat) {
      userId && roomStore.addApplyToAnchorUser({ userId, requestId, timestamp });
    }
  }
  function onRequestCancelled(eventInfo) {
    const { requestId } = eventInfo;
    roomStore.removeApplyToAnchorUser(requestId);
  }
  function onRequestProcessed(eventInfo) {
    const { requestId } = eventInfo;
    roomStore.removeApplyToAnchorUser(requestId);
  }
  async function handleUserApply(applyUserId, agree) {
    var _a;
    try {
      const userInfo = roomStore.userInfoObj[applyUserId];
      const requestId = userInfo.applyToAnchorRequestId;
      if (requestId) {
        await ((_a = roomEngine.instance) == null ? void 0 : _a.responseRemoteRequest({
          requestId,
          agree
        }));
        roomStore.removeApplyToAnchorUser(requestId);
      } else {
        index$1.default.warn(
          "Failed to process the stage application. The data is abnormal. Please try again！",
          userInfo
        );
      }
    } catch (error) {
      if (error.code === TUIRoomEngine.TUIErrorCode.ERR_ALL_SEAT_OCCUPIED) {
        Message.default({ type: "warning", message: t("The stage is full") });
      } else {
        index$1.default.error("Failure to process a user request", error);
      }
    }
  }
  async function agreeUserOnStage(userInfo) {
    var _a;
    try {
      const requestId = userInfo.applyToAnchorRequestId;
      if (requestId) {
        await ((_a = roomEngine.instance) == null ? void 0 : _a.responseRemoteRequest({
          requestId,
          agree: true
        }));
        roomStore.removeApplyToAnchorUser(requestId);
      } else {
        index$1.default.warn(
          "Failed to process the stage application. The data is abnormal. Please try again！",
          userInfo
        );
      }
    } catch (error) {
      if (error.code === TUIRoomEngine.TUIErrorCode.ERR_ALL_SEAT_OCCUPIED) {
        Message.default({ type: "warning", message: t("The stage is full") });
      } else {
        index$1.default.error("Failed application for consent to go on stage", error);
      }
    }
  }
  async function denyUserOnStage(userInfo) {
    var _a;
    const requestId = userInfo.applyToAnchorRequestId;
    if (requestId) {
      await ((_a = roomEngine.instance) == null ? void 0 : _a.responseRemoteRequest({
        requestId,
        agree: false
      }));
      roomStore.removeApplyToAnchorUser(requestId);
    } else {
      index$1.default.warn(
        "Failed to process the stage application. The data is abnormal. Please try again！",
        userInfo
      );
    }
  }
  async function handleAllUserApply(isAgreeOrRejectAllUserApply) {
    var _a;
    let hasErrorOccurred = false;
    const applyUserList = applyToAnchorList.value.map((item) => ({
      userId: item.userId,
      userName: item.nameCard || item.userName,
      applyToAnchorRequestId: item.applyToAnchorRequestId
    }));
    for (const { applyToAnchorRequestId } of applyUserList) {
      const action = isAgreeOrRejectAllUserApply ? "Agree" : "Reject";
      const actionFailedMessage = `${action} sb on stage failed, please retry`;
      try {
        if (applyToAnchorRequestId) {
          await ((_a = roomEngine.instance) == null ? void 0 : _a.responseRemoteRequest({
            requestId: applyToAnchorRequestId,
            agree: isAgreeOrRejectAllUserApply
          }));
          roomStore.removeApplyToAnchorUser(applyToAnchorRequestId);
        }
      } catch (error) {
        if (!hasErrorOccurred) {
          index$1.default.error(actionFailedMessage);
          Message.default({
            type: "warning",
            message: t("The stage is full"),
            duration: message.MESSAGE_DURATION.NORMAL
          });
          hasErrorOccurred = true;
        }
      }
    }
  }
  TUIRoomEngine.once("ready", () => {
    var _a, _b, _c;
    (_a = roomEngine.instance) == null ? void 0 : _a.on(TUIRoomEngine.TUIRoomEvents.onRequestReceived, onRequestReceived);
    (_b = roomEngine.instance) == null ? void 0 : _b.on(
      TUIRoomEngine.TUIRoomEvents.onRequestCancelled,
      onRequestCancelled
    );
    (_c = roomEngine.instance) == null ? void 0 : _c.on(
      TUIRoomEngine.TUIRoomEvents.onRequestProcessed,
      onRequestProcessed
    );
  });
  Vue.onBeforeUnmount(() => {
    var _a, _b, _c;
    (_a = roomEngine.instance) == null ? void 0 : _a.off(
      TUIRoomEngine.TUIRoomEvents.onRequestReceived,
      onRequestReceived
    );
    (_b = roomEngine.instance) == null ? void 0 : _b.off(
      TUIRoomEngine.TUIRoomEvents.onRequestCancelled,
      onRequestCancelled
    );
    (_c = roomEngine.instance) == null ? void 0 : _c.off(
      TUIRoomEngine.TUIRoomEvents.onRequestProcessed,
      onRequestProcessed
    );
  });
  async function inviteUserOnStage(userInfo) {
    var _a;
    const { userId } = userInfo;
    const request = await ((_a = roomEngine.instance) == null ? void 0 : _a.takeUserOnSeatByAdmin({
      seatIndex: -1,
      userId,
      timeout: 60,
      requestCallback: (callbackInfo) => {
        const { requestCallbackType, userId: userId2, code } = callbackInfo;
        const userName = roomStore.getUserName(userId2);
        roomStore.removeInviteToAnchorUser(userId2);
        switch (requestCallbackType) {
          case TUIRoomEngine.TUIRequestCallbackType.kRequestAccepted:
            Message.default({
              type: "success",
              message: `${userName || userId2} ${t("accepted the invitation to the stage")}`,
              duration: message.MESSAGE_DURATION.NORMAL
            });
            break;
          case TUIRoomEngine.TUIRequestCallbackType.kRequestRejected:
            Message.default({
              type: "warning",
              message: `${userName || userId2} ${t("declined the invitation to the stage")}`,
              duration: message.MESSAGE_DURATION.NORMAL
            });
            break;
          case TUIRoomEngine.TUIRequestCallbackType.kRequestTimeout:
            Message.default({
              type: "warning",
              message: t("The invitation to sb to go on stage has timed out", {
                name: userName || userId2
              }),
              duration: message.MESSAGE_DURATION.NORMAL
            });
            break;
          case TUIRoomEngine.TUIRequestCallbackType.kRequestError:
            if (code === TUIRoomEngine.TUIErrorCode.ERR_REQUEST_ID_REPEAT) {
              Message.default({
                type: "warning",
                message: t(
                  "This member has already received the same request, please try again later"
                ),
                duration: message.MESSAGE_DURATION.NORMAL
              });
            }
            break;
        }
      }
    }));
    if (request && request.requestId) {
      roomStore.addInviteToAnchorUser({ userId, requestId: request.requestId });
    }
  }
  function cancelInviteUserOnStage(userInfo) {
    var _a;
    const { userId, inviteToAnchorRequestId } = userInfo;
    roomStore.removeInviteToAnchorUser(userId);
    if (inviteToAnchorRequestId) {
      (_a = roomEngine.instance) == null ? void 0 : _a.cancelRequest({
        requestId: inviteToAnchorRequestId
      });
    }
  }
  function kickUserOffStage(userInfo) {
    var _a;
    (_a = roomEngine.instance) == null ? void 0 : _a.kickUserOffSeatByAdmin({
      seatIndex: -1,
      userId: userInfo.userId
    });
  }
  const handleConfirm = async (onlyOneUserTakeStage, userId) => {
    if (environment.isMobile) {
      basicStore.setSidebarOpenStatus(true);
      basicStore.setSidebarName("apply");
    } else {
      if (onlyOneUserTakeStage) {
        handleUserApply(userId, true);
      } else {
        basicStore.setShowApplyUserList(true);
      }
    }
  };
  const handleCancel = async (onlyOneUserTakeStage, userId) => {
    if (!environment.isMobile && onlyOneUserTakeStage) {
      handleUserApply(userId, false);
    }
  };
  function hideApplyList() {
    basicStore.setShowApplyUserList(false);
  }
  function handleShowNotification() {
    Vue.watch(applyToAnchorUserIdList, (newVal, oldVal) => {
      var _a, _b, _c;
      if (newVal.length === oldVal.length && newVal === oldVal) {
        return;
      }
      if (newVal.length === 0) {
        notification && notification.close();
        notification = null;
        return;
      }
      const onlyOneUserTakeStage = newVal.length === 1;
      const firstUser = applyToAnchorList.value[0];
      const lastIndex = applyToAnchorList.value.length - 1;
      const userName = ((_a = applyToAnchorList.value[lastIndex]) == null ? void 0 : _a.nameCard) || ((_b = applyToAnchorList.value[lastIndex]) == null ? void 0 : _b.userName) || ((_c = applyToAnchorList.value[lastIndex]) == null ? void 0 : _c.userId);
      const message2 = onlyOneUserTakeStage ? `${userName} ${t("Applying for the stage")}` : `${userName} ${t("and so on number people applying to stage", { number: applyToAnchorList.value.length })}`;
      const confirmButtonText = environment.isMobile ? t("Check") : onlyOneUserTakeStage ? t("Agree to the stage") : t("Check");
      const cancelButtonText = environment.isMobile ? void 0 : onlyOneUserTakeStage ? t("Reject") : t("Neglect");
      const confirm = () => handleConfirm(onlyOneUserTakeStage, firstUser == null ? void 0 : firstUser.userId);
      const cancel = () => handleCancel(onlyOneUserTakeStage, firstUser == null ? void 0 : firstUser.userId);
      notification = index$2.default({
        message: message2,
        confirmButtonText,
        cancelButtonText,
        confirm,
        cancel
      });
    });
  }
  return {
    t,
    roomStore,
    showApplyUserList,
    hideApplyList,
    applyToAnchorUserCount,
    applyToAnchorList,
    // Process the user's application for accessing the stage (agree/reject)
    handleUserApply,
    // Allow ordinary users to take the stage
    agreeUserOnStage,
    // Reject ordinary users to take the stage
    denyUserOnStage,
    // Invite users to the stage
    inviteUserOnStage,
    // Cancel invite users to the stage
    cancelInviteUserOnStage,
    // Kick the user off the stage
    kickUserOffStage,
    // Handle all user requests
    handleAllUserApply,
    handleShowNotification
  };
}
exports.default = useMasterApplyControl;
