<template>
  <div ref="content" class="flex-1">
    <van-swipe indicator-color="white" :loop="false">
      <van-swipe-item v-for="tracks in tracksGroup" :key="getTrackReferenceId(tracks[0]) + 1">
        <GroupTrackItem v-for="track in tracks" :size="size" :key="getTrackReferenceId(track)" :track="track"
          :isVideo="isVideo" />
        <!-- <template v-for="member in invitedList">
          <div v-if="!connectedMemberIDs.includes(member.userID)" :style="{ width: size + 'px', height: size + 'px' }"
            class="relative">
            <Avatar :size="size" :src="member.faceURL" :desc="member.nickname" />
            <div :style="{ width: size + 'px', height: size + 'px' }"
              class="absolute top-0 left-0 flex justify-center items-center bg-sub-text bg-opacity-80 z-10 rounded-md overflow-hidden">
              <div class="w-1.5 h-1.5 rounded-full bg-white"></div>
              <div class="w-1.5 h-1.5 rounded-full bg-white mx-1.5"></div>
              <div class="w-1.5 h-1.5 rounded-full bg-white"></div>
            </div>
          </div>
        </template> -->
      </van-swipe-item>
    </van-swipe>
  </div>
</template>

<script lang="ts" setup>
import useUserStore from '@/store/modules/user'
import { IMSDK } from '@/utils/imCommon'
import { Room, Track } from 'livekit-client'
import { useTracks } from '@/utils/open-im-rtc'
import type { GroupMemberItem } from 'open-im-sdk-wasm/lib/types/entity'
import useInviteData from '../useInviteData'
import { InviteData } from '../data'
import GroupTrackItem from './GroupTrackItem.vue'
import { getTrackReferenceId } from '@livekit/components-core'
import emitter from '@/utils/events'

type GroupTrackProps = {
  room: Room
  inviteData: InviteData
}
const props = defineProps<GroupTrackProps>()

const content = ref<HTMLElement>()
const invitedList = ref<GroupMemberItem[]>([])
const connectedMemberIDs = ref<string[]>([])

const userStore = useUserStore()
const { groupID, isVideo, inviteeUserIDList } = useInviteData(props.inviteData)
const tracksType = computed(() =>
  isVideo.value ? Track.Source.Camera : Track.Source.Microphone,
)
const tracks = useTracks({ room: props.room }, [
  { source: tracksType.value, withPlaceholder: true },
])

const tracksGroup = computed(() => {
  tracks.value.sort((a) =>
    a.participant.identity === userStore.selfInfo.userID ? -1 : 1,
  )
  const groups = []
  for (var i = 0; i < tracks.value.length; i += 9) {
    groups.push(tracks.value.slice(i, i + 9))
  }
  return groups
})

const size = computed(() => {
  let size = content.value?.clientWidth || 0

  if (invitedList.value.length > 4) {
    size /= 3
  } else {
    size /= 2
  }

  return size
})

watch(
  () => inviteeUserIDList.value,
  () => {
    IMSDK.getSpecifiedGroupMembersInfo({
      groupID: groupID.value,
      userIDList: [...inviteeUserIDList.value],
    })
      .then(
        ({ data }) =>
        (invitedList.value = data.sort((a) =>
          a.userID === userStore.selfInfo.userID ? -1 : 1,
        )),
      )
      .catch(() => (invitedList.value = []))
  },
  {
    immediate: true,
  },
)

watch(
  () => tracks.value.length,
  () => {
    const newConnectedMemberIDs = tracks.value
      .map((track) => track.participant.identity)
      .filter((id) => id !== '')
    connectedMemberIDs.value = [
      ...new Set([...connectedMemberIDs.value, ...newConnectedMemberIDs]),
    ]
  },
  {
    immediate: true,
  },
)

watch(
  () => tracks.value.length,
  () => {
    if (tracks.value.length === 1) {
      props.room.disconnect()
      emitter.emit('CLOSE_RTC_MODAL')
    }
  },
)
</script>

<style lang="scss" scoped>
:deep(.van-swipe) {
  overflow: initial;
}

:deep(.van-swipe-item) {
  display: flex;
  flex-wrap: wrap;
}

:deep(.van-swipe__indicators) {
  bottom: -40px;
  // left: 25%;
}
</style>
