<template>
  <LiveLayout
    :liveInfo="liveInfo"
    class="live-student"
    :quitText="isPlaying ? '结束直播' : '退出'"
    @quitLive="quitLive"
  >
    <template v-slot:liveBodyLeftMenu>
      <div class="live-body-left">
        <div
          @click="openMediaFun('mic')"
          :class="{
            'left-menu-item': true,
            'left-menu-item-open': openMedia.mic,
          }"
        >
          <i class="i-j-jxzb-yangshengqi"></i>
          {{ openMedia.mic ? "静音" : "解除静音" }}
        </div>
        <div
        @click="openMediaFun('camera')"
          :class="{
            'left-menu-item': true,
          }"
        >

          <i class="i-j-jxzb--shiping"></i>
          摄像头
        </div>
        <!-- <div
          @click="openMediaFun('camera')"
          :class="{
            'left-menu-item': true,
            'left-menu-item-open': openMedia.camera,
          }"
        >
          <i class="i-j-jxzb--shiping"></i>
          摄像头
        </div> -->
        <!-- <div
          @click="openMediaFun('screen')"
          :class="{
            'left-menu-item': true,
            'left-menu-item-open': openMedia.screen,
          }"
        >
          <i class="i-j-jxzb-diannao"></i>
          共享屏幕
        </div> -->
        <!-- <div class="left-menu-item">
          <i class="i-j-jxzb-kejian"></i>
          课件
        </div>
        <div class="left-menu-item">
          <i class="i-x-zxks-canjiakaoshi"></i>
          答题
        </div> -->
      </div>
    </template>
    <template v-slot:playingBox>
      <div class="live-playing" v-show="isPlaying">
        <video
          controls
          muted
          autoplay
          class="video-play"
          ref="videoPlayer"
        ></video>
        <video
          controls
          muted
          autoplay
          class="camera-play"
          style="visibility: hidden;
    width: 0;
    height: 0;;position: fixed;"
          ref="cameraPlayer"
        ></video>
      </div>
      <div class="live-not-start" v-show="!isPlaying">
        直播{{ liveInfo?.status == 1 ? "已暂停" : "未开始" }}，马上开始直播吧！
        <div class="start-button">
          <el-button type="success" round @click="startLive"
            >开始直播</el-button
          >
        </div>
      </div>
    </template>
  </LiveLayout>
</template>

<script>
import LiveLayout from '../components/live-layout.vue'
import {
  getLivePublishInfoAPI,
  updateLiveInfoAPI
} from '@/api/online-teaching/live-manage'

import {
  SrsRtcPublisherAsync,
  SrsError,
  PIPCameraPlayer
} from '@/views/assessment-evaluation/utils/gy.srs.sdk'
import chatListmixins from '../live-play/mixins/live'
export default {
  components: {
    LiveLayout
  },

  data () {
    return {
      liveInfo: null,
      openMedia: { mic: false, screen: false, camera: false },
      isPlaying: false
    }
  },
  mixins: [chatListmixins],
  async activated () {
    this.room = { id: this.$route.query.id }
    this.isPlaying = false
    this.getLiveWatchInfo()
  },

  methods: {
    async startLive () {
      await updateLiveInfoAPI({ id: this.liveInfo.id, status: 1 })
      this.$nextTick(async () => {
        this.openMedia.mic = true
        await this.getMediaStream(this.openMedia.mic)
          .then(() => {
            this.isPlaying = true
          })
          .catch(() => {
            self.isPlaying = false
          })
      })
    },
    async getMediaStream (micro) {
      if (!micro || micro instanceof PointerEvent) micro = this.openMedia.mic
      if (this.sdk) {
        this.sdk.close()
      }
      // alert(JSON.stringify(micro))
      this.sdk = new SrsRtcPublisherAsync()
      this.$refs.videoPlayer.srcObject = this.sdk.stream

      const url = window.GyConfig.webRtcUrl + this.$route.query.id
      const self = this
      return this.sdk.publish(url, { micro }).catch(function (reason) {
        if (reason instanceof SrsError) {
          if (reason.name === 'HttpsRequiredError') {
            self.$message.error('WebRTC推流必须是HTTPS或者localhost')
          } else {
            console.error(`${reason.name} ${reason.message}`)
          }
        }
        if (reason instanceof DOMException) {
          if (reason.name === 'NotFoundError') {
            self.$message.error('找不到麦克风和摄像头设备')
          } else if (reason.name === 'NotAllowedError') {
            self.$message.error('你禁止了网页访问摄像头和麦克风')
          } else if (
            [
              'AbortError',
              'NotAllowedError',
              'NotFoundError',
              'NotReadableError',
              'OverconstrainedError',
              'SecurityError',
              'TypeError'
            ].includes(reason.name)
          ) {
            self.$message.error(
              `getUserMedia ${reason.name} ${reason.message}`
            )
          }
        }
        self.sdk.close()
        self.sdk = null
        console.error(reason)
        throw ErrorEvent()
      })
    },
    async getLiveWatchInfo () {
      const { data } = await getLivePublishInfoAPI(this.room.id)
      this.liveInfo = data
    },
    async playCamera () {
      const camera = new PIPCameraPlayer()
      this.$refs.cameraPlayer.srcObject = camera.stream
      this.$refs.cameraPlayer.onloadeddata = () => {
        this.$refs.cameraPlayer.requestPictureInPicture()
      }
      return await camera.play()
    },
    openMediaFun (media) {
      if (media instanceof PointerEvent) return
      this.openMedia[media] = !this.openMedia[media]
      if (media === 'mic') {
        this.sdk.muted(this.openMedia[media])
      }
      if (media === 'camera') {
        // this.$refs.cameraPlayer.requestPictureInPicture()
        this.playCamera().catch(err => {
          if (err?.name === 'NotFoundError') {
            this.$message.error('没找到摄像头')
          } else if (err?.name === 'NotReadableError') {
            this.$message.error('摄像头画面读取失败')
          }
        })
      }
    },
    quitLive () {
      if (!this.isPlaying) {
        // this.$router.replace('/online-teaching/live-lectures').then()
        this.$router.replace('/online-course/live-lectures').then()
        return
      }
      this.$confirm('即将结束直播, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await updateLiveInfoAPI({ id: this.liveInfo.id, status: 2 })

          this.ws_finish_live()
          // this.$router.replace('/online-teaching/live-lectures').then(() => {
          this.$router.replace('/online-course/live-lectures').then(() => {
            location.reload()
          })
        }

        )
        .catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.live-student {
  height: 100%;
  width: 100%;
}
</style>
<style>
.v-card:has(.live-student) {
  padding: 0 !important;
}
</style>
