import { defineComponent, ref, computed, watch, onMounted, onUnmounted, openBlock, createElementBlock, createVNode, withCtx, createElementVNode, unref, createBlock, normalizeClass, normalizeStyle, createCommentVNode, Fragment, renderList } from "vue";
import { storeToRefs } from "pinia";
import { useRoomStore } from "../../../stores/room.mjs";
import { useBasicStore } from "../../../stores/basic.mjs";
import StreamRegion from "../StreamRegion/StreamRegionPC.vue.mjs";
import StreamList from "../StreamList/index.vue.mjs";
import logger from "../../../utils/common/logger/index.mjs";
import TuiSwiper from "../../common/base/Swiper.vue.mjs";
import TuiSwiperItem from "../../common/base/SwiperItem.vue.mjs";
import TUIRoomEngine__default, { TUIVideoStreamType, TUIRoomEvents } from "@tencentcloud/tuiroom-engine-js";
import useGetRoomEngine from "../../../hooks/useRoomEngine.mjs";
import useStreamContainer from "./useStreamContainerHooks.mjs";
const _hoisted_1 = { class: "page-stream-container" };
const logPrefix = "[StreamContainer]";
const _sfc_main = /* @__PURE__ */ defineComponent({
  __name: "StreamContainerH5",
  props: {
    showRoomTool: { type: Boolean }
  },
  setup(__props) {
    const {
      currentRemoteSpeakerUserId,
      currentSpeakerUserId,
      onUserVoiceVolumeChanged,
      isSameStream,
      getStreamKey
    } = useStreamContainer();
    const roomEngine = useGetRoomEngine();
    const streamContainerRef = ref();
    const roomStore = useRoomStore();
    const {
      streamList,
      localStream,
      masterUserId,
      streamInfoObj,
      remoteStreamList
    } = storeToRefs(roomStore);
    const basicStore = useBasicStore();
    const screenStream = ref(null);
    const fixedStream = ref(null);
    const enlargeStream = computed(() => {
      if (fixedStream.value) {
        return fixedStream.value;
      }
      if (screenStream.value) {
        return screenStream.value;
      }
      if (currentRemoteSpeakerUserId.value) {
        return streamInfoObj.value[`${currentRemoteSpeakerUserId.value}_${TUIVideoStreamType.kCameraStream}`];
      }
      if (remoteStreamList.value.length === 1) {
        return remoteStreamList.value[0];
      }
      if (remoteStreamList.value.length > 1) {
        if (!masterUserId.value || masterUserId.value === localStream.value.userId || !streamInfoObj.value[`${masterUserId.value}_${TUIVideoStreamType.kCameraStream}`]) {
          return remoteStreamList.value[0];
        }
        return streamInfoObj.value[`${masterUserId.value}_${TUIVideoStreamType.kCameraStream}`];
      }
      return localStream.value;
    });
    const horizontalCount = ref(1);
    const verticalCount = ref(1);
    const currentPageIndex = ref(0);
    function handleActiveIndexChange(index) {
      currentPageIndex.value = index;
    }
    const cameraStreamList = computed(
      () => streamList.value.filter(
        (stream) => stream.streamType === TUIVideoStreamType.kCameraStream
      )
    );
    watch(
      () => cameraStreamList.value.length,
      (val) => {
        horizontalCount.value = Math.min(Math.ceil(Math.sqrt(val)), 2);
        verticalCount.value = Math.min(Math.ceil(val / horizontalCount.value), 3);
        const equalPointIndex = enlargeStream.value ? currentPageIndex.value - 1 : currentPageIndex.value;
        if (Math.ceil(val / 6) < equalPointIndex + 1 && equalPointIndex > 0) {
          currentPageIndex.value = currentPageIndex.value - 1;
        }
      }
    );
    watch(
      () => streamList.value.map((stream) => getStreamKey(stream)),
      (val, oldVal) => {
        if (fixedStream.value) {
          const fixedStreamKey = getStreamKey(fixedStream.value);
          if (!val.includes(fixedStreamKey) && oldVal.includes(fixedStreamKey)) {
            fixedStream.value = null;
          }
        }
        if (screenStream.value) {
          const screenStreamKey = getStreamKey(screenStream.value);
          if (!val.includes(screenStreamKey) && oldVal.includes(screenStreamKey)) {
            screenStream.value = null;
          }
        }
        if (currentRemoteSpeakerUserId.value) {
          const currentRemoteSpeakerUserKey = `${currentRemoteSpeakerUserId.value}_${TUIVideoStreamType.kCameraStream}`;
          if (!val.includes(currentRemoteSpeakerUserKey) && oldVal.includes(currentRemoteSpeakerUserKey)) {
            currentRemoteSpeakerUserId.value = "";
          }
        }
      }
    );
    const topRightStyle = ref({ width: "0", height: "0 " });
    const topRightStream = computed(() => {
      if (fixedStream.value && screenStream.value && !isSameStream(fixedStream.value, screenStream.value)) {
        return screenStream.value;
      }
      if (isSameStream(enlargeStream.value, screenStream.value)) {
        if (currentSpeakerUserId.value && currentSpeakerUserId.value !== basicStore.userId) {
          return streamInfoObj.value[`${currentSpeakerUserId.value}_${TUIVideoStreamType.kCameraStream}`];
        }
        return localStream.value;
      }
      if (isSameStream(enlargeStream.value, localStream.value)) {
        if (currentRemoteSpeakerUserId.value) {
          return streamInfoObj.value[`${currentRemoteSpeakerUserId.value}_${TUIVideoStreamType.kCameraStream}`];
        }
        return remoteStreamList.value[0];
      }
      return localStream.value;
    });
    onMounted(() => {
      var _a;
      const containerWidth = ((_a = streamContainerRef.value) == null ? void 0 : _a.offsetWidth) / 2;
      topRightStyle.value.width = `${containerWidth}px`;
      topRightStyle.value.height = `${containerWidth}px`;
    });
    const showPageIndexList = computed(() => {
      const showPageIndexList2 = [currentPageIndex.value];
      if (currentPageIndex.value - 1 >= 0) {
        showPageIndexList2.unshift(currentPageIndex.value - 1);
      }
      if (currentPageIndex.value + 1 <= totalPageNumber.value) {
        showPageIndexList2.push(currentPageIndex.value + 1);
      }
      return showPageIndexList2;
    });
    const showStreamList = computed(() => {
      if (streamList.value.length <= 1) {
        return [];
      }
      return [...new Array(totalPageNumber.value - 1).keys()].map(
        (pageIndex) => {
          return cameraStreamList.value.slice(pageIndex * 6, pageIndex * 6 + 6);
        }
      );
    });
    const totalPageNumber = computed(() => {
      const videoStreamNumber = cameraStreamList.value.length;
      const totalPageOfVideoStream = videoStreamNumber > 6 ? Math.ceil(videoStreamNumber / 6) : 1;
      return totalPageOfVideoStream + 1;
    });
    function handleEnlargeStreamRegion(stream) {
      if (!(stream == null ? void 0 : stream.hasVideoStream)) {
        return;
      }
      currentPageIndex.value = 0;
      fixedStream.value = stream;
    }
    const onUserVideoStateChanged = (eventInfo) => {
      var _a;
      const { userId, streamType, hasVideo } = eventInfo;
      if (streamType === TUIVideoStreamType.kScreenStream) {
        if (hasVideo) {
          screenStream.value = roomStore.streamInfoObj[`${userId}_${streamType}`];
          fixedStream.value = null;
          currentPageIndex.value = 0;
        } else {
          logger.debug(
            `${logPrefix} onUserVideoStateChanged: stop`,
            userId,
            streamType
          );
          (_a = roomEngine.instance) == null ? void 0 : _a.stopPlayRemoteVideo({
            userId,
            streamType
          });
          screenStream.value = null;
        }
      }
    };
    TUIRoomEngine__default.once("ready", () => {
      var _a, _b;
      (_a = roomEngine.instance) == null ? void 0 : _a.on(
        TUIRoomEvents.onUserVideoStateChanged,
        onUserVideoStateChanged
      );
      (_b = roomEngine.instance) == null ? void 0 : _b.on(
        TUIRoomEvents.onUserVoiceVolumeChanged,
        onUserVoiceVolumeChanged
      );
    });
    onUnmounted(() => {
      var _a, _b;
      (_a = roomEngine.instance) == null ? void 0 : _a.off(
        TUIRoomEvents.onUserVideoStateChanged,
        onUserVideoStateChanged
      );
      (_b = roomEngine.instance) == null ? void 0 : _b.off(
        TUIRoomEvents.onUserVoiceVolumeChanged,
        onUserVoiceVolumeChanged
      );
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        ref_key: "streamContainerRef",
        ref: streamContainerRef,
        class: "stream-container"
      }, [
        createVNode(TuiSwiper, {
          activeIndex: currentPageIndex.value,
          onChange: handleActiveIndexChange
        }, {
          default: withCtx(() => [
            createVNode(TuiSwiperItem, null, {
              default: withCtx(() => [
                createElementVNode("div", _hoisted_1, [
                  createVNode(unref(StreamRegion), {
                    class: "enlarge-stream",
                    streamInfo: enlargeStream.value,
                    isEnlarge: true,
                    isNeedPlayStream: showPageIndexList.value.includes(0)
                  }, null, 8, ["streamInfo", "isNeedPlayStream"]),
                  topRightStream.value ? (openBlock(), createBlock(unref(StreamRegion), {
                    key: 0,
                    class: normalizeClass(["top-right-stream", _ctx.showRoomTool ? "show-room-tool" : ""]),
                    streamInfo: topRightStream.value,
                    isNeedPlayStream: showPageIndexList.value.includes(0),
                    style: normalizeStyle(topRightStyle.value)
                  }, null, 8, ["class", "streamInfo", "isNeedPlayStream", "style"])) : createCommentVNode("", true)
                ])
              ]),
              _: 1
            }),
            (openBlock(true), createElementBlock(Fragment, null, renderList(showStreamList.value, (streamList2, index) => {
              return openBlock(), createBlock(TuiSwiperItem, { key: index }, {
                default: withCtx(() => [
                  createVNode(StreamList, {
                    class: "page-stream-container",
                    onRoomDblclick: handleEnlargeStreamRegion,
                    aspectRatio: "1:1",
                    horizontalCount: horizontalCount.value,
                    verticalCount: verticalCount.value,
                    isNeedPlayStream: showPageIndexList.value.includes(index + 1),
                    streamInfoList: streamList2
                  }, null, 8, ["horizontalCount", "verticalCount", "isNeedPlayStream", "streamInfoList"])
                ]),
                _: 2
              }, 1024);
            }), 128))
          ]),
          _: 1
        }, 8, ["activeIndex"])
      ], 512);
    };
  }
});
export {
  _sfc_main as default
};
