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'
import { usePermission, useIntervalFn } from '@vueuse/core'

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 { startTime, start, stop, restart } = useLive({
    enabledUserMedia: autoStart,
    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)
    },
  })

  const cameraPermission = usePermission('camera')

  const hasMessageBox = ref(false)
  const showMessageBox = () => {
    if (hasMessageBox.value) return
    hasMessageBox.value = true
    ElMessageBox.alert('本次考试要求全程开启摄像头，请点击‘确定’允许摄像头访问，以便正常参加考试。', '温馨提示', {
      confirmButtonText: '确定',
      // beforeClose: (action, instance, done) => {
      //   console.log('stream', stream.value)
      //   console.log('cameraPermission', cameraPermission.value)
      //   if (stream.value && cameraPermission.value === 'granted') done()
      // },
      callback: () => {
        hasMessageBox.value = false
        restart()
      },
    })
  }

  useIntervalFn(() => {
    if (cameraPermission.value === 'denied') showMessageBox()
  }, 1000 * 10)

  onMounted(() => {
    if (autoStart) showMessageBox()
  })

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

  return { fileUrl, fileName, start, stop }
}
