import { defineComponent, ref, computed, watch, onUnmounted, openBlock, createElementBlock, normalizeClass, withDirectives, createElementVNode, createBlock, unref, createCommentVNode, vShow, createVNode } from "vue";
import { storeToRefs } from "pinia";
import { useRoomStore } from "../../../stores/room.mjs";
import { useBasicStore } from "../../../stores/basic.mjs";
import { LAYOUT } from "../../../constants/render.mjs";
import StreamRegion from "../StreamRegion/StreamRegionPC.vue.mjs";
import StreamList from "../StreamList/index.vue.mjs";
import logger from "../../../utils/common/logger/index.mjs";
import ArrowStrokeTurnPageIcon from "../../common/icons/ArrowStrokeTurnPageIcon.vue.mjs";
import ArrowStroke from "../../common/ArrowStroke.vue.mjs";
import SvgIcon from "../../common/base/SvgIcon.vue.mjs";
import TUIRoomEngine__default, { TUIVideoStreamType, TUIRoomEvents } from "@tencentcloud/tuiroom-engine-js";
import useGetRoomEngine from "../../../hooks/useRoomEngine.mjs";
const _hoisted_1 = {
  key: 1,
  class: "turn-page-container"
};
const logPrefix = "[StreamContainer]";
const _sfc_main = /* @__PURE__ */ defineComponent({
  __name: "StreamContainerPC",
  props: {
    showRoomTool: { type: Boolean }
  },
  setup(__props) {
    const roomEngine = useGetRoomEngine();
    const roomStore = useRoomStore();
    const { streamList, streamNumber, remoteStreamList } = storeToRefs(roomStore);
    const basicStore = useBasicStore();
    const { layout } = storeToRefs(basicStore);
    const showSideList = ref(true);
    const enlargeStream = ref(null);
    const horizontalCount = ref(1);
    const verticalCount = ref(1);
    const currentPageIndex = ref(0);
    const maxCountEveryPage = computed(
      () => horizontalCount.value * verticalCount.value
    );
    const totalPage = computed(
      () => Math.ceil(streamList.value.length / maxCountEveryPage.value)
    );
    const showTurnPageControl = computed(
      () => layout.value === LAYOUT.NINE_EQUAL_POINTS && totalPage.value > 1
    );
    const showTurnPageLeftArrow = computed(
      () => layout.value === LAYOUT.NINE_EQUAL_POINTS && currentPageIndex.value > 0
    );
    const showTurnPageRightArrow = computed(
      () => layout.value === LAYOUT.NINE_EQUAL_POINTS && currentPageIndex.value < totalPage.value - 1
    );
    function handleTurnPageLeft() {
      currentPageIndex.value = currentPageIndex.value - 1;
    }
    function handleTurnPageRight() {
      currentPageIndex.value = currentPageIndex.value + 1;
    }
    const showStreamList = computed(() => {
      var _a;
      if (layout.value === LAYOUT.NINE_EQUAL_POINTS) {
        return streamList.value.slice(
          currentPageIndex.value * maxCountEveryPage.value,
          (currentPageIndex.value + 1) * maxCountEveryPage.value
        );
      }
      if (((_a = enlargeStream.value) == null ? void 0 : _a.streamType) === TUIVideoStreamType.kScreenStream) {
        return streamList.value.filter((item) => item !== enlargeStream.value);
      }
      return streamList.value;
    });
    watch(
      () => streamList.value.length,
      (val) => {
        if (val === 1) {
          basicStore.setLayout(LAYOUT.NINE_EQUAL_POINTS);
          enlargeStream.value = null;
          return;
        }
      }
    );
    const streamContainerClass = ref("stream-container-flatten");
    const enlargedContainerRef = ref();
    const arrowDirection = computed(() => {
      let arrowDirection2 = "right";
      if (layout.value === LAYOUT.TOP_SIDE_LIST) {
        arrowDirection2 = showSideList.value ? "up" : "down";
      }
      if (layout.value === LAYOUT.RIGHT_SIDE_LIST) {
        arrowDirection2 = showSideList.value ? "right" : "left";
      }
      return arrowDirection2;
    });
    const strokePosition = computed(() => {
      let strokePosition2 = "";
      if (layout.value === LAYOUT.TOP_SIDE_LIST) {
        strokePosition2 = "bottom";
      }
      if (layout.value === LAYOUT.RIGHT_SIDE_LIST) {
        strokePosition2 = "left";
      }
      return strokePosition2;
    });
    function handleClickIcon() {
      showSideList.value = !showSideList.value;
    }
    function getEnlargeStream() {
      var _a;
      if ((_a = roomStore.localScreenStream) == null ? void 0 : _a.hasVideoStream) {
        return roomStore.localScreenStream;
      }
      if (remoteStreamList.value.length > 0) {
        const remoteScreenStream = remoteStreamList.value.find(
          (stream) => stream.streamType === TUIVideoStreamType.kScreenStream && stream.hasVideoStream
        );
        return remoteScreenStream ? remoteScreenStream : remoteStreamList.value[0];
      }
      return roomStore.localStream;
    }
    async function handleNineEqualPointsLayout() {
      streamContainerClass.value = "stream-container-flatten";
      enlargeStream.value = null;
      horizontalCount.value = Math.min(
        Math.ceil(Math.sqrt(streamList.value.length)),
        3
      );
      verticalCount.value = Math.min(
        Math.ceil(streamList.value.length / horizontalCount.value),
        3
      );
      currentPageIndex.value = 0;
    }
    async function handleRightSideListLayout() {
      streamContainerClass.value = "stream-container-right";
      horizontalCount.value = 1;
      verticalCount.value = Infinity;
      if (!enlargeStream.value) {
        enlargeStream.value = getEnlargeStream();
      }
    }
    async function handleTopSideListLayout() {
      streamContainerClass.value = "stream-container-top";
      horizontalCount.value = Infinity;
      verticalCount.value = 1;
      if (!enlargeStream.value) {
        enlargeStream.value = getEnlargeStream();
      }
    }
    function handleEnlargeStreamRegion(stream) {
      if (layout.value === LAYOUT.NINE_EQUAL_POINTS && streamList.value.length > 1) {
        basicStore.setLayout(LAYOUT.RIGHT_SIDE_LIST);
      }
      enlargeStream.value = stream;
    }
    async function handleLayout() {
      switch (layout.value) {
        case LAYOUT.NINE_EQUAL_POINTS:
          handleNineEqualPointsLayout();
          break;
        case LAYOUT.RIGHT_SIDE_LIST:
          handleRightSideListLayout();
          break;
        case LAYOUT.TOP_SIDE_LIST:
          handleTopSideListLayout();
          break;
      }
    }
    watch(streamNumber, (val) => {
      if (layout.value === LAYOUT.NINE_EQUAL_POINTS) {
        horizontalCount.value = Math.min(Math.ceil(Math.sqrt(val)), 3);
        verticalCount.value = Math.min(Math.ceil(val / horizontalCount.value), 3);
        if (currentPageIndex.value > Math.ceil(val / maxCountEveryPage.value) - 1) {
          currentPageIndex.value = Math.ceil(val / maxCountEveryPage.value) - 1;
        }
      }
    });
    watch(
      layout,
      () => {
        handleLayout();
      },
      { immediate: true }
    );
    const showIconControl = computed(
      () => [LAYOUT.RIGHT_SIDE_LIST, LAYOUT.TOP_SIDE_LIST].indexOf(layout.value) >= 0
    );
    const onUserVideoStateChanged = (eventInfo) => {
      var _a, _b;
      const { userId, streamType, hasVideo } = eventInfo;
      if (streamType === TUIVideoStreamType.kScreenStream) {
        if (hasVideo) {
          enlargeStream.value = userId === basicStore.userId ? roomStore.localScreenStream : roomStore.streamInfoObj[`${userId}_${streamType}`];
          if (enlargeStream.value && [LAYOUT.RIGHT_SIDE_LIST, LAYOUT.TOP_SIDE_LIST].indexOf(layout.value) === -1) {
            basicStore.setLayout(LAYOUT.RIGHT_SIDE_LIST);
          }
          if (userId !== basicStore.userId) {
            roomStore.setHasOtherScreenShare(true);
          }
        } else {
          if (userId === ((_a = enlargeStream.value) == null ? void 0 : _a.userId)) {
            handleLargeStreamLeave();
          }
          if (userId !== basicStore.userId) {
            roomStore.setHasOtherScreenShare(false);
          }
          logger.debug(
            `${logPrefix} onUserVideoStateChanged: stop`,
            userId,
            streamType
          );
          (_b = roomEngine.instance) == null ? void 0 : _b.stopPlayRemoteVideo({
            userId,
            streamType
          });
        }
      }
    };
    const onSeatListChanged = (eventInfo) => {
      var _a;
      const { leftList } = eventInfo;
      const leftUserIdList = leftList.map((item) => item.userId);
      if (enlargeStream.value && leftUserIdList.includes((_a = enlargeStream.value) == null ? void 0 : _a.userId)) {
        handleLargeStreamLeave();
      }
    };
    const onRemoteUserLeaveRoom = (eventInfo) => {
      var _a;
      const {
        userInfo: { userId }
      } = eventInfo;
      if (userId === ((_a = enlargeStream.value) == null ? void 0 : _a.userId)) {
        handleLargeStreamLeave();
      }
    };
    const handleLargeStreamLeave = () => {
      if (roomStore.remoteStreamList.length === 0) {
        basicStore.setLayout(LAYOUT.NINE_EQUAL_POINTS);
        enlargeStream.value = null;
      } else {
        [enlargeStream.value] = roomStore.remoteStreamList;
      }
    };
    TUIRoomEngine__default.once("ready", () => {
      var _a, _b, _c;
      (_a = roomEngine.instance) == null ? void 0 : _a.on(
        TUIRoomEvents.onRemoteUserLeaveRoom,
        onRemoteUserLeaveRoom
      );
      (_b = roomEngine.instance) == null ? void 0 : _b.on(TUIRoomEvents.onSeatListChanged, onSeatListChanged);
      (_c = roomEngine.instance) == null ? void 0 : _c.on(
        TUIRoomEvents.onUserVideoStateChanged,
        onUserVideoStateChanged
      );
    });
    onUnmounted(() => {
      var _a, _b, _c;
      (_a = roomEngine.instance) == null ? void 0 : _a.off(
        TUIRoomEvents.onRemoteUserLeaveRoom,
        onRemoteUserLeaveRoom
      );
      (_b = roomEngine.instance) == null ? void 0 : _b.off(TUIRoomEvents.onSeatListChanged, onSeatListChanged);
      (_c = roomEngine.instance) == null ? void 0 : _c.off(
        TUIRoomEvents.onUserVideoStateChanged,
        onUserVideoStateChanged
      );
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        id: "streamContainer",
        class: normalizeClass(streamContainerClass.value)
      }, [
        withDirectives(createElementVNode("div", {
          ref_key: "enlargedContainerRef",
          ref: enlargedContainerRef,
          class: "enlarged-stream-container"
        }, [
          enlargeStream.value ? (openBlock(), createBlock(unref(StreamRegion), {
            key: 0,
            streamInfo: enlargeStream.value,
            aspectRatio: "16:9",
            isEnlarge: true,
            observerViewInVisible: true
          }, null, 8, ["streamInfo"])) : createCommentVNode("", true)
        ], 512), [
          [vShow, enlargeStream.value]
        ]),
        createVNode(StreamList, {
          class: normalizeClass(["stream-list-container", `${showSideList.value ? "" : "hide-list"}`]),
          streamInfoList: showStreamList.value,
          horizontalCount: horizontalCount.value,
          verticalCount: verticalCount.value,
          aspectRatio: "16:9",
          observerViewInVisible: true,
          onRoomDblclick: handleEnlargeStreamRegion
        }, null, 8, ["class", "streamInfoList", "horizontalCount", "verticalCount"]),
        showIconControl.value && (_ctx.showRoomTool || showSideList.value) ? (openBlock(), createBlock(ArrowStroke, {
          key: 0,
          class: normalizeClass([`arrow-stroke-${arrowDirection.value}`]),
          "stroke-position": strokePosition.value,
          "arrow-direction": arrowDirection.value,
          "has-stroke": showSideList.value,
          onClickArrow: handleClickIcon
        }, null, 8, ["class", "stroke-position", "arrow-direction", "has-stroke"])) : createCommentVNode("", true),
        showTurnPageControl.value && _ctx.showRoomTool ? (openBlock(), createElementBlock("div", _hoisted_1, [
          withDirectives(createElementVNode("div", {
            class: "turn-page-arrow-container left-container",
            onClick: handleTurnPageLeft
          }, [
            createVNode(SvgIcon, { icon: ArrowStrokeTurnPageIcon })
          ], 512), [
            [vShow, showTurnPageLeftArrow.value]
          ]),
          withDirectives(createElementVNode("div", {
            class: "turn-page-arrow-container right-container",
            onClick: handleTurnPageRight
          }, [
            createVNode(SvgIcon, {
              class: "turn-page-right",
              icon: ArrowStrokeTurnPageIcon
            })
          ], 512), [
            [vShow, showTurnPageRightArrow.value]
          ])
        ])) : createCommentVNode("", true)
      ], 2);
    };
  }
});
export {
  _sfc_main as default
};
