<template>
  <div class="QdmRecording">
    <button @click="clicks()">{{status ? stopName : startName}}</button>
  </div>
</template>
<script>
export default {
  name: 'QdmRecording',
  props: {
    fileName: {
      type: String,
      default: '录屏文件'
    },
    startName: {
      type: String,
      default: '开始录制'
    },
    stopName: {
      type: String,
      default: '停止录制'
    }
  },
  data() {
    return {
      timeout: 0,
      recordedBlobs: [],
      status: false,
      stream: null,
      options: {
        audioBitsPerSecond: 128000,
        videoBitsPerSecond: 4500000,
        mimeType: 'video/webm'
      },
      startTime: 0,
      endTime: 0
    }
  },
  methods: {
    clicks() {
      if (this.status) {
        this.stopReset()
        this.status = false
      } else {
        this.startScreen()
      }
    },
    stopReset() {
      this.stream.getTracks().forEach(track => track.stop())
      this.recordedBlobs = []
    },
    startScreen() {
      navigator.mediaDevices.getDisplayMedia({ video: true, audio: true }).then(
        stream => {
          this.status = !this.status
          this.startTime = new Date().getTime()
          this.stream = stream
          const mediaRecorder = new MediaRecorder(stream, this.options)
          mediaRecorder.ondataavailable = event => {
            if (event.data.size > 0) {
              this.status = false
              this.recordedBlobs.push(event.data)
              this.download()
              this.stopReset()
            }
          }
          mediaRecorder.start()
        },
        error => console.log(error)
      )
    },
    download() {
      const blob = new Blob(this.recordedBlobs, { type: 'video/mp4' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      document.body.appendChild(a)
      a.style.display = 'none'
      a.href = url
      if (this.fileName) {
        a.download = this.fileName + '.mp4'
      } else {
        a.download = new Date() + '.mp4'
      }
      a.click()
      window.URL.revokeObjectURL(url)
    }
  }
}
</script>
