<script>
import commonMixin from '../base/mixins/common.js'
import { GeometryType } from '../base/GeometryType.js'
import SymbolConfig from '../base/SymbolConfig.js'
import { covertObjToGeometry } from '../base/GeometryUtil.js'
import  Feature  from 'ol/Feature'
import VectorSource from 'ol/source/Vector'
import VectorLayer from 'ol/layer/Vector'
import Cluster from 'ol/source/Cluster'
import {Circle as CircleStyle, Fill, RegularShape, Stroke, Style, Text, Icon, AtlasManager} from 'ol/style'
import {createEmpty, getWidth, getHeight, extend, containsCoordinate} from 'ol/extent'
import  turf_square_grid from '@turf/square-grid'
export default {
  name: 'sl-clusterlayer',
  render (h) { },
  mixins: [commonMixin('layer')],
  props: {
    id: {
      type: String,
      require: true
    },
    name: {
      type: String,
      require: true
    },
    features: {
      type: Array,
      default: function () {
        return []
      }
    },
    visible: {
      type: Boolean,
      default: true
    },
    zIndex: {
      type: Number,
      require: true,
      default: 6
    },
    clusterDistance: {
      type: Number,
      default: 20
    }
  },
  watch: {
    features (val) {
      this.originInstance.getSource().getSource().clear()
      this.addFeatures()
    },
    visible (val) {
      this.originInstance.setVisible(val)
    },
    zIndex(val) {
      this.originInstance.setZIndex(val)
    }
  },
  methods: {
    // 初始化图层-----
    load () {
      const { id, name, $rootComponent,  clusterDistance, zIndex, visible } = this
      if($rootComponent.isLayerExist(id)){
         $rootComponent.removeLayer(id)
      }
      let style = this.styleFunction
      this.originInstance = new VectorLayer({
            source: new Cluster({
              source: new VectorSource(),
              distance: clusterDistance
            }),
            id,
            name,
            style
        })
      this.addFeatures()
      this.originInstance.setZIndex(zIndex)
      this.originInstance.setVisible(visible)
      this.map.addLayer(this.originInstance) 
      $rootComponent.$on('zoom', () => {
          // this.originInstance.getSource().getSource().clear()
          // this.addFeatures()
      })
    },
    // 图层添加要素
    addFeatures () {
      const { features, $rootComponent} = this
      let vectors = []
      let currentExtent =  $rootComponent.getCurrentExtent() // 获取地图的当前可视范围----
      let _extent = [currentExtent.minX, currentExtent.minY, currentExtent.maxX, currentExtent.maxY]
      for (var index in features) {
          var feature = features[index]
          let { geom, attributes, symbol } = feature
          var geometry = covertObjToGeometry(geom)
          let _coord = geometry.getCoordinates()
          // if (containsCoordinate(_extent, _coord)) {
            var vector = new Feature()
            vector.setGeometry(geometry)
            if (attributes) {
              vector.set('attributes', attributes)
            }
            if (attributes && attributes.id) {
              vector.setId(attributes.id)
            }    
            if (symbol) {
              vector.set('symbol', symbol)
            } else {
              vector.set('symbol', {})
            }
            vectors.push(vector)
           }
        // }
        this.originInstance.getSource().getSource().addFeatures(vectors)
    },
    // 刷新图层（触发change事件）
    refresh () {
      const source = this.originInstance.getSource()
      source.refresh()
    },
    styleFunction(feature, resolution) {
      let atlasManager = new AtlasManager({
        initialSize: 30
       })
        var textFill = new Fill({
          color: '#fff'
        })
        var textStroke = new Stroke({
          color: 'rgba(0, 0, 0, 0.6)',
          width: 3
        })
        var style = null
        var size = feature.get('features').length
        style = new Style({
            image: new Icon({
                src: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADQAAAAfCAYAAACoE+4eAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyFpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDE0IDc5LjE1MTQ4MSwgMjAxMy8wMy8xMy0xMjowOToxNSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6OTFGNjYwREY2RkU5MTFFOUE5MTJFRkI2RTg4OUM3OTgiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6OTFGNjYwREU2RkU5MTFFOUE5MTJFRkI2RTg4OUM3OTgiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIChXaW5kb3dzKSI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOjFEMjBDOEE5NkZFNDExRTlCMjVEQkIxRUIzNkQ2NjQ5IiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjFEMjBDOEFBNkZFNDExRTlCMjVEQkIxRUIzNkQ2NjQ5Ii8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+t/X3ZwAAAN1JREFUeNpi/P//P8NwAkwMwwywgAjliS88gdRcIJYcov54DsTJd/MltsNiaCh7hgHq9rnISU5yGKQ2yWGZh0Y9NOqhUQ+NemjUQ6MeGvXQqIdGPTTqoVEPjXpo1EPDzEPPh4FfXiB7KAUmMETBUyBOBjEYKR1oVJ6INRzMgfgIA3SYDAv4BcSWQHyOUp/czZegSx46CcSNeORrqOEZehcK7UB8GIv4XiDuGYql3F8gjgXiD0hib4E4Doj/D0UPgcBDIM5A4oMy7jNaWshChxJoJRDbQQuCjbS2DCDAAKRJJxspr2RvAAAAAElFTkSuQmCC'
            }),
            text: new Text({
              text: size.toString(),
              fill: textFill,
              font: 'normal 14px 微软雅黑',
              offsetY:-3
              // stroke: textStroke
            }),
            atlasManager: atlasManager
          })
        return style
      }
}
}
</script>
