/**
 * assistant.html 问答面板：对齐 live-web-operator question.vue 的核心数据流与操作
 * — onQuestion / onAnswer / onQaPublish 与 DWLive.publishQuestion、DWLive.answerQuestion
 */
;(function ($) {
  var MAX_REPLY = 1000

  function parsePayload(j) {
    if (j == null) return null
    if (typeof j === 'string') {
      try {
        return JSON.parse(j)
      } catch (e) {
        return null
      }
    }
    return j
  }

  function escapeHtml(s) {
    if (s == null) return ''
    return String(s)
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
  }

  function groupMatch(v) {
    if (!v) return false
    var g = DWLive.groupId
    return v.groupId === g || !g || !v.groupId
  }

  function nick(name) {
    return escapeHtml(name || '')
  }

  var state = {
    questions: [],
    answers: [],
    publishedIds: [],
    replay: false,
    replayIndex: -1,
    operateIndex: -1,
    replayContent: '',
    replayPrivate: false,
    curQuestion: null,
    uploading: false
  }

  var els = {}

  function currentAnswers(questionId) {
    return state.answers.filter(function (a) {
      return a.questionId === questionId
    })
  }

  function isPublishedUi(q) {
    return (
      currentAnswers(q.id).length > 0 ||
      !!q.publish ||
      state.publishedIds.indexOf(q.id) !== -1
    )
  }

  function findQuestionIndex(id) {
    for (var i = 0; i < state.questions.length; i++) {
      if (state.questions[i].id === id) return i
    }
    return -1
  }

  function replayBoxHtml(index) {
    var len = (state.replayContent || '').length
    return (
      '<div class="qa-replay-box" data-replay-index="' +
      index +
      '">' +
      '<textarea class="qa-replay-input" maxlength="' +
      MAX_REPLY +
      '" placeholder="输入回复内容">' +
      escapeHtml(state.replayContent) +
      '</textarea>' +
      '<div class="qa-replay-meta">' +
      '<span></span><span class="qa-char-count">' +
      len +
      '/' +
      MAX_REPLY +
      '</span></div>' +
      '<div class="qa-replay-actions">' +
      '<label><input type="checkbox" class="qa-private-only" ' +
      (state.replayPrivate ? 'checked' : '') +
      '> 仅提问者可见</label>' +
      '<div class="qa-replay-btns">' +
      '<button type="button" class="qa-send">发送</button>' +
      '<button type="button" class="qa-cancel">取消</button>' +
      '</div></div></div>'
    )
  }

  function render() {
    var ul = els.qaList
    if (!ul) return

    if (!state.questions.length) {
      ul.innerHTML = '<li class="qa-empty">暂无提问</li>'
      return
    }

    var html = ''
    for (var index = 0; index < state.questions.length; index++) {
      var q = state.questions[index]
      var answers = currentAnswers(q.id)
      var published = isPublishedUi(q)
      var imgs = (q.extra && q.extra.img) || []
      var imgHtml = ''
      if (imgs.length) {
        imgHtml = '<div class="qa-imgs">'
        for (var ii = 0; ii < imgs.length; ii++) {
          var u = imgs[ii].url || imgs[ii]
          imgHtml +=
            '<img src="' +
            escapeHtml(u) +
            '" alt="" data-preview="' +
            escapeHtml(u) +
            '">'
        }
        imgHtml += '</div>'
      }

      var ansHtml = ''
      if (answers.length) {
        ansHtml = '<div class="qa-answers">'
        for (var ai = 0; ai < answers.length; ai++) {
          var a = answers[ai]
          var my =
            DWLive.viewerid && String(a.userId) === String(DWLive.viewerid)
          var aimgs = (a.extra && a.extra.img) || []
          var aimgBlock = ''
          if (aimgs.length) {
            aimgBlock = '<div class="qa-imgs">'
            for (var aj = 0; aj < aimgs.length; aj++) {
              var au = aimgs[aj].url || aimgs[aj]
              aimgBlock +=
                '<img src="' +
                escapeHtml(au) +
                '" alt="" data-preview="' +
                escapeHtml(au) +
                '">'
            }
            aimgBlock += '</div>'
          }
          ansHtml +=
            '<div class="qa-answer-row"><span class="qa-ans-user' +
            (my ? ' myanswer' : '') +
            '">' +
            nick(a.userName) +
            ': </span><span class="qa-ans-content">' +
            escapeHtml(a.content || '') +
            '</span>' +
            aimgBlock +
            '</div>'
        }
        ansHtml += '</div>'
      }

      var replayOpen = state.replay && state.replayIndex === index
      var itemClass = 'qa-question-item' + (replayOpen ? ' qa-item--replay-open' : '')
      var pubBtn = published
        ? '<button type="button" class="qa-btn qa-btn--disabled" disabled>已发布</button>'
        : '<button type="button" class="qa-btn qa-publish" data-qid="' +
          escapeHtml(String(q.id)) +
          '">发布</button>'

      html +=
        '<li class="' +
        itemClass +
        '" data-index="' +
        index +
        '" data-qid="' +
        escapeHtml(String(q.id)) +
        '">' +
        '<div class="qa-info">' +
        '<span class="qa-nickname" title="' +
        escapeHtml(q.userName || '') +
        '">' +
        nick(q.userName) +
        '</span>' +
        '<div class="qa-actions">' +
        '<button type="button" class="qa-btn qa-reply" data-index="' +
        index +
        '">回复</button>' +
        '<button type="button" class="qa-btn qa-private-chat" data-index="' +
        index +
        '">私聊</button>' +
        pubBtn +
        '</div></div>' +
        '<div class="qa-body">' +
        '<span class="qa-icon-q">问</span>' +
        '<p class="qa-text">' +
        escapeHtml(q.content || '') +
        '</p></div>' +
        imgHtml +
        ansHtml +
        (replayOpen ? replayBoxHtml(index) : '') +
        '</li>'
    }
    ul.innerHTML = html
  }

  function bindListEvents() {
    var ul = els.qaList
    if (!ul || ul._qaBound) return
    ul._qaBound = true

    ul.addEventListener('click', function (e) {
      var t = e.target
      if (t.classList && t.classList.contains('qa-reply')) {
        var idx = parseInt(t.getAttribute('data-index'), 10)
        replayFn(state.questions[idx], idx)
        return
      }
      if (t.classList && t.classList.contains('qa-private-chat')) {
        var i2 = parseInt(t.getAttribute('data-index'), 10)
        privateChat(state.questions[i2])
        return
      }
      if (t.classList && t.classList.contains('qa-publish')) {
        if (state.uploading) return
        var qid = t.getAttribute('data-qid')
        if (typeof DWLive.publishQuestion === 'function') {
          DWLive.publishQuestion(qid)
        }
        return
      }
      if (t.classList && t.classList.contains('qa-send')) {
        publishFn()
        return
      }
      if (t.classList && t.classList.contains('qa-cancel')) {
        cancelFn()
        return
      }
      if (t.tagName === 'IMG' && t.getAttribute('data-preview')) {
        window.open(t.getAttribute('data-preview'), '_blank')
      }
    })

    ul.addEventListener('input', function (e) {
      if (e.target.classList && e.target.classList.contains('qa-replay-input')) {
        state.replayContent = e.target.value
        var box = e.target.parentElement
        if (box && box.classList && box.classList.contains('qa-replay-box')) {
          var cc = box.querySelector('.qa-char-count')
          if (cc) cc.textContent = state.replayContent.length + '/' + MAX_REPLY
        }
      }
    })

    ul.addEventListener('change', function (e) {
      if (e.target.classList && e.target.classList.contains('qa-private-only')) {
        state.replayPrivate = !!e.target.checked
      }
    })
  }

  function replayFn(question, index) {
    if (state.uploading) return
    if (!question) return
    state.curQuestion = {
      questionId: question.id,
      content: '',
      isPrivate: 0,
      userId: DWLive.viewerid,
      userName: DWLive.viewername,
      questionUserId: question.userId
    }
    state.replay = true
    state.replayIndex = index
    state.operateIndex = index
    state.replayContent = ''
    state.replayPrivate = false
    render()
    var ta = els.qaList && els.qaList.querySelector('.qa-replay-input')
    if (ta) {
      ta.focus()
    }
  }

  function cancelFn() {
    state.replayContent = ''
    state.replayPrivate = false
    state.replay = false
    state.replayIndex = -1
    state.curQuestion = null
    render()
  }

  function publishFn() {
    if (state.uploading) return
    if (!state.replayContent || !String(state.replayContent).trim()) {
      alert('请输入回复内容')
      return
    }
    if (!state.curQuestion || !state.curQuestion.questionId) return

    var payload = {
      questionId: state.curQuestion.questionId,
      content: String(state.replayContent).trim(),
      isPrivate: state.replayPrivate ? 1 : 0,
      userId: DWLive.viewerid,
      userName: DWLive.viewername,
      questionUserId: state.curQuestion.questionUserId
    }

    if (typeof DWLive.answerQuestion === 'function') {
      DWLive.answerQuestion(payload)
    }

    if (state.publishedIds.indexOf(state.curQuestion.questionId) === -1) {
      state.publishedIds.push(state.curQuestion.questionId)
    }
    cancelFn()
  }

  function privateChat(question) {
    if (state.uploading || !question) return
    switchTab('chat')
    if (window.console && console.info) {
      console.info(
        '[问答] 私聊对象（请在本页公聊区向该用户发起私聊，或使用 DWLive.sendPrivateChatMsg）:',
        question.userName,
        question.userId
      )
    }
  }

  function onQuestion(j) {
    var o = parsePayload(j)
    if (!o || o.action !== 'question') return
    var v = o.value
    if (!v || !groupMatch(v)) return

    var idx = findQuestionIndex(v.id)
    var row = {
      id: v.id,
      userId: v.userId,
      userName: v.userName,
      content: v.content,
      groupId: v.groupId,
      publish: !!v.publish,
      extra: v.extra
    }
    if (idx >= 0) {
      state.questions[idx] = Object.assign({}, state.questions[idx], row)
    } else {
      state.questions.push(row)
    }
    render()
  }

  function onAnswer(j) {
    var o = parsePayload(j)
    if (!o || o.action !== 'answer') return
    var v = o.value
    if (!v || !groupMatch(v)) return

    state.answers.push({
      questionId: v.questionId,
      userId: v.userId,
      userName: v.userName,
      content: v.content,
      isPrivate: v.isPrivate,
      questionUserId: v.questionUserId,
      groupId: v.groupId,
      extra: v.extra
    })
    render()
  }

  function onQaPublish(data) {
    var id = data && data.value && data.value.questionId
    if (!id) return
    if (state.publishedIds.indexOf(id) === -1) {
      state.publishedIds.push(id)
    }
    var idx = findQuestionIndex(id)
    if (idx >= 0) {
      state.questions[idx].publish = true
    }
    render()
  }

  function chain(name, handler) {
    var prev = DWLive[name]
    DWLive[name] = function () {
      var args = arguments
      if (typeof prev === 'function') {
        try {
          prev.apply(DWLive, args)
        } catch (e1) {}
      }
      try {
        handler.apply(null, args)
      } catch (e2) {
        console.warn('QAPanel.' + name, e2)
      }
    }
  }

  function switchTab(name) {
    var chatPanel = document.getElementById('panel-chat')
    var qaPanel = document.getElementById('panel-qa')
    var tabs = document.querySelectorAll('.assistant-tab[data-tab]')
    for (var ti = 0; ti < tabs.length; ti++) {
      var btn = tabs[ti]
      var on = btn.getAttribute('data-tab') === name
      if (on) {
        btn.classList.add('active')
      } else {
        btn.classList.remove('active')
      }
    }
    if (chatPanel) {
      if (name === 'chat') chatPanel.classList.add('is-active')
      else chatPanel.classList.remove('is-active')
    }
    if (qaPanel) {
      if (name === 'qa') qaPanel.classList.add('is-active')
      else qaPanel.classList.remove('is-active')
    }
    var noticePanel = document.getElementById('panel-notice')
    if (noticePanel) {
      if (name === 'notice') noticePanel.classList.add('is-active')
      else noticePanel.classList.remove('is-active')
    }
    var userPanel = document.getElementById('panel-user')
    if (userPanel) {
      if (name === 'user') userPanel.classList.add('is-active')
      else userPanel.classList.remove('is-active')
    }
  }

  function bindTabs() {
    var tabs = document.querySelectorAll('.assistant-tab[data-tab]')
    for (var i = 0; i < tabs.length; i++) {
      ;(function (btn) {
        btn.addEventListener('click', function () {
          switchTab(btn.getAttribute('data-tab'))
        })
      })(tabs[i])
    }
  }

  function bindToolbar() {
    var banQa = document.getElementById('qa-ban-qa')
    var banChat = document.getElementById('qa-ban-chat')
    if (banQa) {
      banQa.addEventListener('change', function () {
        if (typeof DWLive.silenceQa !== 'function' || typeof DWLive.unSilenceQa !== 'function') {
          return
        }
        if (banQa.checked) {
          DWLive.silenceQa()
        } else {
          DWLive.unSilenceQa()
        }
      })
    }
    if (banChat) {
      banChat.addEventListener('change', function () {
        if (typeof DWLive.silenceChat !== 'function' || typeof DWLive.unSilenceChat !== 'function') {
          return
        }
        if (banChat.checked) {
          DWLive.silenceChat()
        } else {
          DWLive.unSilenceChat()
        }
      })
    }
    var manage = document.getElementById('qa-goto-chat-manage')
    if (manage) {
      manage.addEventListener('click', function (e) {
        e.preventDefault()
        alert('演示页未接入聊天管理后台')
      })
    }
  }

  function install() {
    els.qaList = document.getElementById('qa-list')
    if (!els.qaList) return

    chain('onQuestion', onQuestion)
    chain('onAnswer', onAnswer)
    chain('onQaPublish', onQaPublish)

    bindListEvents()
    bindTabs()
    bindToolbar()
    switchTab('chat')
    render()
  }

  $(install)
})(window.jQuery)
