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

class Tab extends Widget {
  constructor(layer, screen) {
    super(layer, screen)
    this._container = Dom.createElement('div', 'tab-container comp', this.el)
    this.on('resize', () => {
      this.resize()
    })
    this.activeTab = 0
  }

  setPaint() {
    this.setListener()
    this._container.innerHTML = ''
    let newPaint = this._mergePaint()
    Dom.css(this._container, {
      fontSize: newPaint.style.fontSize + 'px',
      border: `1px solid ${newPaint.style.borderColor}`
    })
    var data = newPaint.tabs
    for (let i = 0; i < data.length; i++) {
      var tabItem
      if (i === newPaint.defaultTab) {
        tabItem = Dom.createElement('div', 'tab-item active', this._container)
      } else {
        tabItem = Dom.createElement('div', 'tab-item', this._container)
      }
      Dom.css(tabItem, {
        display: 'inline-block',
        width: 100 / data.length + '%',
        lineHeight: this.el.style.height
      })
      tabItem.innerText = data[i].label
      tabItem.onclick = e => {
        let tabName = e.target.innerText
        let tabs = this._container.getElementsByClassName('tab-item')
        for (let j = 0; j < tabs.length; j++) {
          Dom.removeClass(tabs[j], 'active')
        }
        Dom.addClass(e.target, 'active')
        this.tabAction(data, tabName)
        this.updateStyle(newPaint.style)
        this.fire('tabChange', { name: tabName })
      }
    }
    this.tabAction(data, data[newPaint.defaultTab].label)
    this.updateStyle(newPaint.style)
  }

  tabAction(data, tabName) {
    for (let j = 0; j < data.length; j++) {
      let tab = data[j]
      let components = tab.charts || []
      if (tab.label === tabName) {
        this.activeTab = j
        components.forEach(componentId => {
          this._screen.setLayoutProperty(componentId, 'visible', true)
        })
      } else {
        components.forEach(componentId => {
          this._screen.setLayoutProperty(componentId, 'visible', false)
        })
      }
    }
  }

  resize() {
    let tabs = this._container.getElementsByClassName('tab-item')
    for (let i = 0; i < tabs.length; i++) {
      Dom.css(tabs[i], {
        lineHeight: this.el.style.height
      })
    }
  }

  updateStyle(style) {
    let tabItems = this._container.querySelectorAll('.tab-item')
    let activeTabItem = this._container.querySelector('.tab-item.active')
    for (let i = 0; i < tabItems.length; i++) {
      Dom.css(tabItems[i], {
        color: style.fontColor,
        backgroundColor: 'transparent'
      })
    }
    Dom.css(activeTabItem, {
      color: style.activeFontColor,
      backgroundColor: style.activeBackground
    })
  }

  getActiveTab() {
    return this.activeTab
  }
}

export default Tab
