/**
 * assistant.html 公告面板：对齐 live-web-operator _notice/index.vue
 * 依赖 hdChat：releaseAnnouncement / removeAnnouncement；事件 announcementShow、announcementUpdate
 */
;(function ($) {
  var state = {
    text: '',
    editing: false,
    draft: '',
    limit: 100,
    hdchat: null
  }

  function toDisplayHtml(raw) {
    var item = String(raw || '')
    item = item
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
    item = item.replace(/\n/g, '<br/>')
    item = item.replace(/&nbsp;/g, '&amp;nbsp;').replace(/&nbsp/g, '&amp;nbsp')
    return item
  }

  function toast(msg) {
    if (window.console && console.warn) console.warn('[公告]', msg)
    window.alert(msg)
  }

  function runAsync(p, onOk, onErr) {
    if (!p) {
      if (onErr) onErr('无返回')
      return
    }
    if (typeof p.then === 'function') {
      p.then(onOk).catch(function (e) {
        if (onErr) onErr(e)
      })
      return
    }
    if (typeof p.done === 'function') {
      p.done(onOk).fail(function (e) {
        if (onErr) onErr(e)
      })
    }
  }

  function getLimit() {
    var h = state.hdchat
    if (h && h.options && h.options.account && h.options.account.announceCharNum) {
      return Number(h.options.account.announceCharNum) || 100
    }
    return 100
  }

  function syncDraftFromText() {
    state.draft = state.text || ''
  }

  function render() {
    var editBtn = document.getElementById('notice-edit-btn')
    var editWrap = document.getElementById('notice-edit-wrap')
    var emptyEl = document.getElementById('notice-empty')
    var displayWrap = document.getElementById('notice-display-wrap')
    var displayBox = document.getElementById('notice-display')
    var ta = document.getElementById('notice-textarea')
    var countEl = document.getElementById('notice-char-count')
    var delBtn = document.getElementById('notice-delete')

    state.limit = getLimit()
    if (ta) ta.setAttribute('maxlength', String(state.limit))

    if (editBtn) {
      editBtn.style.display = state.editing ? 'none' : ''
      editBtn.textContent = state.text ? '编辑公告' : '发布公告'
    }

    if (editWrap) {
      editWrap.style.display = state.editing ? 'block' : 'none'
    }
    if (ta && state.editing) {
      ta.value = state.draft
    }

    var has = !!(state.text && String(state.text).trim())
    if (emptyEl) {
      emptyEl.style.display = !state.editing && !has ? 'flex' : 'none'
    }
    if (displayWrap) {
      displayWrap.style.display = !state.editing && has ? 'block' : 'none'
    }
    if (displayBox && has) {
      displayBox.innerHTML = toDisplayHtml(state.text)
    }
    if (delBtn) {
      delBtn.style.display = !state.editing && has ? 'block' : 'none'
    }

    var len = state.editing ? String((ta && ta.value) || state.draft || '').length : 0
    if (countEl) {
      countEl.textContent = len + '/' + state.limit
    }
  }

  function enterEdit() {
    if (!state.hdchat) {
      toast('请先登录并初始化聊天室（hdChat）后再操作公告')
      return
    }
    state.editing = true
    syncDraftFromText()
    render()
    var ta = document.getElementById('notice-textarea')
    if (ta) {
      try {
        ta.focus()
      } catch (e) {}
    }
  }

  function exitEdit(keepDraft) {
    state.editing = false
    if (!keepDraft) {
      state.draft = state.text || ''
    }
    render()
  }

  function publish() {
    var ta = document.getElementById('notice-textarea')
    var text = $.trim((ta && ta.value) || state.draft || '')
    if (!text) {
      toast('公告内容不能为空')
      return
    }
    if (!state.hdchat) {
      toast('hdChat 未就绪')
      return
    }
    var ret = state.hdchat.releaseAnnouncement(text)
    if (ret === false) {
      toast('发布失败：内容为空或超过字数限制（最多 ' + state.limit + ' 字）')
      return
    }
    runAsync(
      ret,
      function () {
        state.text = text
        state.draft = text
        state.editing = false
        render()
      },
      function (err) {
        toast((err && (err.message || err.msg || String(err))) || '发布失败，请重试')
      }
    )
  }

  function openDeleteModal() {
    var mask = document.getElementById('notice-delete-modal')
    if (mask) mask.classList.add('is-open')
  }

  function closeDeleteModal() {
    var mask = document.getElementById('notice-delete-modal')
    if (mask) mask.classList.remove('is-open')
  }

  function confirmDelete() {
    if (!state.hdchat) {
      closeDeleteModal()
      return
    }
    var ret = state.hdchat.removeAnnouncement()
    runAsync(
      ret,
      function () {
        closeDeleteModal()
        state.text = ''
        state.draft = ''
        render()
      },
      function (err) {
        closeDeleteModal()
        toast((err && (err.message || err.msg || String(err))) || '删除失败，请重试')
      }
    )
  }

  function onAnnouncementShow(str) {
    state.text = str != null ? String(str) : ''
    state.editing = false
    state.draft = state.text
    render()
  }

  function onAnnouncementUpdate(res) {
    if (!res) return
    if (res.action === 'remove') {
      state.text = ''
    } else if (res.action === 'release') {
      state.text = res.announcement != null ? String(res.announcement) : ''
    }
    state.editing = false
    state.draft = state.text
    render()
  }

  function bindUi() {
    var editBtn = document.getElementById('notice-edit-btn')
    if (editBtn) {
      editBtn.addEventListener('click', function () {
        enterEdit()
      })
    }
    var cancel = document.getElementById('notice-cancel-edit')
    if (cancel) {
      cancel.addEventListener('click', function () {
        exitEdit(false)
      })
    }
    var pub = document.getElementById('notice-publish')
    if (pub) {
      pub.addEventListener('click', function () {
        publish()
      })
    }
    var del = document.getElementById('notice-delete')
    if (del) {
      del.addEventListener('click', function () {
        openDeleteModal()
      })
    }
    var ta = document.getElementById('notice-textarea')
    if (ta) {
      ta.addEventListener('input', function () {
        state.draft = ta.value
        var countEl = document.getElementById('notice-char-count')
        if (countEl) {
          state.limit = getLimit()
          countEl.textContent = String(ta.value.length) + '/' + state.limit
        }
      })
    }

    var mClose = document.getElementById('notice-modal-close')
    var mCancel = document.getElementById('notice-modal-cancel')
    var mOk = document.getElementById('notice-modal-ok')
    var mask = document.getElementById('notice-delete-modal')
    if (mClose) mClose.addEventListener('click', closeDeleteModal)
    if (mCancel) mCancel.addEventListener('click', closeDeleteModal)
    if (mOk) mOk.addEventListener('click', confirmDelete)
    if (mask) {
      mask.addEventListener('click', function (e) {
        if (e.target === mask) closeDeleteModal()
      })
    }
  }

  window.DemoAnnouncementPanel_attachHdchat = function (hdchat) {
    if (!hdchat) return
    state.hdchat = hdchat
    state.limit = getLimit()
    if (!hdchat._demoAnnouncementPanelBound) {
      hdchat._demoAnnouncementPanelBound = true
      hdchat.on('announcementShow', onAnnouncementShow)
      hdchat.on('announcementUpdate', onAnnouncementUpdate)
    }
    if (hdchat.announceMentData != null && hdchat.announceMentData !== '') {
      state.text = String(hdchat.announceMentData)
      state.draft = state.text
    }
    state.editing = false
    render()
  }

  $(function () {
    if (!document.getElementById('panel-notice')) return
    bindUi()
    render()
  })
})(window.jQuery)
