// component/voice/voice.js

Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    show: true,
    pushUrl: false,
    pullUrls: [],
    trtcConfig: {},
    room: 0
  },
  


  attached() {
    this.callback = (user={}) => {
      console.warn('---user---', user,'---user---')
      if (user.action === 'stopCall' && this.hasEnter) {
        this.unpublishLocalAudio()
        this.trtcRoomContext.exitRoom()
        this.hasEnter = false
        return
      }
      if (user.userId) {
        this.enterAudioRoom(user)
        return
      }
      console.warn(user.noMute, '---noMute')
      if (user.noMute) {
        this.unpublishLocalAudio()
      } else {
        this.publishLocalAudio()
      }
    }
    // console.log(getApp().globalData.pusher, 'getApp().globalData.pusher')
    // if (getApp().globalData.pusher) {
    //   this.callback(getApp().globalData.pusher)
    // }
    console.log('attch')
    getApp().addVoicePropsListener(this.callback)
  },
  detached() {
    console.log('detached')
    getApp().removeVoicePropsListener(this.callback)
    // this.trtcRoomContext.exitRoom()
    this.hasEnter = false
  },
  pageLifetimes: {
    show() {
      this.setData({show: true})
      // this.trtcRoomContext = this.selectComponent('#trtcroom')
      // if (getApp().globalData.audioUser) {
      //   this.enterAudioRoom(getApp().globalData.audioUser, true)
      // }
      // if (this.data.show) {
      //   this.enterAudioRoom()
      // }
    },
    hide() {
      clearTimeout(this.time)
      this.setData({show: false})
    },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    enterAudioRoom(user, noEnter) {
      // if (this.hasEnter) {
      //   return
      // }
      console.error('hasEnter', this.hasEnter)
      this.hasEnter = true
      getApp().globalData.audioUser = user
      console.log(user, 'user')
      this.setData({
        trtcConfig: {
          scene: 'rtc',
          sdkAppID: '1400450635', // 开通实时音视频服务创建应用后分配的 SDKAppID
          userID: user.userId, // 用户 ID，可以由您的帐号系统指定
          userSig: user.sig, // 身份签名，相当于登录密码的作用
          template: 'custom', // 画面排版模式
        }
      }, () => {
        this.trtcRoomContext = this.selectComponent('#trtcroom')
        if (noEnter) {
          return
        }
        console.log(this.trtcRoomContext, )
        let EVENT =this.trtcRoomContext.EVENT
  
        if (this.trtcRoomContext) {
          this.trtcRoomContext.on(EVENT.LOCAL_JOIN, (event) => {
            // 进房成功后发布本地音频流和视频流 
            console.error('进入房间')
            this.successEnter = true
            if (user.noMute) {
              this.unpublishLocalAudio()
            } else {
              this.publishLocalAudio()
            }
          })
  
          this.trtcRoomContext.on(EVENT.LOCAL_LEAVE, (event) => {
            console.error('离开房间')
          })

          // 监听远端用户的音频流的变更事件
         this.trtcRoomContext.on(EVENT.REMOTE_AUDIO_ADD, (event) => {
            // 订阅（即播放）远端用户的音频流
            let userID = event.data.userID
           this.trtcRoomContext.subscribeRemoteAudio({
              userID: userID
            })
          })
          // this.trtcRoomContext.on(EVENT.LOCAL_AUDIO_VOLUME_UPDATE, event => {
          //   console.log(event)
          // })
         this.trtcRoomContext.enterRoom({
            roomID: getApp().globalData.roomId
          }).then(() => {
            
            console.log('成功进入房间')
          }).catch((res) => {
            console.error('room joinRoom 进房失败:', res)
            this.hasEnter = false
          })
          let timer = null
          timer = setInterval(() => {
            if (!this.successEnter) {
              this.trtcRoomContext.enterRoom({
                roomID: getApp().globalData.roomId
              }).then(() => {
                console.log('成功进入房间')
              }).catch((res) => {
                console.error('room joinRoom 进房失败:', res)
                this.hasEnter = false
              })
            } else {
              clearInterval(timer)
              timer = null
            }
          }, 3000);
        }
      })
    },
    unpublishLocalAudio () {
      this.trtcRoomContext && this.trtcRoomContext.unpublishLocalAudio()
    },
    publishLocalAudio () {
      this.trtcRoomContext && this.trtcRoomContext.publishLocalAudio()
    }
  }
})
