"use strict";
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
const Vue = require("vue");
const pinia = require("pinia");
const room = require("../../../stores/room.js");
const basic = require("../../../stores/basic.js");
const StreamRegionPC = require("../StreamRegion/StreamRegionPC.vue.js");
const index = require("../StreamList/index.vue.js");
const index$1 = require("../../../utils/common/logger/index.js");
const Swiper = require("../../common/base/Swiper.vue.js");
const SwiperItem = require("../../common/base/SwiperItem.vue.js");
const TUIRoomEngine = require("@tencentcloud/tuiroom-engine-js");
const useRoomEngine = require("../../../hooks/useRoomEngine.js");
const useStreamContainerHooks = require("./useStreamContainerHooks.js");
const _hoisted_1 = { class: "page-stream-container" };
const logPrefix = "[StreamContainer]";
const _sfc_main = /* @__PURE__ */ Vue.defineComponent({
  __name: "StreamContainerH5",
  props: {
    showRoomTool: { type: Boolean }
  },
  setup(__props) {
    const {
      currentRemoteSpeakerUserId,
      currentSpeakerUserId,
      onUserVoiceVolumeChanged,
      isSameStream,
      getStreamKey
    } = useStreamContainerHooks.default();
    const roomEngine = useRoomEngine.default();
    const streamContainerRef = Vue.ref();
    const roomStore = room.useRoomStore();
    const {
      streamList,
      localStream,
      masterUserId,
      streamInfoObj,
      remoteStreamList
    } = pinia.storeToRefs(roomStore);
    const basicStore = basic.useBasicStore();
    const screenStream = Vue.ref(null);
    const fixedStream = Vue.ref(null);
    const enlargeStream = Vue.computed(() => {
      if (fixedStream.value) {
        return fixedStream.value;
      }
      if (screenStream.value) {
        return screenStream.value;
      }
      if (currentRemoteSpeakerUserId.value) {
        return streamInfoObj.value[`${currentRemoteSpeakerUserId.value}_${TUIRoomEngine.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}_${TUIRoomEngine.TUIVideoStreamType.kCameraStream}`]) {
          return remoteStreamList.value[0];
        }
        return streamInfoObj.value[`${masterUserId.value}_${TUIRoomEngine.TUIVideoStreamType.kCameraStream}`];
      }
      return localStream.value;
    });
    const horizontalCount = Vue.ref(1);
    const verticalCount = Vue.ref(1);
    const currentPageIndex = Vue.ref(0);
    function handleActiveIndexChange(index2) {
      currentPageIndex.value = index2;
    }
    const cameraStreamList = Vue.computed(
      () => streamList.value.filter(
        (stream) => stream.streamType === TUIRoomEngine.TUIVideoStreamType.kCameraStream
      )
    );
    Vue.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;
        }
      }
    );
    Vue.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}_${TUIRoomEngine.TUIVideoStreamType.kCameraStream}`;
          if (!val.includes(currentRemoteSpeakerUserKey) && oldVal.includes(currentRemoteSpeakerUserKey)) {
            currentRemoteSpeakerUserId.value = "";
          }
        }
      }
    );
    const topRightStyle = Vue.ref({ width: "0", height: "0 " });
    const topRightStream = Vue.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}_${TUIRoomEngine.TUIVideoStreamType.kCameraStream}`];
        }
        return localStream.value;
      }
      if (isSameStream(enlargeStream.value, localStream.value)) {
        if (currentRemoteSpeakerUserId.value) {
          return streamInfoObj.value[`${currentRemoteSpeakerUserId.value}_${TUIRoomEngine.TUIVideoStreamType.kCameraStream}`];
        }
        return remoteStreamList.value[0];
      }
      return localStream.value;
    });
    Vue.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 = Vue.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 = Vue.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 = Vue.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 === TUIRoomEngine.TUIVideoStreamType.kScreenStream) {
        if (hasVideo) {
          screenStream.value = roomStore.streamInfoObj[`${userId}_${streamType}`];
          fixedStream.value = null;
          currentPageIndex.value = 0;
        } else {
          index$1.default.debug(
            `${logPrefix} onUserVideoStateChanged: stop`,
            userId,
            streamType
          );
          (_a = roomEngine.instance) == null ? void 0 : _a.stopPlayRemoteVideo({
            userId,
            streamType
          });
          screenStream.value = null;
        }
      }
    };
    TUIRoomEngine.once("ready", () => {
      var _a, _b;
      (_a = roomEngine.instance) == null ? void 0 : _a.on(
        TUIRoomEngine.TUIRoomEvents.onUserVideoStateChanged,
        onUserVideoStateChanged
      );
      (_b = roomEngine.instance) == null ? void 0 : _b.on(
        TUIRoomEngine.TUIRoomEvents.onUserVoiceVolumeChanged,
        onUserVoiceVolumeChanged
      );
    });
    Vue.onUnmounted(() => {
      var _a, _b;
      (_a = roomEngine.instance) == null ? void 0 : _a.off(
        TUIRoomEngine.TUIRoomEvents.onUserVideoStateChanged,
        onUserVideoStateChanged
      );
      (_b = roomEngine.instance) == null ? void 0 : _b.off(
        TUIRoomEngine.TUIRoomEvents.onUserVoiceVolumeChanged,
        onUserVoiceVolumeChanged
      );
    });
    return (_ctx, _cache) => {
      return Vue.openBlock(), Vue.createElementBlock("div", {
        ref_key: "streamContainerRef",
        ref: streamContainerRef,
        class: "stream-container"
      }, [
        Vue.createVNode(Swiper.default, {
          activeIndex: currentPageIndex.value,
          onChange: handleActiveIndexChange
        }, {
          default: Vue.withCtx(() => [
            Vue.createVNode(SwiperItem.default, null, {
              default: Vue.withCtx(() => [
                Vue.createElementVNode("div", _hoisted_1, [
                  Vue.createVNode(Vue.unref(StreamRegionPC.default), {
                    class: "enlarge-stream",
                    streamInfo: enlargeStream.value,
                    isEnlarge: true,
                    isNeedPlayStream: showPageIndexList.value.includes(0)
                  }, null, 8, ["streamInfo", "isNeedPlayStream"]),
                  topRightStream.value ? (Vue.openBlock(), Vue.createBlock(Vue.unref(StreamRegionPC.default), {
                    key: 0,
                    class: Vue.normalizeClass(["top-right-stream", _ctx.showRoomTool ? "show-room-tool" : ""]),
                    streamInfo: topRightStream.value,
                    isNeedPlayStream: showPageIndexList.value.includes(0),
                    style: Vue.normalizeStyle(topRightStyle.value)
                  }, null, 8, ["class", "streamInfo", "isNeedPlayStream", "style"])) : Vue.createCommentVNode("", true)
                ])
              ]),
              _: 1
            }),
            (Vue.openBlock(true), Vue.createElementBlock(Vue.Fragment, null, Vue.renderList(showStreamList.value, (streamList2, index$12) => {
              return Vue.openBlock(), Vue.createBlock(SwiperItem.default, { key: index$12 }, {
                default: Vue.withCtx(() => [
                  Vue.createVNode(index.default, {
                    class: "page-stream-container",
                    onRoomDblclick: handleEnlargeStreamRegion,
                    aspectRatio: "1:1",
                    horizontalCount: horizontalCount.value,
                    verticalCount: verticalCount.value,
                    isNeedPlayStream: showPageIndexList.value.includes(index$12 + 1),
                    streamInfoList: streamList2
                  }, null, 8, ["horizontalCount", "verticalCount", "isNeedPlayStream", "streamInfoList"])
                ]),
                _: 2
              }, 1024);
            }), 128))
          ]),
          _: 1
        }, 8, ["activeIndex"])
      ], 512);
    };
  }
});
exports.default = _sfc_main;
