/**
 * assistant.html — 抽奖 2.0 助教模块
 * 对齐 live-web-operator/src/pc/components/LuckyDraw 与 src/api/lottery.js
 * 接口走 assistantsdk：DWLive.hdLottery*
 */
;(function ($) {
  var USABLE_FALLBACK = 10000
  var searchTimer = null
  var drawCountTimer = null

  var state = {
    activeLotteryId: '',
    isHasStopLotter: false,
    isCloseLottery: false,
    startFlag: false,
    endFlag: false,
    searchUserList: [],
    virtualDraft: [],
    drawForm: {
      participatingUserType: 0,
      prize: { name: '' },
      winnerNum: '',
      isPreset: false,
      presetWinnerUsers: [],
      virtualWinners: [],
      isUserCollection: false,
      winningUsersCollectTemplates: [
        { title: '名称', tips: '请输入您的姓名' },
        { title: '手机号', tips: '请输入您的手机号' }
      ],
      lotteryType: 0
    }
  }

  var dwHooksBound = false

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

  /** 解析接口 JSON（兼容 { data: ... }） */
  function innerData(root) {
    if (root == null || typeof root !== 'object') return null
    return root.data !== undefined ? root.data : root
  }

  function chainDwLive(name, handler) {
    if (typeof DWLive === 'undefined') return
    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('DemoLottery.' + name, e2)
      }
    }
  }

  function openMask(id) {
    var m = document.getElementById(id)
    if (!m) return
    m.classList.add('is-open')
    m.setAttribute('aria-hidden', 'false')
  }
  function closeMask(id) {
    var m = document.getElementById(id)
    if (!m) return
    m.classList.remove('is-open')
    m.setAttribute('aria-hidden', 'true')
  }

  function setSwitch(el, on) {
    if (!el) return
    if (on) {
      el.classList.add('is-on')
      el.setAttribute('aria-checked', 'true')
    } else {
      el.classList.remove('is-on')
      el.setAttribute('aria-checked', 'false')
    }
  }

  function syncTplUi() {
    var nodes = document.querySelectorAll('[data-lottery-tpl]')
    for (var i = 0; i < nodes.length; i++) {
      var n = nodes[i]
      if (Number(n.getAttribute('data-lottery-tpl')) === state.drawForm.lotteryType) n.classList.add('is-active')
      else n.classList.remove('is-active')
    }
  }

  function syncPresetUi() {
    var on = state.drawForm.isPreset
    setSwitch(document.getElementById('lottery-preset-switch'), on)
    document.getElementById('lottery-open-virtual').style.display = on ? 'inline-flex' : 'none'
    document.getElementById('lottery-preset-search-row').style.display = on ? 'flex' : 'none'
    document.getElementById('lottery-preset-list-row').style.display = on ? 'flex' : 'none'
    renderPresetBox()
  }

  function syncCollectUi() {
    var on = state.drawForm.isUserCollection
    setSwitch(document.getElementById('lottery-collect-switch'), on)
    document.getElementById('lottery-collect-add').style.display = on ? 'inline-flex' : 'none'
    document.getElementById('lottery-collect-fields').style.display = on ? 'block' : 'none'
  }

  function renderPresetBox() {
    var box = document.getElementById('lottery-preset-userbox')
    var cnt = document.getElementById('lottery-preset-count')
    if (!box) return
    var pu = state.drawForm.presetWinnerUsers
    var vw = state.drawForm.virtualWinners
    var n = pu.length + vw.length
    if (!state.drawForm.isPreset || n === 0) {
      box.className = 'demo-lottery-userbox demo-lottery-userbox--empty'
      box.innerHTML = '<span aria-hidden="true">👤</span><span>暂无虚拟中奖用户</span>'
      if (cnt) {
        cnt.style.display = 'none'
        cnt.textContent = ''
      }
      return
    }
    box.className = 'demo-lottery-userbox'
    var html = '<ul class="demo-lottery-userlist">'
    var i
    for (i = 0; i < pu.length; i++) {
      var p = pu[i]
      html +=
        '<li data-pi="' +
        i +
        '"><span class="name">' +
        escapeHtml(p.userName) +
        '</span><span class="rm" data-rm-preset="' +
        i +
        '">移除</span></li>'
    }
    for (i = 0; i < vw.length; i++) {
      var v = vw[i]
      html +=
        '<li data-vi="' +
        i +
        '"><span class="name">' +
        escapeHtml(v.userName) +
        '</span><span class="tag">虚拟用户</span><span class="rm" data-rm-vir="' +
        i +
        '">移除</span></li>'
    }
    html += '</ul>'
    box.innerHTML = html
    if (cnt) {
      cnt.style.display = 'block'
      cnt.textContent = n + '人'
    }
  }

  function renderVirtualDraft() {
    var box = document.getElementById('lottery-virtual-preview')
    if (!box) return
    if (!state.virtualDraft.length) {
      box.className = 'demo-lottery-userbox demo-lottery-userbox--empty'
      box.innerHTML = '<span aria-hidden="true">👤</span><span>暂无虚拟中奖用户</span>'
      return
    }
    box.className = 'demo-lottery-userbox'
    var html = '<ul class="demo-lottery-userlist">'
    for (var i = 0; i < state.virtualDraft.length; i++) {
      var u = state.virtualDraft[i]
      var src = String(u.userAvatar || '').replace(/"/g, '')
      html +=
        '<li><img width="32" height="32" style="border-radius:50%;object-fit:cover;margin-right:8px" alt="" src="' +
        src +
        '"/><span class="name">' +
        escapeHtml(u.userName) +
        '</span><span class="rm" data-rm-draft="' +
        i +
        '">移除</span></li>'
    }
    html += '</ul>'
    box.innerHTML = html
  }

  function renderCollectCustom() {
    var wrap = document.getElementById('lottery-collect-custom')
    if (!wrap) return
    var arr = state.drawForm.winningUsersCollectTemplates
    var html = ''
    for (var i = 2; i < arr.length; i++) {
      var it = arr[i]
      html +=
        '<div class="demo-lottery-row" data-ci="' +
        i +
        '"><div class="demo-lottery-row__label">自定义</div><div class="demo-lottery-row__field" style="display:flex;gap:8px;align-items:center">' +
        '<input type="text" class="demo-lottery-input c-title" style="width:8rem" maxlength="4" placeholder="标题" value="' +
        escapeHtml(it.title) +
        '" />' +
        '<input type="text" class="demo-lottery-input c-tips" style="flex:1" maxlength="12" placeholder="提示文案" value="' +
        escapeHtml(it.tips) +
        '" />' +
        '<span class="rm" data-rm-custom="' +
        i +
        '" style="color:#f66275;cursor:pointer">✕</span></div></div>'
    }
    wrap.innerHTML = html
  }

  function showHint(msg) {
    var el = document.getElementById('lottery-hint-msg')
    if (el) el.textContent = msg || ''
    openMask('lottery-hint-mask')
  }

  function showConfirm(html, onOk, onCancel) {
    var el = document.getElementById('lottery-confirm-msg')
    if (el) el.innerHTML = html || ''
    var okBtn = document.getElementById('lottery-confirm-ok')
    var caBtn = document.getElementById('lottery-confirm-cancel')
    function clean() {
      okBtn.onclick = null
      caBtn.onclick = null
    }
    okBtn.onclick = function () {
      clean()
      closeMask('lottery-confirm-mask')
      onOk && onOk()
    }
    caBtn.onclick = function () {
      clean()
      closeMask('lottery-confirm-mask')
      onCancel && onCancel()
    }
    openMask('lottery-confirm-mask')
  }

  function clearDrawTimer() {
    if (drawCountTimer) {
      clearInterval(drawCountTimer)
      drawCountTimer = null
    }
    var btn = document.getElementById('lottery-drawing-stop')
    var n = document.getElementById('lottery-drawing-count')
    if (n) n.textContent = '3'
    if (btn) {
      btn.disabled = true
      btn.classList.add('demo-lottery-btn--gray')
    }
  }

  function startDrawCountdown() {
    clearDrawTimer()
    var btn = document.getElementById('lottery-drawing-stop')
    var n = document.getElementById('lottery-drawing-count')
    var ft = document.getElementById('lottery-drawing-ft')
    if (state.isHasStopLotter) {
      if (ft) ft.classList.remove('is-center')
      if (btn) btn.style.display = ''
    } else {
      if (ft) ft.classList.add('is-center')
      if (btn) btn.style.display = 'none'
    }
    var t = 3
    if (n) n.textContent = String(t)
    drawCountTimer = setInterval(function () {
      t--
      if (n) n.textContent = String(Math.max(0, t))
      if (t <= 0) {
        clearInterval(drawCountTimer)
        drawCountTimer = null
        if (btn && state.isHasStopLotter) {
          btn.disabled = false
          btn.classList.remove('demo-lottery-btn--gray')
        }
      }
    }, 1000)
  }

  function openDrawing() {
    openMask('lottery-drawing-mask')
    startDrawCountdown()
  }

  function drawingStop() {
    if (state.endFlag || !state.activeLotteryId) return
    if (typeof DWLive.hdLotteryStop !== 'function') return
    state.endFlag = true
    DWLive.hdLotteryStop({ lotteryId: state.activeLotteryId }, function (res) {
      state.endFlag = false
      if (typeof res === 'number') {
        window.alert('网络错误')
        return
      }
      if (res && res.success) {
        clearDrawTimer()
        closeMask('lottery-drawing-mask')
        showEnding(innerData(res) || {})
      } else {
        window.alert('停止失败')
      }
    })
  }

  function showEnding(awardInfo) {
    var title = document.getElementById('lottery-ending-title')
    var name = (awardInfo.prize && awardInfo.prize.name) || ''
    if (title) {
      title.innerHTML = '恭喜以下用户获得了<em>【' + escapeHtml(name) + '】</em>'
    }
    var tb = document.getElementById('lottery-ending-table')
    var users = awardInfo.winnerUsers || []
    var h = '<div class="th"><div class="c1">昵称</div><div class="c2">中奖码</div></div>'
    for (var i = 0; i < users.length; i++) {
      var u = users[i]
      h +=
        '<div class="tr"><div class="c1"><span class="name">' +
        escapeHtml(u.userName) +
        '</span>' +
        (Number(u.type) === 2 ? '<span class="tag">虚拟用户</span>' : '') +
        '</div><div class="c2">' +
        escapeHtml(u.prizeCode || '') +
        '</div></div>'
    }
    if (tb) tb.innerHTML = h
    openMask('lottery-ending-mask')
  }

  function fetchWinningRecords() {
    var err = document.getElementById('lottery-config-err')
    if (typeof DWLive.hdLotteryWinningInfo !== 'function') {
      if (err) err.textContent = 'SDK 缺少 hdLotteryWinningInfo'
      return
    }
    DWLive.hdLotteryWinningInfo(function (res) {
      if (typeof res === 'number') return
      if (res && res.success === false) return
      var inner = innerData(res) || res
      var info = inner.lotteryInfo || []
      if (!info || !info.length) {
        if (err) err.textContent = '本场直播暂无抽奖记录'
        return
      }
      var tip = document.getElementById('lottery-record-tip')
      if (tip) {
        tip.innerHTML =
          '<span class="dot"></span>本次直播共有' + info.length + '轮抽奖'
      }
      var body = document.getElementById('lottery-record-body')
      var html = ''
      for (var r = 0; r < info.length; r++) {
        var item = info[r]
        html += '<div class="demo-lottery-record-round"><div class="t">第' + (r + 1) + '轮</div>'
        html +=
          '<div>奖品名称：' +
          escapeHtml((item.prize && item.prize.name) || '') +
          '</div>'
        html += '<div style="margin:8px 0">中奖时间：' + escapeHtml(item.completeTime || '') + '</div>'
        html += '<div class="demo-lottery-record-table">'
        html += '<div class="th"><div class="c1">昵称</div><div class="c2">中奖码</div></div>'
        var ws = item.winnerUsers || []
        for (var j = 0; j < ws.length; j++) {
          var w = ws[j]
          html +=
            '<div class="tr"><div class="c1">' +
            escapeHtml(w.userName) +
            (Number(w.type) === 2 ? '<span class="tag">虚拟用户</span>' : '') +
            '</div><div class="c2">' +
            escapeHtml(w.prizeCode || '') +
            '</div></div>'
        }
        html += '</div></div>'
      }
      if (body) body.innerHTML = html
      window.__lotteryRecordCopy = info
      openMask('lottery-record-mask')
    })
  }

  function copyRecords() {
    var info = window.__lotteryRecordCopy
    if (!info || !info.length) return
    var str = '本次直播共有' + info.length + '轮抽奖\n\n'
    for (var i = 0; i < info.length; i++) {
      var item = info[i]
      str += '第' + (i + 1) + '轮\n奖品名称：' + (item.prize && item.prize.name) + '\n中奖时间：' + item.completeTime + '\n中奖用户列表  中奖码\n'
      var ws = item.winnerUsers || []
      for (var j = 0; j < ws.length; j++) {
        str += ws[j].userName + '  ' + ws[j].prizeCode + ' \n'
      }
      str += '\n'
    }
    var ta = document.createElement('textarea')
    ta.value = str
    document.body.appendChild(ta)
    ta.select()
    try {
      document.execCommand('copy')
      window.alert('复制成功')
    } catch (e) {
      window.alert('复制失败')
    }
    ta.remove()
  }

  function pollStatus() {
    if (typeof DWLive.hdLotteryStatus !== 'function') return
    DWLive.hdLotteryStatus(function (res) {
      if (typeof res === 'number') return
      var d = innerData(res) || res
      if (d && d.haveLottery) {
        state.activeLotteryId = d.lotteryId
        state.isHasStopLotter = false
        closeMask('lottery-config-mask')
        openDrawing()
      }
    })
  }

  function validateForm() {
    var err = document.getElementById('lottery-config-err')
    if (err) err.textContent = ''
    var name = (document.getElementById('lottery-prize-name') || {}).value || ''
    if (!name.trim()) {
      if (err) err.textContent = '请输入奖品名称'
      return false
    }
    var wn = (document.getElementById('lottery-winner-num') || {}).value || ''
    var count = parseInt(wn, 10)
    if (!wn || isNaN(count)) {
      if (err) err.textContent = '请输入中奖人数'
      return false
    }
    if (count > 200 || count < 1) {
      if (err) err.textContent = '中奖人数不超过200，最小为1'
      return false
    }
    var presetN = state.drawForm.presetWinnerUsers.length + state.drawForm.virtualWinners.length
    if (state.drawForm.isPreset && count < presetN) {
      if (err) err.textContent = '中奖人数不能少于预设中奖列表中的人数'
      return false
    }
    var usable = USABLE_FALLBACK
    if (
      (!state.drawForm.isPreset && count > usable) ||
      (state.drawForm.isPreset && count > presetN + usable)
    ) {
      if (err) err.textContent = '参与抽奖用户不足，无法发起抽奖'
      return false
    }
    if (state.drawForm.isPreset && presetN === 0) {
      if (err) err.textContent = '请添加预设中奖用户'
      return false
    }
    if (state.drawForm.isPreset && presetN > count) {
      if (err) err.textContent = '预设中奖人数不能超过设置的中奖人数'
      return false
    }
    if (state.drawForm.isUserCollection) {
      var arr = state.drawForm.winningUsersCollectTemplates
      var rows = document.querySelectorAll('#lottery-collect-custom .demo-lottery-row')
      for (var j = 0; j < rows.length; j++) {
        var row = rows[j]
        var t1 = row.querySelector('.c-title')
        var t2 = row.querySelector('.c-tips')
        var ix = Number(row.getAttribute('data-ci'))
        if (t1 && t2 && arr[ix]) {
          arr[ix].title = t1.value
          arr[ix].tips = t2.value
        }
      }
      var ok = true
      for (var i = 0; i < arr.length; i++) {
        if (arr[i].title === '' || arr[i].tips === '') {
          arr[i].error = '请输入中奖用户信息收集标题或提示文案'
          ok = false
        } else arr[i].error = ''
      }
      if (!ok) {
        if (err) err.textContent = '请完善中奖用户信息收集项'
        return false
      }
    }
    return true
  }

  function submitDraw() {
    if (state.startFlag) return
    if (!validateForm()) return
    if (typeof DWLive.hdLotteryCreate !== 'function') {
      window.alert('请更新 assistantsdk')
      return
    }
    state.startFlag = true
    var df = JSON.parse(JSON.stringify(state.drawForm))
    if (!df.isPreset) {
      df.presetWinnerUsers = []
      df.virtualWinners = []
    }
    if (!df.isUserCollection) {
      df.winningUsersCollectTemplates = []
    }
    df.winnerNum = Number(df.winnerNum)
    df.liveId = DWLive.liveId || DWLive.liveid || ''
    DWLive.hdLotteryCreate(df, function (res) {
      state.startFlag = false
      if (typeof res === 'number') {
        window.alert('网络错误')
        return
      }
      if (res && res.success) {
        var pack = innerData(res) || {}
        state.activeLotteryId = pack.lotteryId || ''
        state.isHasStopLotter = true
        closeMask('lottery-config-mask')
        openDrawing()
      } else {
        var err = document.getElementById('lottery-config-err')
        var code = res && res.error && res.error.code
        if (code === 20220000 && err) err.textContent = '未开启直播，发起抽奖失败'
        else if (code === 20220002 && err) err.textContent = '未中奖用户不足，无法发起抽奖'
        else if (err) err.textContent = '发起失败'
      }
    })
  }

  function cancelDrawApi() {
    if (!state.activeLotteryId) return
    DWLive.hdLotteryCancel({ lotteryId: state.activeLotteryId }, function (res) {
      if (typeof res === 'number') return
      if (res && res.success) {
        clearDrawTimer()
        closeMask('lottery-drawing-mask')
        showHint('本轮抽奖已取消')
      }
    })
  }

  function resetMainForm() {
    state.drawForm = {
      participatingUserType: 0,
      prize: { name: '' },
      winnerNum: '',
      isPreset: false,
      presetWinnerUsers: [],
      virtualWinners: [],
      isUserCollection: false,
      winningUsersCollectTemplates: [
        { title: '名称', tips: '请输入您的姓名' },
        { title: '手机号', tips: '请输入您的手机号' }
      ],
      lotteryType: 0
    }
    var pn = document.getElementById('lottery-prize-name')
    if (pn) pn.value = ''
    var len = document.getElementById('lottery-prize-len')
    if (len) len.textContent = '0'
    var part = document.getElementById('lottery-participate')
    if (part) part.value = '0'
    var wn = document.getElementById('lottery-winner-num')
    if (wn) wn.value = ''
    syncTplUi()
    syncPresetUi()
    syncCollectUi()
    renderCollectCustom()
    document.getElementById('lottery-preset-search').value = ''
    document.getElementById('lottery-preset-suggest').classList.remove('is-open')
    document.getElementById('lottery-preset-suggest').innerHTML = ''
    var e = document.getElementById('lottery-config-err')
    if (e) e.textContent = ''
  }

  function openMain() {
    resetMainForm()
    openMask('lottery-config-mask')
    pollStatus()
  }

  function onDwLotteryCreated(res) {
    if (res && res.lotteryId) {
      state.activeLotteryId = res.lotteryId
      state.isHasStopLotter = true
      closeMask('lottery-config-mask')
      openDrawing()
    }
  }
  function onDwLotteryCompleted() {
    if (document.getElementById('lottery-drawing-mask').classList.contains('is-open')) {
      drawingStop()
    }
  }
  function onDwLotteryCanceled() {
    clearDrawTimer()
    closeMask('lottery-drawing-mask')
    showHint('本轮抽奖已取消')
  }

  function bindDwHooks() {
    if (dwHooksBound) return
    if (typeof DWLive === 'undefined') return
    if (!document.getElementById('lottery-config-mask')) return
    dwHooksBound = true
    chainDwLive('onLotteryCreated', onDwLotteryCreated)
    chainDwLive('onLotteryCompleted', onDwLotteryCompleted)
    chainDwLive('onLotteryCanceled', onDwLotteryCanceled)
  }

  function bindUi() {
    document.addEventListener('click', function (e) {
      var t = e.target
      if (!t || !t.closest) return
      if (t.closest('[data-interact-tool="lottery"]')) {
        e.preventDefault()
        if (typeof DWLive === 'undefined' || !DWLive.userid) {
          window.alert('请先登录 DWLive')
          return
        }
        openMain()
      }
    })

    document.getElementById('lottery-config-close').addEventListener('click', function () {
      closeMask('lottery-config-mask')
    })
    document.getElementById('lottery-config-mask').addEventListener('click', function (e) {
      if (e.target.id === 'lottery-config-mask') closeMask('lottery-config-mask')
    })

    var dlg = document.querySelector('#lottery-config-mask .demo-lottery-dialog')
    if (dlg) {
      dlg.addEventListener('click', function (e) {
        e.stopPropagation()
      })
    }

    document.querySelectorAll('[data-lottery-tpl]').forEach(function (el) {
      el.addEventListener('click', function () {
        state.drawForm.lotteryType = Number(el.getAttribute('data-lottery-tpl'))
        syncTplUi()
      })
    })

    var pn = document.getElementById('lottery-prize-name')
    pn.addEventListener('input', function () {
      document.getElementById('lottery-prize-len').textContent = String(pn.value.length)
      state.drawForm.prize.name = pn.value
    })
    document.getElementById('lottery-participate').addEventListener('change', function () {
      state.drawForm.participatingUserType = Number(this.value)
    })
    document.getElementById('lottery-winner-num').addEventListener('input', function () {
      this.value = String(this.value).replace(/\D/g, '')
      state.drawForm.winnerNum = this.value
    })

    document.getElementById('lottery-preset-switch').addEventListener('click', function () {
      state.drawForm.isPreset = !state.drawForm.isPreset
      syncPresetUi()
    })
    document.getElementById('lottery-collect-switch').addEventListener('click', function () {
      state.drawForm.isUserCollection = !state.drawForm.isUserCollection
      syncCollectUi()
    })

    document.getElementById('lottery-open-virtual').addEventListener('click', function () {
      state.virtualDraft = []
      renderVirtualDraft()
      openMask('lottery-virtual-mask')
    })
    document.getElementById('lottery-virtual-close').addEventListener('click', function () {
      closeMask('lottery-virtual-mask')
    })
    document.getElementById('lottery-virtual-fetch').addEventListener('click', function () {
      var type = Number(document.querySelector('input[name="lottery-vtype"]:checked').value)
      var len = parseInt(document.getElementById('lottery-virtual-len').value, 10) || 0
      if (!len || len > 200) {
        window.alert('请输入 1～200 的虚拟用户数')
        return
      }
      DWLive.hdLotteryGetVirtualUsers({ type: type, length: len }, function (res) {
        if (typeof res === 'number') return
        var d = innerData(res) || res
        var users = (d && d.users) || (d.data && d.data.users) || []
        state.virtualDraft = state.virtualDraft.concat(users)
        renderVirtualDraft()
      })
    })
    document.getElementById('lottery-virtual-preview').addEventListener('click', function (e) {
      var rm = e.target.getAttribute && e.target.getAttribute('data-rm-draft')
      if (rm == null) return
      state.virtualDraft.splice(Number(rm), 1)
      renderVirtualDraft()
    })
    document.getElementById('lottery-virtual-ok').addEventListener('click', function () {
      state.drawForm.virtualWinners = state.drawForm.virtualWinners.concat(state.virtualDraft)
      closeMask('lottery-virtual-mask')
      renderPresetBox()
    })

    var ps = document.getElementById('lottery-preset-search')
    ps.addEventListener('input', function () {
      clearTimeout(searchTimer)
      var q = ps.value.trim()
      searchTimer = setTimeout(function () {
        if (!q) {
          document.getElementById('lottery-preset-suggest').classList.remove('is-open')
          return
        }
        DWLive.hdLotterySearchOnlineUsers(q, function (res) {
          if (typeof res === 'number') return
          var d = innerData(res) || res
          var list = (d && d.onlineUsers) || []
          var ul = document.getElementById('lottery-preset-suggest')
          ul.innerHTML = ''
          for (var i = 0; i < list.length; i++) {
            var li = document.createElement('li')
            li.textContent = list[i].userName
            li.setAttribute('data-uid', list[i].userId)
            li.setAttribute('data-uname', list[i].userName)
            ul.appendChild(li)
          }
          ul.classList.toggle('is-open', list.length > 0)
        })
      }, 350)
    })
    document.getElementById('lottery-preset-suggest').addEventListener('click', function (e) {
      var li = e.target.closest && e.target.closest('li[data-uid]')
      if (!li) return
      var uid = li.getAttribute('data-uid')
      if (state.drawForm.presetWinnerUsers.some(function (x) { return x.userId === uid })) return
      state.drawForm.presetWinnerUsers.push({
        userId: uid,
        userName: li.getAttribute('data-uname') || ''
      })
      document.getElementById('lottery-preset-search').value = ''
      document.getElementById('lottery-preset-suggest').classList.remove('is-open')
      renderPresetBox()
    })

    document.getElementById('lottery-preset-userbox').addEventListener('click', function (e) {
      var rp = e.target.getAttribute && e.target.getAttribute('data-rm-preset')
      var rv = e.target.getAttribute && e.target.getAttribute('data-rm-vir')
      if (rp != null) {
        state.drawForm.presetWinnerUsers.splice(Number(rp), 1)
        renderPresetBox()
      } else if (rv != null) {
        state.drawForm.virtualWinners.splice(Number(rv), 1)
        renderPresetBox()
      }
    })

    document.getElementById('lottery-collect-add').addEventListener('click', function () {
      if (state.drawForm.winningUsersCollectTemplates.length >= 5) {
        window.alert('最多添加三个自定义项')
        return
      }
      state.drawForm.winningUsersCollectTemplates.push({ title: '', tips: '', error: '' })
      renderCollectCustom()
    })
    document.getElementById('lottery-collect-custom').addEventListener('click', function (e) {
      var ix = e.target.getAttribute && e.target.getAttribute('data-rm-custom')
      if (ix == null) return
      state.drawForm.winningUsersCollectTemplates.splice(Number(ix), 1)
      renderCollectCustom()
    })

    document.getElementById('lottery-btn-records').addEventListener('click', fetchWinningRecords)
    document.getElementById('lottery-btn-start').addEventListener('click', submitDraw)

    document.getElementById('lottery-drawing-cancel').addEventListener('click', function () {
      state.isCloseLottery = false
      showConfirm('确定要取消本轮抽奖吗？', cancelDrawApi, function () {})
    })
    document.getElementById('lottery-drawing-xclose').addEventListener('click', function () {
      state.isCloseLottery = true
      showConfirm(
        '<span>您当前还未停止抽奖，确认要关闭弹框吗？</span><br/>关闭后抽奖不中断',
        function () {
          clearDrawTimer()
          closeMask('lottery-drawing-mask')
        },
        function () {}
      )
    })
    document.getElementById('lottery-drawing-stop').addEventListener('click', drawingStop)

    document.getElementById('lottery-hint-close').addEventListener('click', function () {
      closeMask('lottery-hint-mask')
    })
    document.getElementById('lottery-hint-ok').addEventListener('click', function () {
      closeMask('lottery-hint-mask')
    })

    document.getElementById('lottery-confirm-close').addEventListener('click', function () {
      closeMask('lottery-confirm-mask')
    })

    document.getElementById('lottery-ending-ok').addEventListener('click', function () {
      closeMask('lottery-ending-mask')
    })
    document.getElementById('lottery-ending-close').addEventListener('click', function () {
      closeMask('lottery-ending-mask')
    })

    document.getElementById('lottery-record-close').addEventListener('click', function () {
      closeMask('lottery-record-mask')
    })
    document.getElementById('lottery-record-copy').addEventListener('click', copyRecords)
  }

  function install() {
    if (!document.getElementById('lottery-config-mask')) return
    bindUi()
    bindDwHooks()
  }

  $(install)
})(window.jQuery)
