<template>
  <Icon
    name="mic"
    :size="22"
    :color="show && rtcConnected ? '#00CED1' : 'rgba(255, 255, 255, 0.5)'"
    style="margin-left: 6px;"
    @click="change"
  />
</template>

<script setup lang='ts'>
import { useNotification } from 'naive-ui'
import {
  computed, onMounted, onUnmounted, ref
} from 'vue'
import useStore from '@/store'

const props = withDefaults(defineProps<{ value?: number }>(), { value: 5000 })
const emit = defineEmits<{(evt: 'callBack', value: Blob): void }>()
const notice = useNotification()
const store = useStore()
const rtcConnected = computed(() => store.rtcConnected)
const show = ref(false)
let chunks = [] as Blob[]
let audio = null as null | MediaRecorder
let timer = null as Any

async function initMic() {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
    audio = new MediaRecorder(stream)
    audio.ondataavailable = (e: { data: Blob }) => {
      chunks.push(e.data)
    }
    audio.onstart = () => {
      chunks = []
    }
    audio.onstop = () => {
      const blob = new Blob(chunks, { type: 'audio/webm;codecs=opus' })
      emit('callBack', blob)
    }
  } catch (error: any) {
    console.log('录音错误', error)
    const type = error.toString().includes('getUserMedia')
    notice.warning({ title: type ? '不支持webrtc音频' : '未获取到音频设备', duration: 2000 })
  }
}

function distory() {
  if (audio) audio.stop()
  chunks = []
  audio = null
}

function change() {
  if (!rtcConnected.value) return
  show.value = !show.value
  if (!audio) return
  if (show.value) { audio?.start(); timer = setTimeout(() => { show.value = false; audio?.stop() }, props.value) } else { audio?.stop(); clearTimeout(timer) }
  console.log('mic', show.value)
}

onMounted(() => initMic())

onUnmounted(() => distory())
</script>
<style lang="scss" scoped>
svg {
  cursor: pointer;
}
</style>
