/**
 * 演示页启动逻辑：在 assistantsdk、live.js、ui.js、hdChat.js 之后执行。
 * 负责 DWLive.init、公聊 hdChat 实例化，以及本页用到的少量全局回调。
 */
;(function ($) {
  var cfg = window.DEMO_CONFIG || {}
  var dwInit = cfg.dwInit || {}
  var hdOpts = cfg.hdChat || {}

  function dlog() {
    if (dwInit.debug && window.console && console.log) {
      console.log.apply(console, arguments)
    }
  }

  window._onStart = function () {
    dlog('websdk log: window._onStart')
  }

  // 从 localStorage 中获取 token
  try {
    var saved = JSON.parse(localStorage.getItem('dwlive_token_' + (dwInit.roomid || '')) || 'null')
    if (saved && saved.token) dwInit.token = saved.token
  } catch (e) {}

  DWLive.init(dwInit)

  $('#destroy').click(function () {
    DWLive.destroy()
    dlog('websdk log: DWLive.destroy')
  })

  DWLive.onLoginSuccess = function (data) {
    dlog('websdk log: DWLive.onLoginSuccess', data)
    try {
      localStorage.setItem('dwlive_token_' + (DWLive.roomid || ''), JSON.stringify({ token: DWLive.token }))
    } catch (e) {}
    if (typeof window.DemoLiveStatusBar_applyLogin === 'function') {
      try {
        window.DemoLiveStatusBar_applyLogin(data)
      } catch (e) {
        console.warn('DemoLiveStatusBar_applyLogin', e)
      }
    }
    DWLive.groupId = data.viewer.groupId
    $('#assistant_viewer_name').text(DWLive.viewername || '')

    if (typeof hdChat === 'undefined') {
      console.warn('hdChat 未加载，请检查 live.html 中 hdChat.js 地址')
      return
    }
    // user.role 会参与互动 token 签发：0=学生无公告等管理权限；与运营端一致助教为 2
    var hdUser = $.extend(
      {
        role: 2,
        userid: DWLive.viewerid,
        username: DWLive.viewername,
        avatar: ''
      },
      (hdOpts && hdOpts.user) || {}
    )
    window.hdchat = new hdChat($.extend(true, {
      container: document.getElementById('chat'),
      roomId: DWLive.roomid,
      accountId: DWLive.userid,
      token: DWLive.token,
      user: hdUser
    }, hdOpts))

    if (typeof window.DemoUserPanel_attachHdchat === 'function') {
      try {
        window.DemoUserPanel_attachHdchat(window.hdchat)
      } catch (e) {
        dlog('DemoUserPanel_attachHdchat', e)
      }
    }

    if (typeof window.DemoAnnouncementPanel_attachHdchat === 'function') {
      try {
        window.DemoAnnouncementPanel_attachHdchat(window.hdchat)
      } catch (e) {
        dlog('DemoAnnouncementPanel_attachHdchat', e)
      }
    }

    if (typeof window.DemoBroadcastPanel_attachHdchat === 'function') {
      try {
        window.DemoBroadcastPanel_attachHdchat(window.hdchat)
      } catch (e) {
        dlog('DemoBroadcastPanel_attachHdchat', e)
      }
    }

    hdchat.on('getTokenError', function (err) {
      if (err) {
        try {
          localStorage.removeItem('login')
          localStorage.removeItem('data')
        } catch (e) {}
      }
    })
    hdchat.on('liveCardClick', function (res) {
      dlog('hdchat liveCardClick', res)
    })
  }
  DWLive.onRoomContext = function (res) {
    dlog('websdk log: DWLive.onRoomContext', res)
    if (typeof window.DemoUserPanel_applyRoomContext === 'function') {
      try {
        window.DemoUserPanel_applyRoomContext(res)
      } catch (e) {
        console.warn('DemoUserPanel_applyRoomContext', e)
      }
    }
    if (typeof window.DemoRoomBaseUserPanel_onRoomContext === 'function') {
      try {
        window.DemoRoomBaseUserPanel_onRoomContext(res)
      } catch (e) {
        console.warn('DemoRoomBaseUserPanel_onRoomContext', e)
      }
    }
    if (typeof window.DemoLiveStatusBar_onRoomContext === 'function') {
      try {
        window.DemoLiveStatusBar_onRoomContext(res)
      } catch (e) {
        console.warn('DemoLiveStatusBar_onRoomContext', e)
      }
    }
  }
  DWLive.on_live_play = function () {
    dlog('直播开始播放')
  }

  DWLive.onLiveStart = function (j) {
    dlog('websdk log: onLiveStart', j)
    var m = DWLive.marquee
    if (m) {
      setTimeout(function () {
        DWLive.showMarquee(m)
        dlog('websdk log: DWLive.showMarquee', m)
      }, 1500)
    }
  }

  DWLive.onInteractionToken = function (data) {
    dlog('websdk log: onInteractionToken', data)
  }
  DWLive.onInteractionSettings = function (data) {
    dlog('websdk log: onInteractionSettings', data)
  }
  DWLive.onRoomSettings = function (data) {
    dlog('onRoomSettings', data)
    window.onRoomSettings(data)
  }
  DWLive.onInteractionDisconnect = function (res) {
    dlog('onInteractionDisconnect', res)
  }

  DWLive.onChatCustomEmoji = function (data) {
    dlog('onChatCustomEmoji', data)
  }

  DWLive.onSwitchSource = function (data) {
    dlog('websdk log: DWLive.onSwitchSource', data)
    var parsed = JSON.parse(data)
    var arr = ['30', '40', '50']
    if (!arr.includes(parsed.source_type)) {
      $('#doc-main').attr('data-module', 0)
    } else {
      $('#doc-main').attr('data-module', 1)
    }
    if (typeof switchPptToVideo === 'function') switchPptToVideo()
  }

  DWLive.onLoginError = function (error) {
    console.warn('websdk log: DWLive.onLoginError', error)

  }

  DWLive.onSwitchVideoDoc = function (main) {
    dlog('websdk log: DWLive.onSwitchVideoDoc', main)
    var isVideoMain = main === 'true' ? 1 : 0
    $('#doc-main').attr('data-module', isVideoMain)
    if (typeof switchPptToVideo === 'function') switchPptToVideo()
  }

  window.switch_main_show_marquee = function () {
    var m = DWLive.marquee
    if (!m) return
    if (typeof isMainVideo !== 'undefined' && !isMainVideo) {
      DWLive.closeMarquee()
      DWLive.showMarqueeDoc(typeof m === 'string' ? m : JSON.stringify(m))
    } else {
      DWLive.closeMarqueeDoc()
      DWLive.showMarquee(m)
    }
  }

  window.on_hdLive_drawPanel_complete = function () {
    dlog('websdk log: DWLive.docAdapt', true)
  }
  window.on_cc_live_pagechange_complete = function (data) {
    dlog('websdk log: on_cc_live_pagechange_complete', data)
  }
  window.on_cc_live_pagechange_error = function (data) {
    dlog('websdk log: on_cc_live_pagechange_error', data)
  }
  window.cc_player_stream_disconnect = function () {
    dlog('websdk log: cc_player_stream_disconnect')
  }
  window.cc_player_stream_waiting = function () {
    dlog('websdk log: cc_player_stream_waiting')
  }
  window.onSocketConnect = function () {
    dlog('websdk log: onSocketConnect')
  }
  window.onSocketDisconnect = function () {
    dlog('websdk log: onSocketDisconnect')
  }
  window.on_cc_swf_loading_completed = function () {
    dlog('websdk log: on_cc_swf_loading_completed')
  }

  $('#full-screen').click(function () {
    DWLive.switchFullScreen(true)
    dlog('websdk log: DWLive.switchFullScreen', true)
  })
  $('#getDocs').click(function () {
    DWLive.getDocs(function (data) {
      dlog('websdk log: DWLive.getDocs', data)
    })
  })
  $('#docAdapt').click(function (e) {
    if (e.target.innerText === '文档适高') {
      DWLive.docAdapt(true)
      $('#docAdapt').text('文档适宽')
    } else {
      DWLive.docAdapt(false)
      $('#docAdapt').text('文档适高')
    }
    dlog('websdk log: DWLive.docAdapt')
  })

  DWLive.onKickOut = function (data) {
    dlog('websdk log: DWLive.onKickOut', data)
    DWLive.logout({
      success: function () {
        window.location.href = './login/index.html'
      },
      error: function (err) {
        console.warn('logout error', err)
      }
    })
  }

  window.onbeforeunload = function () {
    if (typeof DWLive.destroy === 'function') DWLive.destroy()
  }

  $('#submitPracticeInfo').click(function () {
    var pId = $('#practiceId').val()
    var opt = $('#practiceOpt').val()
    DWLive.submitPracticeInfo(pId, opt, function (data) {
      dlog('websdk log: DWLive.submitPracticeInfo', pId, opt, data)
    })
  })

  var punchId
  DWLive.onHdLiveStartPunch = function (data) {
    dlog('websdk log: onHdLiveStartPunch', data)
    DWLive.getHdInquirePunchInformation(function (res) {
      punchId = res.data && res.data.punch && res.data.punch.id
      dlog('websdk log: getHdInquirePunchInformation', res)
    })
  }
  DWLive.onHdLiveStopPunch = function (data) {
    dlog('websdk log: onHdLiveStopPunch', data)
  }
  $('#hdCommitPunch').click(function () {
    DWLive.hdCommitPunch(punchId, function (data) {
      dlog('websdk log: DWLive.hdCommitPunch', punchId, data)
    })
  })

  function isSafari() {
    return /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent)
  }
})(jQuery)
