/**
 * assistant.html：左侧视频下方「直播状态 + 在线人数」条
 * 对齐 live-web-operator/src/pc/components/Internactions.vue 左侧 controls.left：
 * - liveRoomInfo.live.status === 1 → 直播中（动效条替代运营端 living.gif）
 * - 否则 → 圆点 + 待直播
 * - roomSetting.onlineUser === 1 → 展示在线人数 +「人在线」
 * 数据：登录 settings / live；DWLive.livestatus（开播停播信令）；onRoomContext 在线列表；onUserCountMessage 房间人数（若服务端下发）
 */
;(function ($) {
  var state = {
    onlineUserSetting: 0,
    onlineCount: 0
  }

  function byId(id) {
    return document.getElementById(id)
  }

  function render() {
    var living = typeof DWLive !== 'undefined' && DWLive.livestatus === 1
    var liveOn = byId('assistant-live-status-living')
    var liveOff = byId('assistant-live-status-wait')
    var people = byId('assistant-live-status-people')
    if (liveOn && liveOff) {
      liveOn.style.display = living ? 'inline-flex' : 'none'
      liveOff.style.display = living ? 'none' : 'inline-flex'
    }
    if (people) {
      people.style.display = state.onlineUserSetting === 1 ? 'inline-flex' : 'none'
      var numEl = byId('assistant-live-online-num')
      if (numEl) numEl.textContent = String(state.onlineCount)
    }
  }

  function applyLogin(data) {
    var s = data && data.settings
    if (s && s.onlineUser != null) state.onlineUserSetting = Number(s.onlineUser)
    render()
  }

  function applyRoomContext(res) {
    var rs = res && res.roomSettings
    if (rs && rs.onlineUser != null) state.onlineUserSetting = Number(rs.onlineUser)
    if (res && Array.isArray(res.onlineUsers)) state.onlineCount = res.onlineUsers.length
    render()
  }

  $(function () {
    var prevCount = DWLive.onUserCountMessage
    DWLive.onUserCountMessage = function (j) {
      if (typeof prevCount === 'function') prevCount(j)
      try {
        var d = typeof j === 'string' ? JSON.parse(j) : j
        var n =
          d &&
          (d.count != null
            ? d.count
            : d.userCount != null
              ? d.userCount
              : d.total != null
                ? d.total
                : d.data != null && typeof d.data === 'number'
                  ? d.data
                  : null)
        if (n != null && !isNaN(Number(n))) state.onlineCount = Number(n)
      } catch (e) {}
      render()
    }
    var prevEnd = DWLive.onLiveEnd
    DWLive.onLiveEnd = function (j) {
      if (typeof prevEnd === 'function') prevEnd(j)
      render()
    }
    var prevStart = DWLive.onLiveStart
    DWLive.onLiveStart = function (j) {
      if (typeof prevStart === 'function') prevStart(j)
      render()
    }
  })

  window.DemoLiveStatusBar_applyLogin = applyLogin
  window.DemoLiveStatusBar_onRoomContext = applyRoomContext
  window.DemoLiveStatusBar_refresh = render
})(jQuery)
