import EchartsLayer from './echarts_layer'
import echarts from 'echarts/lib/echarts'
import { Marker } from '@cgcs2000/l7'
require('echarts/lib/chart/bar')

class Bar extends EchartsLayer {
  constructor(layer, scene) {
    super(layer, scene)
  }

  setStyle() {
    if (!this.layer.visible) {
      return
    }
    let { style } = this._mergeProperties()
    this.data.forEach(d => {
      let chartId = d.chartId
      if (this.myCharts[chartId]) {
        // 已经绘上去了
        let option = this._getOption(style, d.properties)
        this.myCharts[chartId].setOption(option, true)
        let marker = this.myMarkers.find(m => m.id === chartId)
        let element = marker.getElement()
        element.style.height = style.height + 'px'
        this.myCharts[chartId].resize()
        marker.markerOption.offsets = style.offset
        marker.updatePosition()
      } else {
        // 没有绘上去，需要构造marker并添加到地图上
        let marker = this._getMarker(style, d)
        this.myMarkers.push(marker)
        this._scene.addMarker(marker)
      }
    })
  }

  _getMarker(style, { chartId, properties, coordinate }) {
    let el = document.createElement('div')
    el.style.width = '100px'
    el.style.height = style.height + 'px'
    let option = this._getOption(style, properties)
    let myChart = echarts.init(el)
    myChart.setOption(option)
    this.myCharts[chartId] = myChart
    let marker = new Marker({
      element: el,
      offsets: style.offset
    }).setLnglat({
      lng: coordinate[0],
      lat: coordinate[1]
    })
    marker.id = chartId
    return marker
  }

  _getOption(style, properties) {
    let option = {
      grid: {
        top: '20',
        bottom: '0',
        left: '0',
        right: '0'
      },
      xAxis: {
        type: 'category',
        show: false,
        data: ['']
      },
      yAxis: {
        type: 'value',
        show: false
      },
      series: []
    }
    style.dataItems.forEach(({ field, color }) => {
      option.series.push({
        type: 'bar',
        data: [properties[field]],
        barWidth: style.barWidth,
        barGap: style.barGap,
        itemStyle: {
          color
        },
        label: {
          show: style.showLabel,
          position: 'top',
          textStyle: {
            fontSize: style.labelSize,
            color: style.labelColor
          }
        }
      })
    })
    return option
  }
}

export default Bar
