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

class Pie 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.width = style.size + 'px'
        element.style.height = style.size + '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 = style.size + 'px'
    el.style.height = style.size + '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 data = []
    style.dataItems.forEach(({ field, color }) => {
      data.push({
        value: properties[field],
        itemStyle: {
          color
        }
      })
    })
    return {
      series: [
        {
          type: 'pie',
          data,
          radius: style.type === 'ring' ? ['40%', '75%'] : [0, '75%'],
          roseType: style.type === 'rose',
          label: {
            show: style.showLabel,
            position: 'inside',
            formatter: '{c}',
            textStyle: {
              fontSize: style.labelSize,
              color: style.labelColor
            }
          },
          labelLine: {
            show: false
          }
        }
      ]
    }
  }
}

export default Pie
