<template>
  <div :class="[ns.b()]"><slot /></div>
</template>

<script lang="ts" setup>
import { computed, inject, ref, unref, watch, watchEffect } from 'vue'
import { useNamespace } from '@kankan-components/hooks'
import { daikanProps } from './daikan'

const __sdk: any = inject('__sdk')
const props = defineProps(daikanProps)
const ns = useNamespace('daikan')
defineOptions({
  name: 'KkDaikan',
})
const isLeader = computed(() => {
  return unref(props.userInfo).role === 'leader'
})

const isSDKLoad = computed(() => {
  return __sdk && __sdk.Scene && __sdk.Scene.ready
})
const isSocketLoad = ref(false)
const emits = defineEmits(['join', 'sync', 'receiveSync', 'error'])
const loadSocket = (libSdk: string) => {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script')
    script.src = libSdk
    script.addEventListener('load', resolve)
    script.addEventListener('error', reject)
    document.body.append(script)
  })
}

const handleSocketSetup = async (): Promise<void> => {
  const socket = (window as any).io(props.socketUrl, {
    path: '/ws-sync',
    transports: ['websocket'],
  })

  if (socket) {
    // console.error(`isSDKLoad-socket`)
    socket.on('connect', () => {
      socket.emit('join', {
        ...unref(props.userInfo),
      })
      socket.on('action', (data: any) => {
        if (data.type === 'user-join') {
          emits('join')
        }
        if (data.type === 'error') {
          emits('error', {
            ...data,
          })
        }
      })
      // console.error(`isLeader:${unref(isLeader)}`)
      if (unref(isLeader)) {
        // 带看主动发送同屏数据到socket room
        __sdk.Connect.follow.on('data', (data: any) => {
          socket.emit('sync', data)
          emits('sync', data)
        })
      } else {
        // 角色接收到同屏数据
        socket.on('sync', (data: any) => {
          __sdk.Connect.follow.receive(data)
          emits('receiveSync', data)
        })
      }
    })
  }
}
watchEffect(async () => {
  if (props.socketLib) {
    try {
      await loadSocket(unref(props.socketLib))
      isSocketLoad.value = true
    } catch {
      // eslint-disable-next-line no-console
      isSocketLoad.value = false
      console.error('socket load fail!')
    }
  }
})
watch(
  [isSDKLoad, isSocketLoad],
  async (checker) => {
    if (unref(checker[0]) && unref(checker[1])) {
      // console.error(`isSDKLoaded`)
      await handleSocketSetup()
      __sdk.Connect.follow.start({ follow: !unref(isLeader) })
    }
  },
  {
    immediate: true,
  }
)
</script>
