import { defineComponent, ref } from 'vue'
import * as RTC from '@rongcloud/plugin-rtc'
import Header from './header'
import ActionBar from './action-bar'
import VideoStatus from './video-status'
import { state } from '/src/state'
import event, { LIVE_EVENT_MESSAGE } from './event'
import runtime, * as RuntimeUtils from './runtime'
import { removeMedia } from './helpers'
import styles from './index.module.less'

const videoRef = ref<HTMLVideoElement | null>(null)

let microphoneAudioTrack: RTC.RCLocalTrack
let cameraVideoTrack: RTC.RCLocalTrack

export default defineComponent({
  name: 'LiveBroadcast',
  async mounted() {
    this.initializeRoom()
    RuntimeUtils.loopSyncLike()
    event.on(LIVE_EVENT_MESSAGE['RC:Chatroom:Like'], this.onLikeMessage)
  },
  beforeUnmount() {
    event.off(LIVE_EVENT_MESSAGE['RC:Chatroom:Like'], this.onLikeMessage)
  },
  methods: {
    onLikeMessage(msg: any) {
      runtime.likeCount += msg.counts
    },
    async initializeRoom () {
      if (!state.user) throw Error('请先登录')
      try {
        await RuntimeUtils.connectIM(state.user?.imToken)
        runtime.videoRef = videoRef.value
        await RuntimeUtils.getMicrophones()
        await RuntimeUtils.getCameras()
        RuntimeUtils.setSelectCamera(runtime.cameras[0])
        RuntimeUtils.setSelectMicrophone(runtime.microphones[0])
        cameraVideoTrack = await RuntimeUtils.getTrack('camera')
        runtime.videoRef && cameraVideoTrack.play(runtime.videoRef)
        await RuntimeUtils.setTrack([cameraVideoTrack], 'camera')
        microphoneAudioTrack = await RuntimeUtils.getTrack('microphone')
        runtime.videoRef && microphoneAudioTrack.play(runtime.videoRef)
        console.log(runtime.deviceStatus)
        runtime.videoStatus = 'stream'
        const join = await RuntimeUtils.joinRoom(state.user?.roomUid, RTC.RCLivingType.VIDEO, {
          onMessageReceive(name, content) {
            console.log(name, content)
          },
          onKickOff(byServer: boolean) {
            console.log(byServer)
          },
          async onTrackPublish (tracks: RTC.RCRemoteTrack[]) {
            const subscribeRes = await join?.room?.subscribe(tracks)
            console.log(subscribeRes)
            if (subscribeRes?.code && subscribeRes.code !== RTC.RCRTCCode.SUCCESS) {
              console.log('资源订阅失败 ->', subscribeRes.code)
            }
          },
          onTrackUnpublish(tracks: RTC.RCRemoteTrack[]) {
            console.log(tracks)
            event.emit(LIVE_EVENT_MESSAGE['RM:RTC:TrackUnpublish'], tracks)
          },
          onSwitchRole(userId: string, role: RTC.RCRTCLiveRole) {
            event.emit(LIVE_EVENT_MESSAGE['RM:RTC:SwitchRole'], {
              userId,
              role,
            })
          },
          onTrackReady (track: RTC.RCRemoteTrack) {
            if (track.isAudioTrack()) {
              // 音轨不需要传递播放控件
              track.play()
            }
          },
          onUserJoin (userIds: string[]) {
            console.log('onUserJoin', userIds)
          },
          onUserLeave (userIds: string[]) {
            event.emit(LIVE_EVENT_MESSAGE['RM:RTC:UserLeave'], userIds)
            console.log('onUserLeave', userIds)
          },
        })
        if (join.room && join.code === RTC.RCRTCCode.SUCCESS) {
          runtime.joinedRoom = join.room
        }
      } catch (error) {
        runtime.videoStatus = 'error'
        console.log(error)
      }
    },
    closeLive() {
      removeMedia(runtime.mediaStreams, runtime.mediaStreamTrack)
      runtime.videoStatus = 'stopped'
    },
  },
  render() {
    return (
      <div class={styles.main}>
        <Header/>
        <div class={styles.video}>
          <video ref={videoRef}></video>
          <VideoStatus/>
        </div>
        <ActionBar/>
        {/* <div>video: {runtime.videoStatus}, imStatus: {runtime.imConnectStatus}</div> */}
      </div>
    )
  }
})
