import Dom from '../../libs/dom'
import Widget from '../widget'
import util from '../../libs/util'

class Select extends Widget {
  constructor(layer, screen) {
    super(layer, screen)
    this.events = ['selectEvent'] // 事件
    this.showDropDown = false
    this._contanier = Dom.createElement('div', 'select-container comp', this.el)
  }

  setPaint() {
    this.setListener()
    let newPaint = this._mergePaint()
    this._contanier.innerHTML = ''
    let data = newPaint.data || []
    this.selectBox = Dom.createElement('div', 'select', this._contanier)
    this.selectBox.onclick = this._clickSelect.bind(this)
    if (this.layer.events) {
      this.selectBox.textContent = data.length ? data[0].name : ''
    }
    if (Array.isArray(newPaint.backgroundColor)) {
      newPaint.backgroundColor = util.gradient(
        'css',
        newPaint.gradientDirection,
        ...newPaint.backgroundColor
      )
    }
    Dom.css(this.selectBox, {
      color: newPaint.fontColor,
      fontSize: newPaint.fontSize + 'px',
      background: newPaint.backgroundColor,
      borderColor: newPaint.borderColor,
      borderRadius: newPaint.borderRadius + 'px'
    })
    this.dropdownBox = Dom.createElement('div', 'dropdown', this._contanier)
    data.forEach(d => {
      let { name, value } = d
      let option = Dom.createElement('div', 'option', this.dropdownBox)
      option.textContent = name
      option.value = value
      option.onclick = this._clickOption.bind(this)
    })
    Dom.css(this.dropdownBox, {
      color: newPaint.fontColor,
      fontSize: newPaint.fontSize + 'px',
      backgroundColor: newPaint.optionColor,
      display: this.showDropDown ? 'block' : 'none'
    })
    document.addEventListener(
      'click',
      e => {
        if (e.target === this.el || this.el.contains(e.target)) {
          return
        }
        this.showDropDown = false
        Dom.removeClass(this.selectBox, 'open')
        Dom.css(this.dropdownBox, {
          display: 'none'
        })
      },
      false
    )
    this.fire('render', this)
  }

  _clickSelect(e) {
    // 点击下拉框，显示选项列表
    this.showDropDown = !this.showDropDown
    if (this.showDropDown) {
      Dom.addClass(this.selectBox, 'open')
    } else {
      Dom.removeClass(this.selectBox, 'open')
    }
    Dom.css(this.dropdownBox, {
      display: this.showDropDown ? 'block' : 'none'
    })
  }

  _clickOption(e) {
    let value = e.target.value
    let name = e.target.textContent
    this.selectBox.textContent = name
    let events = this.layer.events // 绑定的事件
    this.events.forEach(eventName => {
      let alias =
        events && events[eventName] ? events[eventName].alias : eventName
      this._screen.store.patchState(alias, value)
    })
    this.showDropDown = false
    Dom.removeClass(this.selectBox, 'open')
    Dom.css(this.dropdownBox, {
      display: 'none'
    })
  }
}

export default Select
