<script>
import commonMixin from '../base/mixins/common.js'
import { convertObjToStyle } from '../base/SymbolUtil.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 GeoJSON from 'ol/format/GeoJSON'
import KML from 'ol/format/KML'
import VectorSource from 'ol/source/Vector'
import VectorLayer from 'ol/layer/Vector'
import {bbox as bboxStrategy} from 'ol/loadingstrategy'
export default {
  name: 'sl-layer',
  render (h) { },
  mixins: [commonMixin('layer')],
  props: {
    id: {
      type: String,
      require: true
    },
    name: {
      type: String,
      require: true
    },
    styleConfig: {
      type: [Object, Function],
      default: function () {
        return SymbolConfig['defaultVectorLayer']
      }
    },
    features: {
      type: Array,
      default: function () {
        return []
      }
    },
    visible: {
      type: Boolean,
      default: true
    },
    zIndex: {
      type: Number,
      require: true,
      default: 1
    },
    url:{
      type: String
    },
    format:{
      type: String,
      default: "geojson"
    }
  },
  watch: {
    features (val) {
      if (this.url) {
        return
      }
      this.originInstance.getSource().clear()
      this.addFeatures()
    },
    visible (val) {
      this.originInstance.setVisible(val)
    },
    zIndex(val) {
      this.originInstance.setZIndex(val)
    }
  },
  methods: {
    // 初始化图层-----
    load () {
      const { id, name, styleConfig, $rootComponent, zIndex, url, format } = this
      if ($rootComponent.isLayerExist(id)) {
           $rootComponent.removeLayer(id)
      }
      let featureFormat = new GeoJSON()
      let style = null
      if (styleConfig instanceof Function) {
        style = styleConfig
      } else {
        style = convertObjToStyle(styleConfig)
      }
      if (format === "kml") {
          featureFormat = new KML()
      }
      if (url) {
        let param =  {
              format: featureFormat,
              url: function(extent) {
                return url + '&bbox=' + extent.join(',') + ',EPSG:4326';
              },
              strategy: bboxStrategy
          }
        var source = new VectorSource(param)
        this.originInstance = new VectorLayer({
            source,
            id,
            name
         })
        this.originInstance.setZIndex(zIndex)
        this.originInstance.setStyle(style)
      } else {
        this.originInstance = new VectorLayer({
            source: new VectorSource({strategy: bboxStrategy}),
            id,
            name
          })  
        this.originInstance.setZIndex(zIndex)
        this.originInstance.setStyle(style)
        this.addFeatures()
      }
      this.map.addLayer(this.originInstance)   
    },
    // 图层添加要素
    addFeatures () {
      const { features} = this
        let vectors = []
        for (var index in features) {
          var feature = features[index]
          let { geom, symbol, attributes } = feature
          var geometry = covertObjToGeometry(geom)
          var vector = new Feature()
          vector.setGeometry(geometry)
          if (symbol) {
            var sty = convertObjToStyle(symbol)
            vector.setStyle(sty)
          } 
          if(attributes && attributes.id) {
             vector.set('attributes', attributes)
             vector.setId(attributes.id)
          } 
          vectors.push(vector)
        }
        this.originInstance.getSource().addFeatures(vectors)
    },
    // 通过id获取对象
    getFeatureById (id) {
      const source = this.originInstance.getSource()
      const feature = source.getFeatureById(id)
      return this.convertFeatureToObj(feature)
    },
    // 刷新图层（触发change事件）
    refresh () {
      const source = this.originInstance.getSource()
      source.refresh()
    },
    getFeaturesAtCoordinate(coordinate) {
      var vectors = this.originInstance.getSource().getFeaturesAtCoordinate(coordinate)
        let arr = []
        vectors.forEach((fea) =>{
           arr.push(this.convertFeatureToObj(fea))
        })
        return arr
      },
    getFeatures() {
        var vectors = this.originInstance.getSource().getFeatures()
        let arr = []
        vectors.forEach((fea) =>{
           arr.push(this.convertFeatureToObj(fea))
        })
        return arr
      },
    getFeaturesInExtent(extent) {
        var vectors = this.originInstance.getSource().getFeaturesInExtent(extent)
        let arr = []
        vectors.forEach((fea) =>{
           arr.push(this.convertFeatureToObj(fea))
        })
        return arr
      },
    hasFeature(feature) {
        return this.originInstance.getSource().hasFeature(feature)
      },
    removeFeature(){

     },
    getClosestFeatureToCoordinate(coordinate) {
      const fea= this.originInstance.getSource().getClosestFeatureToCoordinate(coordinate)
      return this.convertFeatureToObj(fea)
    },
    forEachFeatureIntersectingExtent(extent, callback) {
        this.originInstance.getSource().forEachFeatureIntersectingExtent(extent,(fea)=>{
            callback(this.convertFeatureToObj(fea))
         })
    },
    forEachFeatureInExtent(extent, callback) {
      this.originInstance.getSource().forEachFeatureInExtent(extent,(fea)=>{
            callback(this.convertFeatureToObj(fea))
         })
    },
      // 遍历图层中的所有的要素--------
    forEachFeature(callback) {
        this.originInstance.getSource().forEachFeature((fea)=>{
              callback(this.convertFeatureToObj(fea))
         })
     },
      // 将要素转化为对象----
    convertFeatureToObj(feature) {
          const type = feature.getGeometry().getType()
          var center = []
          var coods = []
          if (type === GeometryType.POINT) {
            center = feature.getGeometry().getCoordinates()
            coods = feature.getGeometry().getCoordinates()
          }
          if (type === GeometryType.POLYGON) {
            center = feature.getGeometry().getInteriorPoint().getCoordinates()
            coods = feature.getGeometry().getCoordinates()
          }
          if (type === GeometryType.MULTIPOLYGON) {
            const bounds = feature.getGeometry().getExtent()
            center = [(bounds[0] + bounds[2]) / 2, (bounds[1] + bounds[3]) / 2]
            const polygons = feature.getGeometry().getPolygons()
            for (let polygon of polygons.values()) {
              coods.push(polygon.getCoordinates())
            }
          }
          if (type === GeometryType.POLYLINE) {
            center = feature.getGeometry().getLastCoordinate()
            coods = feature.getGeometry().getCoordinates()
          }
         return  { feature, type, center, coods, attributes: feature.get('attributes') }
      }
  }
}
</script>
