"use strict";
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
const vue = require("vue");
const TUIRoomEngine = require("@tencentcloud/tuiroom-engine-js");
const uikitBaseComponentVue3 = require("@tencentcloud/uikit-base-component-vue3");
const room = require("tuikit-atomicx-vue3/room");
const _hoisted_1 = { class: "dialog-message" };
const _hoisted_2 = { class: "button-container" };
const _hoisted_3 = { class: "button-container" };
const _sfc_main = /* @__PURE__ */ vue.defineComponent({
  __name: "StandardLeave",
  props: {
    emitFunction: { type: Function }
  },
  setup(__props) {
    const { t } = uikitBaseComponentVue3.useUIKit();
    const props = __props;
    const {
      currentRoom,
      leaveRoom: leaveRoomStateApi,
      endRoom: endRoomStateApi
    } = room.useRoomState();
    const { localParticipant, participantList, transferOwner } = room.useRoomParticipantState();
    const showTransferDialog = vue.ref(false);
    const showConfirmDialog = vue.ref(false);
    const selectedUserId = vue.ref("");
    const isTransferring = vue.ref(false);
    const isEnding = vue.ref(false);
    const otherParticipants = vue.computed(
      () => participantList.value.filter(
        (participant) => {
          var _a;
          return participant.userId !== ((_a = localParticipant.value) == null ? void 0 : _a.userId);
        }
      )
    );
    const dialogMessage = vue.computed(() => {
      if (otherParticipants.value.length === 0) {
        return t("Room.LeaveRoomTip");
      }
      return t("Room.ConfirmLeaveTip");
    });
    const leaveRoom = async () => {
      try {
        return await leaveRoomStateApi();
      } catch (_error) {
        if (_error.code === TUIRoomEngine.TUIErrorCode.ERR_INVALID_PARAMETER) {
          return Promise.resolve();
        }
        throw _error;
      }
    };
    const endRoom = async () => {
      try {
        return await endRoomStateApi();
      } catch (_error) {
        if (_error.code === TUIRoomEngine.TUIErrorCode.ERR_INVALID_PARAMETER) {
          return Promise.resolve();
        }
        throw _error;
      }
    };
    const performLeave = async () => {
      var _a;
      try {
        if (!((_a = currentRoom.value) == null ? void 0 : _a.roomId)) {
          return;
        }
        await leaveRoom();
        props.emitFunction("leave");
      } catch (_error) {
        uikitBaseComponentVue3.TUIToast.error({ message: t("Room.LeaveRoomFailed") });
      }
    };
    const handleEndRoom = async () => {
      var _a;
      if (!((_a = currentRoom.value) == null ? void 0 : _a.roomId) || isEnding.value) {
        return;
      }
      try {
        isEnding.value = true;
        await endRoom();
        showConfirmDialog.value = false;
        props.emitFunction("end");
      } catch (_error) {
        uikitBaseComponentVue3.TUIToast.error({ message: t("Room.EndRoomFailed") });
      } finally {
        isEnding.value = false;
      }
    };
    const autoTransferAndLeave = async () => {
      var _a;
      if (otherParticipants.value.length !== 1 || !((_a = currentRoom.value) == null ? void 0 : _a.roomId)) {
        return;
      }
      try {
        const targetParticipant = otherParticipants.value[0];
        await transferOwner({ userId: targetParticipant.userId });
        await leaveRoom();
        props.emitFunction("leave");
      } catch (_error) {
        uikitBaseComponentVue3.TUIToast.error({ message: t("Room.TransferAndLeaveFailed") });
      }
    };
    const handleLeaveFromConfirmDialog = () => {
      showConfirmDialog.value = false;
      if (otherParticipants.value.length === 0) {
        performLeave();
        return;
      }
      if (otherParticipants.value.length === 1) {
        autoTransferAndLeave();
        return;
      }
      showTransferDialog.value = true;
      selectedUserId.value = "";
    };
    const handleTransferAndLeave = async () => {
      var _a;
      if (!selectedUserId.value || !((_a = currentRoom.value) == null ? void 0 : _a.roomId) || isTransferring.value) {
        return;
      }
      try {
        isTransferring.value = true;
        await transferOwner({ userId: selectedUserId.value });
        await leaveRoom();
        showTransferDialog.value = false;
        props.emitFunction("leave");
      } catch (_error) {
        uikitBaseComponentVue3.TUIToast.error({ message: t("Room.TransferAndLeaveFailed") });
      } finally {
        isTransferring.value = false;
      }
    };
    const handleLeaveRoom = () => {
      var _a, _b;
      if (!((_a = currentRoom.value) == null ? void 0 : _a.roomId)) {
        return;
      }
      const isOwner = ((_b = localParticipant.value) == null ? void 0 : _b.role) === room.RoomParticipantRole.Owner;
      if (!isOwner) {
        uikitBaseComponentVue3.TUIMessageBox.confirm({
          title: t("Room.ConfirmLeaveTitle"),
          content: t("Room.ConfirmLeaveRoom"),
          callback: (action) => {
            if (action === "confirm") {
              performLeave();
            }
          }
        });
        return;
      }
      showConfirmDialog.value = true;
    };
    return (_ctx, _cache) => {
      var _a;
      return vue.openBlock(), vue.createElementBlock(vue.Fragment, null, [
        vue.createVNode(vue.unref(uikitBaseComponentVue3.TUIButton), {
          color: "red",
          disabled: !((_a = vue.unref(currentRoom)) == null ? void 0 : _a.roomId),
          onClick: handleLeaveRoom
        }, {
          default: vue.withCtx(() => [
            vue.createTextVNode(vue.toDisplayString(vue.unref(t)("Room.LeaveRoom")), 1)
          ]),
          _: 1
        }, 8, ["disabled"]),
        vue.createVNode(vue.unref(uikitBaseComponentVue3.TUIDialog), {
          visible: showConfirmDialog.value,
          "onUpdate:visible": _cache[1] || (_cache[1] = ($event) => showConfirmDialog.value = $event),
          title: vue.unref(t)("Room.ConfirmLeaveTitle")
        }, {
          footer: vue.withCtx(() => [
            vue.createElementVNode("div", _hoisted_2, [
              vue.createVNode(vue.unref(uikitBaseComponentVue3.TUIButton), {
                color: "red",
                style: { "min-width": "88px" },
                loading: isEnding.value,
                onClick: handleEndRoom
              }, {
                default: vue.withCtx(() => [
                  vue.createTextVNode(vue.toDisplayString(vue.unref(t)("Room.EndRoom")), 1)
                ]),
                _: 1
              }, 8, ["loading"]),
              vue.createVNode(vue.unref(uikitBaseComponentVue3.TUIButton), {
                type: "primary",
                style: { "min-width": "88px" },
                onClick: handleLeaveFromConfirmDialog
              }, {
                default: vue.withCtx(() => [
                  vue.createTextVNode(vue.toDisplayString(vue.unref(t)("Room.LeaveRoom")), 1)
                ]),
                _: 1
              }),
              vue.createVNode(vue.unref(uikitBaseComponentVue3.TUIButton), {
                style: { "min-width": "88px" },
                onClick: _cache[0] || (_cache[0] = ($event) => showConfirmDialog.value = false)
              }, {
                default: vue.withCtx(() => [
                  vue.createTextVNode(vue.toDisplayString(vue.unref(t)("Room.Cancel")), 1)
                ]),
                _: 1
              })
            ])
          ]),
          default: vue.withCtx(() => [
            vue.createElementVNode("div", _hoisted_1, vue.toDisplayString(dialogMessage.value), 1)
          ]),
          _: 1
        }, 8, ["visible", "title"]),
        vue.createVNode(vue.unref(uikitBaseComponentVue3.TUIDialog), {
          visible: showTransferDialog.value,
          "onUpdate:visible": _cache[4] || (_cache[4] = ($event) => showTransferDialog.value = $event),
          title: vue.unref(t)("Room.SelectNewHost")
        }, {
          footer: vue.withCtx(() => [
            vue.createElementVNode("div", _hoisted_3, [
              vue.createVNode(vue.unref(uikitBaseComponentVue3.TUIButton), {
                type: "primary",
                style: { "min-width": "88px" },
                disabled: !selectedUserId.value,
                loading: isTransferring.value,
                onClick: handleTransferAndLeave
              }, {
                default: vue.withCtx(() => [
                  vue.createTextVNode(vue.toDisplayString(vue.unref(t)("Room.TransferAndLeave")), 1)
                ]),
                _: 1
              }, 8, ["disabled", "loading"]),
              vue.createVNode(vue.unref(uikitBaseComponentVue3.TUIButton), {
                style: { "min-width": "88px" },
                onClick: _cache[3] || (_cache[3] = ($event) => showTransferDialog.value = false)
              }, {
                default: vue.withCtx(() => [
                  vue.createTextVNode(vue.toDisplayString(vue.unref(t)("Room.Cancel")), 1)
                ]),
                _: 1
              })
            ])
          ]),
          default: vue.withCtx(() => [
            vue.createVNode(vue.unref(uikitBaseComponentVue3.TUISelect), {
              modelValue: selectedUserId.value,
              "onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => selectedUserId.value = $event),
              placeholder: vue.unref(t)("Room.PleaseSelectNewHost"),
              style: { "width": "100%" }
            }, {
              default: vue.withCtx(() => [
                (vue.openBlock(true), vue.createElementBlock(vue.Fragment, null, vue.renderList(otherParticipants.value, (participant) => {
                  return vue.openBlock(), vue.createBlock(vue.unref(uikitBaseComponentVue3.TUIOption), {
                    key: participant.userId,
                    label: participant.userName || participant.userId,
                    value: participant.userId
                  }, null, 8, ["label", "value"]);
                }), 128))
              ]),
              _: 1
            }, 8, ["modelValue", "placeholder"])
          ]),
          _: 1
        }, 8, ["visible", "title"])
      ], 64);
    };
  }
});
exports.default = _sfc_main;
