import { defineComponent, ref, computed, onMounted, onUnmounted, withDirectives, openBlock, createElementBlock, normalizeClass, unref, createVNode, createElementVNode, toDisplayString, Fragment, renderList, createCommentVNode, vShow } from "vue";
import "../../services/main.mjs";
import { roomService } from "../../services/roomService.mjs";
import { EventType } from "../../services/types.mjs";
import { useI18n } from "../../locales/index.mjs";
import { TUIConferenceListManagerEvents } from "@tencentcloud/tuiroom-engine-js";
import "mitt";
import "../../services/manager/roomActionManager.mjs";
import "@tencentcloud/tui-core";
import SvgIcon from "../common/base/SvgIcon.vue.mjs";
import CalendarIcon from "../common/icons/CalendarIcon.vue.mjs";
import ApplyStageLabelIcon from "../common/icons/ApplyStageLabelIcon.vue.mjs";
import ScheduleRoomControl from "./ScheduleRoomControl.vue.mjs";
import LoadingScheduleIcon from "../common/icons/LoadingScheduleIcon.vue.mjs";
import { isMobile } from "../../utils/environment.mjs";
import { objectMerge } from "../../utils/utils.mjs";
const _hoisted_1 = {
  key: 0,
  class: "schedule-loading"
};
const _hoisted_2 = { class: "text" };
const _hoisted_3 = {
  key: 0,
  class: "schedule-room-container"
};
const _hoisted_4 = {
  key: 0,
  class: "schedule-room-date"
};
const _hoisted_5 = {
  key: 1,
  class: "schedule-no-body"
};
const _hoisted_6 = { class: "text" };
const _sfc_main = /* @__PURE__ */ defineComponent({
  __name: "ScheduleRoomList",
  props: {
    isShowScheduledConference: { type: Boolean, default: true }
  },
  emits: ["join-conference"],
  setup(__props, { emit: __emit }) {
    const { t } = useI18n();
    const scheduleRoomList = ref([]);
    const emit = __emit;
    const isShowLoading = ref(true);
    const joinConference = (options) => {
      emit("join-conference", options);
    };
    const props = __props;
    function sortScheduleRoomList() {
      return scheduleRoomList.value.sort(
        (a, b) => a.scheduleStartTime - b.scheduleStartTime
      );
    }
    const sortedScheduleRoomList = computed(() => sortScheduleRoomList());
    const fetchScheduledData = async (cursor = "", result = []) => {
      const res = await roomService.scheduleConferenceManager.fetchScheduledConferenceList({
        cursor,
        count: 20
      });
      (res == null ? void 0 : res.conferenceList) && result.push(...(res == null ? void 0 : res.conferenceList) || []);
      if (res.cursor !== "") {
        await fetchScheduledData(res.cursor, result);
      }
      return result;
    };
    const scheduleContentList = computed(
      () => sortedScheduleRoomList.value.map((item, index, arr) => {
        if (index === 0 || getScheduleDate(item.scheduleStartTime) !== getScheduleDate(arr[index - 1].scheduleStartTime)) {
          return { ...item, showTimestamp: true };
        }
        return { ...item, showTimestamp: false };
      })
    );
    function getScheduleDate(timestamp) {
      const date = new Date(timestamp * 1e3);
      const year = `${date.getFullYear()}`;
      const month = `${date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1}`;
      const day = `${date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()}`;
      return `${year}${t("schedule year")}${month}${t("schedule month")}${day}${t("schedule day")}`;
    }
    function getScheduleTime(timestamp) {
      const date = new Date(timestamp * 1e3);
      const hours = `${date.getHours() < 10 ? `0${date.getHours()}` : date.getHours()}`;
      const minutes = `${date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes()}`;
      return `${hours}:${minutes}`;
    }
    const fetchAttendeeList = async (roomId, cursor = "", result = []) => {
      const res = await roomService.scheduleConferenceManager.fetchAttendeeList({
        roomId,
        cursor,
        count: 20
      });
      if (!(res == null ? void 0 : res.attendeeList)) return [];
      result.push(...(res == null ? void 0 : res.attendeeList) || []);
      if (res.cursor !== "") {
        await fetchAttendeeList(roomId, res.cursor, result);
      }
      return result;
    };
    const handleShowMore = async (data) => {
      const attendeeList = await fetchAttendeeList(data.roomId);
      const scheduleRoom = scheduleRoomList.value.find(
        (item) => item.basicRoomInfo.roomId === data.roomId
      );
      if (scheduleRoom) {
        scheduleRoom.scheduleAttendees = attendeeList;
      }
    };
    const fetchData = async () => {
      scheduleRoomList.value = await fetchScheduledData();
      isShowLoading.value = false;
    };
    const updateAttendees = (originList = [], changeData) => {
      const { joinedUsers, leftUsers } = changeData;
      let resultList = [...originList, ...joinedUsers];
      resultList = resultList.filter(
        (attendee) => !leftUsers.some((leftUser) => leftUser.userId === attendee.userId)
      );
      return resultList;
    };
    const onConferenceScheduled = async (data) => {
      const { conferenceInfo } = data;
      const index = scheduleRoomList.value.findIndex(
        (item) => item.basicRoomInfo.roomId === conferenceInfo.basicRoomInfo.roomId
      );
      if (index >= 0) {
        scheduleRoomList.value.splice(index, 1, conferenceInfo);
      } else {
        scheduleRoomList.value.push(conferenceInfo);
      }
    };
    const onConferenceCancelled = async (data) => {
      scheduleRoomList.value = scheduleRoomList.value.filter(
        (item) => item.basicRoomInfo.roomId !== data.roomId
      );
    };
    const onConferenceInfoChanged = async (data) => {
      const aimConferenceIndex = scheduleRoomList.value.findIndex(
        (item) => item.basicRoomInfo.roomId === data.conferenceModifyInfo.basicRoomInfo.roomId
      );
      if (aimConferenceIndex !== -1) {
        scheduleRoomList.value[aimConferenceIndex] = objectMerge(
          scheduleRoomList.value[aimConferenceIndex],
          data.conferenceModifyInfo
        );
      }
    };
    const onScheduleAttendeesChanged = async (data) => {
      const aimConference = scheduleRoomList.value.find(
        (item) => item.basicRoomInfo.roomId === data.roomId
      );
      if (aimConference) {
        aimConference.scheduleAttendees = updateAttendees(
          aimConference.scheduleAttendees,
          data
        );
      }
    };
    const onConferenceStatusChanged = (data) => {
      const aimConference = scheduleRoomList.value.find(
        (item) => item.basicRoomInfo.roomId === data.roomId
      );
      if (aimConference) {
        aimConference.status = data.status;
      }
    };
    onMounted(() => {
      roomService.on(EventType.ROOM_LOGIN, fetchData);
      roomService.scheduleConferenceManager.on(
        TUIConferenceListManagerEvents.onConferenceScheduled,
        onConferenceScheduled
      );
      roomService.scheduleConferenceManager.on(
        TUIConferenceListManagerEvents.onConferenceCancelled,
        onConferenceCancelled
      );
      roomService.scheduleConferenceManager.on(
        TUIConferenceListManagerEvents.onConferenceInfoChanged,
        onConferenceInfoChanged
      );
      roomService.scheduleConferenceManager.on(
        TUIConferenceListManagerEvents.onScheduleAttendeesChanged,
        onScheduleAttendeesChanged
      );
      roomService.scheduleConferenceManager.on(
        TUIConferenceListManagerEvents.onConferenceStatusChanged,
        onConferenceStatusChanged
      );
    });
    onUnmounted(() => {
      roomService.off(EventType.ROOM_LOGIN, fetchData);
      roomService.scheduleConferenceManager.off(
        TUIConferenceListManagerEvents.onConferenceScheduled,
        onConferenceScheduled
      );
      roomService.scheduleConferenceManager.off(
        TUIConferenceListManagerEvents.onConferenceCancelled,
        onConferenceCancelled
      );
      roomService.scheduleConferenceManager.off(
        TUIConferenceListManagerEvents.onConferenceInfoChanged,
        onConferenceInfoChanged
      );
      roomService.scheduleConferenceManager.off(
        TUIConferenceListManagerEvents.onScheduleAttendeesChanged,
        onScheduleAttendeesChanged
      );
      roomService.scheduleConferenceManager.off(
        TUIConferenceListManagerEvents.onConferenceStatusChanged,
        onConferenceStatusChanged
      );
    });
    return (_ctx, _cache) => {
      return withDirectives((openBlock(), createElementBlock("div", {
        id: "scheduleRoomContainer",
        class: normalizeClass([
          "schedule-room",
          !unref(isMobile) ? "schedule-room-pc" : "schedule-room-h5"
        ])
      }, [
        isShowLoading.value ? (openBlock(), createElementBlock("div", _hoisted_1, [
          createVNode(SvgIcon, {
            icon: LoadingScheduleIcon,
            class: "loading"
          }),
          createElementVNode("span", _hoisted_2, toDisplayString(unref(t)("Schedule room loading")), 1)
        ])) : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
          scheduleRoomList.value.length > 0 ? (openBlock(), createElementBlock("div", _hoisted_3, [
            (openBlock(true), createElementBlock(Fragment, null, renderList(scheduleContentList.value, (item) => {
              return openBlock(), createElementBlock("div", {
                key: item.basicRoomInfo.roomId
              }, [
                item.showTimestamp ? (openBlock(), createElementBlock("div", _hoisted_4, [
                  createVNode(SvgIcon, {
                    class: "date",
                    icon: CalendarIcon
                  }),
                  createElementVNode("span", null, toDisplayString(getScheduleDate(item.scheduleStartTime)), 1)
                ])) : createCommentVNode("", true),
                createVNode(ScheduleRoomControl, {
                  item,
                  "schedule-start-date": getScheduleDate(item.scheduleStartTime),
                  "schedule-end-date": getScheduleDate(item.scheduleEndTime),
                  "schedule-start-time": getScheduleTime(item.scheduleStartTime),
                  "schedule-end-time": getScheduleTime(item.scheduleEndTime),
                  onJoinConference: joinConference,
                  onShowMore: handleShowMore
                }, null, 8, ["item", "schedule-start-date", "schedule-end-date", "schedule-start-time", "schedule-end-time"])
              ]);
            }), 128))
          ])) : (openBlock(), createElementBlock("div", _hoisted_5, [
            createVNode(SvgIcon, { icon: ApplyStageLabelIcon }),
            createElementVNode("span", _hoisted_6, toDisplayString(unref(t)("No room available for booking")), 1)
          ]))
        ], 64))
      ], 2)), [
        [vShow, props.isShowScheduledConference]
      ]);
    };
  }
});
export {
  _sfc_main as default
};
