import { useUserStore } from '@/stores/user'
import { useLive, readBlobAsBase64 } from '@/composables/useLive'
import { useSocket } from '@/composables/useSocket'
import md5 from 'blueimp-md5'
import { ElMessageBox } from 'element-plus'

export function useLiveMonitor({ autoStart = false }: { autoStart?: boolean } = {}) {
  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 { stream, startTime, start, stop } = useLive({
    onRecord: async (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)
    },
  })

  watchEffect(() => {
    if (autoStart) {
      ElMessageBox.alert('本次考试要求全程开启摄像头，请点击‘确定’允许摄像头访问，以便正常参加考试。', '温馨提示', {
        confirmButtonText: '确定',
        beforeClose: (action, instance, done) => {
          if (stream.value) done()
        },
        callback: () => {
          start()
        },
      })
    }
  })

  onUnmounted(() => {
    stop()
  })

  return { fileUrl, fileName, start, stop }
}
