import Event from '../libs/event'
import util from '../libs/util'
import Source from '../source'
import getDefaultProperties from '../constants/default_properties'
import cloneDeep from 'lodash/cloneDeep'
import { convert2geojson } from 'admin-tools'

class EchartsLayer extends Event {
  constructor(layer, scene) {
    super()
    this.id = layer.id
    this.type = layer.type
    this.name = layer.name
    this.layer = layer
    this._scene = scene
    this.data = [] // 图层的数据源，包括属性数据和点位坐标
    this.myCharts = {} // {chartId: ChartInstance}  图表实例
    this.myMarkers = [] // marker实例
    this.setSource()
  }
  /**
   * 根据source选项值获取组件的数据，并监听source.load事件，触发视图更新
   */
  setSource() {
    this.off('source.load')
    let source = this.layer.source
    if (!source || Object.keys(source).length === 0) {
      return
    }
    this.sourceInstance = new Source(this.layer.id, source, this)
    this.once('source.load', ({ data }) => {
      let source = this.layer.source
      if (source.type === 'json') {
        this.data = this._reduceJsonData(data, source.parser)
      } else {
        this.data = this._reduceGeojsonData(data)
      }
      this.setStyle()
    })
  }

  _reduceJsonData(data, parser) {
    // 行政区划的点数据和线段数据需要由引擎进行空间化
    if (parser && parser.type === 'admin' && parser.dataType !== 'polygon') {
      data = convert2geojson(data, parser)
      return this._reduceGeojsonData(data)
    } else {
      let { x, y } = parser
      let result = []
      data.forEach(d => {
        let id = util.generateId()
        let coordinate = [d[x], d[y]]
        result.push({
          chartId: id,
          properties: d,
          coordinate
        })
      })
      return result
    }
  }

  _reduceGeojsonData(data) {
    let result = []
    data.features.forEach(d => {
      let id = util.generateId()
      let coordinate = d.geometry.coordinates
      result.push({
        chartId: id,
        properties: d.properties,
        coordinate
      })
    })
    return result
  }

  remove() {
    this.myMarkers.forEach(marker => {
      marker.remove()
    })
    this.myMarkers = []
    this.myCharts = []
  }

  show() {
    this.setStyle()
  }

  hide() {
    this.remove()
  }

  setIndex() {
    return
  }

  _mergeProperties() {
    let defaultProperties = getDefaultProperties(this.type)
    let { scale, shape, style, action } = this.layer
    let newProperties = util.mergeObjs(cloneDeep(defaultProperties), {
      scale: scale || {},
      shape: shape || {},
      style: style || {},
      action: action || {}
    })
    return newProperties
  }
}

export default EchartsLayer
