"use strict";
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
const Vue = require("vue");
const index = require("../../../locales/index.js");
const room = require("../../../stores/room.js");
const useRoomEngine = require("../../../hooks/useRoomEngine.js");
const basic = require("../../../stores/basic.js");
const useMasterApplyControl = require("../../../hooks/useMasterApplyControl.js");
const TUIRoomEngine = require("@tencentcloud/tuiroom-engine-js");
const AudioOpenIcon = require("../../common/icons/AudioOpenIcon.vue.js");
const VideoOpenIcon = require("../../common/icons/VideoOpenIcon.vue.js");
const ChatForbiddenIcon = require("../../common/icons/ChatForbiddenIcon.vue.js");
const KickOutIcon = require("../../common/icons/KickOutIcon.vue.js");
const InviteOnStageIcon = require("../../common/icons/InviteOnStageIcon.vue.js");
const DenyOnStageIcon = require("../../common/icons/DenyOnStageIcon.vue.js");
const OnStageIcon = require("../../common/icons/OnStageIcon.vue.js");
const OffStageIcon = require("../../common/icons/OffStageIcon.vue.js");
const TransferOwnerIcon = require("../../common/icons/TransferOwnerIcon.vue.js");
const SetAdminIcon = require("../../common/icons/SetAdminIcon.vue.js");
const RevokeAdminIcon = require("../../common/icons/RevokeAdminIcon.vue.js");
const EditNameCardIcon = require("../../common/icons/EditNameCardIcon.vue.js");
const pinia = require("pinia");
const Message = require("../../common/base/Message/Message.js");
const message = require("../../../constants/message.js");
const useMitt = require("../../../hooks/useMitt.js");
const useMemberItemHooks = require("../MemberItem/useMemberItemHooks.js");
require("../../../services/main.js");
const roomService = require("../../../services/roomService.js");
require("mitt");
require("../../../services/manager/roomActionManager.js");
require("@tencentcloud/tui-core");
const environment = require("../../../utils/environment.js");
const utils = require("../../../utils/utils.js");
function useMemberControl(props) {
  const roomEngine = useRoomEngine.default();
  const { t } = index.useI18n();
  const basicStore = basic.useBasicStore();
  const roomStore = room.useRoomStore();
  const isDialogVisible = Vue.ref(false);
  const isShowInput = Vue.ref(false);
  const editorInputEle = Vue.ref();
  const editorInputEleContainer = Vue.ref();
  const tempUserName = Vue.ref(props.userInfo.nameCard || props.userInfo.userName);
  const dialogData = Vue.ref({
    title: "",
    content: "",
    confirmText: "",
    actionType: "",
    showInput: false
  });
  const kickOffDialogContent = Vue.computed(
    () => t("whether to kick sb off the room", {
      name: roomService.roomService.getDisplayName(props.userInfo)
    })
  );
  const transferOwnerTitle = Vue.computed(
    () => t("Transfer the roomOwner to sb", {
      name: roomService.roomService.getDisplayName(props.userInfo)
    })
  );
  const {
    isFreeSpeakMode,
    isSpeakAfterTakingSeatMode,
    localUser,
    isGeneralUser,
    anchorUserList,
    maxSeatCount
  } = pinia.storeToRefs(roomStore);
  const {
    agreeUserOnStage,
    denyUserOnStage,
    inviteUserOnStage,
    cancelInviteUserOnStage,
    kickUserOffStage
  } = useMasterApplyControl.default();
  const { isCanOperateMySelf } = useMemberItemHooks.default(props.userInfo);
  const isMe = Vue.computed(() => basicStore.userId === props.userInfo.userId);
  const isTargetUserAnchor = Vue.computed(() => props.userInfo.onSeat === true);
  const isTargetUserAudience = Vue.computed(() => props.userInfo.onSeat !== true);
  const controlList = Vue.computed(() => {
    if (isCanOperateMySelf.value) {
      return [changeUserNameCard.value];
    }
    const agreeOrDenyStageList = props.userInfo.isUserApplyingToAnchor ? [agreeOnStage.value, denyOnStage.value] : [];
    const inviteStageList = isTargetUserAudience.value && !props.userInfo.isUserApplyingToAnchor ? [inviteOnStage.value] : [];
    const onStageControlList = isTargetUserAnchor.value ? [audioControl.value, videoControl.value, makeOffStage.value] : [];
    const controlListObj = {
      freeSpeak: {
        [TUIRoomEngine.TUIRole.kRoomOwner]: [
          audioControl.value,
          videoControl.value,
          chatControl.value,
          setOrRevokeAdmin.value,
          transferOwner.value,
          kickUser.value,
          changeUserNameCard.value
        ],
        [TUIRoomEngine.TUIRole.kAdministrator]: [
          audioControl.value,
          videoControl.value,
          chatControl.value,
          changeUserNameCard.value
        ]
      },
      speakAfterTakeSeat: {
        [TUIRoomEngine.TUIRole.kRoomOwner]: [
          ...inviteStageList,
          ...onStageControlList,
          ...agreeOrDenyStageList,
          setOrRevokeAdmin.value,
          transferOwner.value,
          chatControl.value,
          kickUser.value,
          changeUserNameCard.value
        ],
        [TUIRoomEngine.TUIRole.kAdministrator]: [
          ...inviteStageList,
          ...onStageControlList,
          ...agreeOrDenyStageList,
          chatControl.value,
          changeUserNameCard.value
        ]
      }
    };
    if (isFreeSpeakMode.value) {
      return controlListObj.freeSpeak[localUser.value.userRole] || [];
    }
    if (isSpeakAfterTakingSeatMode.value) {
      return controlListObj.speakAfterTakeSeat[localUser.value.userRole] || [];
    }
    return [];
  });
  const audioControl = Vue.computed(() => ({
    key: "audioControl",
    icon: AudioOpenIcon.default,
    title: props.userInfo.hasAudioStream ? t("Mute") : t("Unmute"),
    func: muteUserAudio
  }));
  const videoControl = Vue.computed(() => {
    const videoControlTitle = props.userInfo.hasVideoStream ? t("Disable video") : t("Enable video");
    return {
      key: "videoControl",
      icon: VideoOpenIcon.default,
      title: videoControlTitle,
      func: muteUserVideo
    };
  });
  const chatControl = Vue.computed(() => ({
    key: "chatControl",
    icon: ChatForbiddenIcon.default,
    title: props.userInfo.isMessageDisabled ? t("Enable chat") : t("Disable chat"),
    func: disableUserChat
  }));
  const transferOwner = Vue.computed(() => ({
    key: "transferOwner",
    icon: TransferOwnerIcon.default,
    title: t("Make host"),
    func: () => handleOpenDialog("transferOwner")
  }));
  const setOrRevokeAdmin = Vue.computed(() => ({
    key: "setOrRevokeAdmin",
    icon: props.userInfo.userRole === TUIRoomEngine.TUIRole.kAdministrator ? RevokeAdminIcon.default : SetAdminIcon.default,
    title: props.userInfo.userRole === TUIRoomEngine.TUIRole.kAdministrator ? t("Remove administrator") : t("Set as administrator"),
    func: handleSetOrRevokeAdmin
  }));
  const kickUser = Vue.computed(() => ({
    key: "kickUser",
    icon: KickOutIcon.default,
    title: t("Kick out"),
    func: () => handleOpenDialog("kickUser")
  }));
  const inviteOnStage = Vue.computed(() => ({
    key: "inviteOnStage",
    icon: props.userInfo.isInvitingUserToAnchor ? DenyOnStageIcon.default : InviteOnStageIcon.default,
    title: props.userInfo.isInvitingUserToAnchor ? t("Cancel stage") : t("Invite stage"),
    func: toggleInviteUserOnStage
  }));
  const agreeOnStage = Vue.computed(() => ({
    key: "agreeOnStage",
    icon: OnStageIcon.default,
    title: t("Agree to the stage"),
    func: agreeUserOnStage
  }));
  const denyOnStage = Vue.computed(() => ({
    key: "denyOnStage",
    icon: DenyOnStageIcon.default,
    title: t("Refuse stage"),
    func: denyUserOnStage
  }));
  const makeOffStage = Vue.computed(() => ({
    key: "makeOffStage",
    icon: OffStageIcon.default,
    title: t("Step down"),
    func: kickUserOffStage
  }));
  const changeUserNameCard = Vue.computed(() => ({
    key: "changeUserNameCard",
    icon: EditNameCardIcon.default,
    title: t("change name"),
    func: () => handleOpenDialog("changeUserNameCard")
  }));
  async function toggleInviteUserOnStage(userInfo) {
    const { isInvitingUserToAnchor } = userInfo;
    if (isInvitingUserToAnchor) {
      cancelInviteUserOnStage(userInfo);
    } else {
      if (anchorUserList.value.length === maxSeatCount.value) {
        Message.default({
          type: "warning",
          message: `${t("The stage is full")}`,
          duration: message.MESSAGE_DURATION.NORMAL
        });
        return;
      }
      inviteUserOnStage(userInfo);
    }
  }
  async function muteUserAudio(userInfo) {
    var _a, _b;
    if (userInfo.hasAudioStream) {
      await ((_a = roomEngine.instance) == null ? void 0 : _a.closeRemoteDeviceByAdmin({
        userId: userInfo.userId,
        device: TUIRoomEngine.TUIMediaDevice.kMicrophone
      }));
    } else {
      if (userInfo.isRequestingUserOpenMic) {
        Message.default({
          type: "info",
          message: `${t("An invitation to open the microphone has been sent to sb.", { name: roomService.roomService.getDisplayName(userInfo) })}`,
          duration: message.MESSAGE_DURATION.NORMAL
        });
        return;
      }
      const request = await ((_b = roomEngine.instance) == null ? void 0 : _b.openRemoteDeviceByAdmin({
        userId: userInfo.userId,
        device: TUIRoomEngine.TUIMediaDevice.kMicrophone,
        timeout: 0,
        requestCallback: (callbackInfo) => {
          roomStore.setRequestUserOpenMic({
            userId: userInfo.userId,
            isRequesting: false
          });
          const { requestCallbackType, code } = callbackInfo;
          switch (requestCallbackType) {
            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;
          }
        }
      }));
      Message.default({
        type: "info",
        message: `${t("An invitation to open the microphone has been sent to sb.", { name: roomService.roomService.getDisplayName(userInfo) })}`,
        duration: message.MESSAGE_DURATION.NORMAL
      });
      if (request && request.requestId) {
        roomStore.setRequestUserOpenMic({
          userId: userInfo.userId,
          isRequesting: true,
          requestId: request.requestId
        });
      }
    }
  }
  async function muteUserVideo(userInfo) {
    var _a, _b;
    if (userInfo.hasVideoStream) {
      await ((_a = roomEngine.instance) == null ? void 0 : _a.closeRemoteDeviceByAdmin({
        userId: userInfo.userId,
        device: TUIRoomEngine.TUIMediaDevice.kCamera
      }));
    } else {
      if (userInfo.isRequestingUserOpenCamera) {
        Message.default({
          type: "info",
          message: `${t("An invitation to open the camera has been sent to sb.", { name: roomService.roomService.getDisplayName(userInfo) })}`,
          duration: message.MESSAGE_DURATION.NORMAL
        });
        return;
      }
      const request = await ((_b = roomEngine.instance) == null ? void 0 : _b.openRemoteDeviceByAdmin({
        userId: userInfo.userId,
        device: TUIRoomEngine.TUIMediaDevice.kCamera,
        timeout: 0,
        requestCallback: (callbackInfo) => {
          roomStore.setRequestUserOpenCamera({
            userId: userInfo.userId,
            isRequesting: false
          });
          const { requestCallbackType, code } = callbackInfo;
          switch (requestCallbackType) {
            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;
          }
        }
      }));
      Message.default({
        type: "info",
        message: `${t("An invitation to open the camera has been sent to sb.", { name: roomService.roomService.getDisplayName(userInfo) })}`,
        duration: message.MESSAGE_DURATION.NORMAL
      });
      if (request && request.requestId) {
        roomStore.setRequestUserOpenCamera({
          userId: userInfo.userId,
          isRequesting: true,
          requestId: request.requestId
        });
      }
    }
  }
  async function disableUserChat(userInfo) {
    var _a;
    const { isMessageDisabled } = userInfo;
    try {
      await ((_a = roomEngine.instance) == null ? void 0 : _a.disableSendingMessageByAdmin({
        userId: userInfo.userId,
        isDisable: !isMessageDisabled
      }));
      roomStore.setMuteUserChat(userInfo.userId, !isMessageDisabled);
    } catch (error) {
      Message.default({
        type: "error",
        message: t("Failed to disable chat"),
        duration: message.MESSAGE_DURATION.NORMAL
      });
    }
  }
  async function kickOffUser(userInfo) {
    var _a;
    await ((_a = roomEngine.instance) == null ? void 0 : _a.kickRemoteUserOutOfRoom({
      userId: userInfo.userId
    }));
    roomStore.removeRemoteUser(userInfo.userId);
  }
  async function handleTransferOwner(userInfo) {
    var _a, _b;
    const roomInfo = await ((_a = roomEngine.instance) == null ? void 0 : _a.fetchRoomInfo());
    if ((roomInfo == null ? void 0 : roomInfo.roomOwner) === roomStore.localUser.userId) {
      try {
        if (roomStore.localUser.hasScreenStream) {
          useMitt.default.emit("ScreenShare:stopScreenShare");
        }
        await ((_b = roomEngine.instance) == null ? void 0 : _b.changeUserRole({
          userId: userInfo.userId,
          userRole: TUIRoomEngine.TUIRole.kRoomOwner
        }));
        roomStore.setMasterUserId(userInfo.userId);
        Message.default({
          type: "success",
          message: t("The room owner has been transferred to sb", {
            name: roomService.roomService.getDisplayName(userInfo)
          }),
          duration: message.MESSAGE_DURATION.NORMAL
        });
      } catch (error) {
        Message.default({
          type: "error",
          message: t("Make host failed, please try again."),
          duration: message.MESSAGE_DURATION.NORMAL
        });
      }
    }
  }
  async function handleSetOrRevokeAdmin(userInfo) {
    var _a, _b;
    const newRole = userInfo.userRole === TUIRoomEngine.TUIRole.kGeneralUser ? TUIRoomEngine.TUIRole.kAdministrator : TUIRoomEngine.TUIRole.kGeneralUser;
    await ((_a = roomEngine.instance) == null ? void 0 : _a.changeUserRole({
      userId: userInfo.userId,
      userRole: newRole
    }));
    const updatedUserName = roomStore.getUserName(userInfo.userId);
    const tipMessage = newRole === TUIRoomEngine.TUIRole.kAdministrator ? `${t("sb has been set as administrator", { name: updatedUserName })}` : `${t("The administrator status of sb has been withdrawn", { name: updatedUserName })}`;
    Message.default({ type: "success", message: tipMessage });
    roomStore.setRemoteUserRole(userInfo.userId, newRole);
    if (newRole === TUIRoomEngine.TUIRole.kGeneralUser && userInfo.hasScreenStream) {
      await ((_b = roomEngine.instance) == null ? void 0 : _b.closeRemoteDeviceByAdmin({
        userId: userInfo.userId,
        device: TUIRoomEngine.TUIMediaDevice.kScreen
      }));
    }
  }
  function handleOpenDialog(action) {
    var _a;
    switch (action) {
      case "kickUser":
        isDialogVisible.value = true;
        dialogData.value = {
          title: t("Note"),
          content: kickOffDialogContent.value,
          confirmText: t("Confirm"),
          actionType: action,
          showInput: false
        };
        break;
      case "transferOwner":
        isDialogVisible.value = true;
        dialogData.value = {
          title: transferOwnerTitle.value,
          content: t(
            "After transfer the room owner, you will become a general user"
          ),
          confirmText: t("Confirm transfer"),
          actionType: action,
          showInput: false
        };
        break;
      case "changeUserNameCard":
        if (environment.isMobile) {
          isShowInput.value = true;
          (_a = document == null ? void 0 : document.body) == null ? void 0 : _a.appendChild(editorInputEleContainer.value);
        } else {
          isDialogVisible.value = true;
        }
        dialogData.value = {
          title: t("change name"),
          content: "",
          confirmText: t("Confirm"),
          actionType: action,
          showInput: true
        };
        break;
    }
  }
  const nameCardCheck = () => {
    const result = utils.calculateByteLength(tempUserName.value) <= 32;
    !result && Message.default({
      type: "warning",
      message: t("The user name cannot exceed 32 characters"),
      duration: message.MESSAGE_DURATION.NORMAL
    });
    return result;
  };
  async function handleChangeUserNameCard(userInfo) {
    var _a;
    if (!nameCardCheck()) return;
    try {
      await ((_a = roomEngine.instance) == null ? void 0 : _a.changeUserNameCard({
        userId: userInfo.userId,
        nameCard: tempUserName.value
      }));
      Message.default({
        type: "success",
        message: t("Name changed successfully"),
        duration: message.MESSAGE_DURATION.NORMAL
      });
    } catch (error) {
      Message.default({
        type: "error",
        message: t("change name failed, please try again."),
        duration: message.MESSAGE_DURATION.NORMAL
      });
    }
  }
  function handleAction(userInfo) {
    switch (dialogData.value.actionType) {
      case "kickUser":
        kickOffUser(userInfo);
        break;
      case "transferOwner":
        handleTransferOwner(userInfo);
        break;
      case "changeUserNameCard":
        handleChangeUserNameCard(userInfo);
        isShowInput.value = false;
    }
    isDialogVisible.value = false;
  }
  function handleCancelDialog() {
    tempUserName.value = props.userInfo.nameCard || props.userInfo.userName;
    isDialogVisible.value = false;
  }
  return {
    props,
    isMe,
    isGeneralUser,
    controlList,
    kickOffDialogContent,
    handleCancelDialog,
    handleAction,
    isDialogVisible,
    dialogData,
    tempUserName,
    isShowInput,
    editorInputEle,
    editorInputEleContainer
  };
}
exports.default = useMemberControl;
