<script setup lang="ts">
import { useUserStore } from '@/stores/user'
import { useLive, readBlobAsBase64 } from '@/composables/useLive'
import { useSocket } from '@/composables/useSocket'
import md5 from 'blueimp-md5'

const userStore = useUserStore()
const ssoId = userStore.user?.id

const fileUrl = ref('')
const fileName = computed(() => md5(`${ssoId}${startTime.value}`))

// WebSocket 设置
const { send } = useSocket({
  onMessage: (ws, event) => {
    try {
      const data = JSON.parse(event.data)
      if (data?.type === 'video_rtc') {
        fileUrl.value = data.data.uri
      }
    } catch (error) {
      console.error('Failed to parse message:', error)
    }
  },
})

const { startTime, start, stop } = useLive({
  onRecord: async (blob) => {
    console.log('onRecord', blob)
    const base64Data = await readBlobAsBase64(blob)
    const jsonData = JSON.stringify({
      type: 'send',
      sso_id: ssoId,
      data: { type: 'video_rtc', channel: 'rtc', data: { video: base64Data, file_name: fileName.value } },
    })
    send(jsonData)
  },
})

onMounted(() => {
  start()
})

onUnmounted(() => {
  stop()
})
</script>

<template>
  <div class="live"></div>
</template>
