<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 VectorSource from 'ol/source/Vector'
import VectorLayer from 'ol/layer/Vector'
import FontSymbol from '../style/FontSymbol'
import Style from 'ol/style/Style'
import Fill from 'ol/style/Fill'
import Stroke from 'ol/style/Stroke'
import { containsCoordinate } from 'ol/extent'
export default {
  name: 'sl-layer',
  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: 1
    },
    isOnlyVisibleCurExtent: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    features (val) {
      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, visible, isOnlyVisibleCurExtent } = this
      if ($rootComponent.isLayerExist(id)) {
           $rootComponent.removeLayer(id)
      }
      this.originInstance = new VectorLayer({
        source: new VectorSource(),
        id,
        name
      })  
      this.originInstance.setZIndex(zIndex)
      this.addFeatures()
      this.originInstance.setVisible(visible)
      this.map.addLayer(this.originInstance)
      $rootComponent.$on('zoom', () => {
         if( isOnlyVisibleCurExtent ) {
           this.originInstance.getSource().clear()
           console.log("清除上一次视图范围内的所有点位")
           this.addFeatures()
         }        
      })
    },
    // 图层添加要素
    addFeatures () {
      const { features,  $rootComponent, isOnlyVisibleCurExtent} = this
      let currentExtent =  $rootComponent.getCurrentExtent() // 获取地图的当前可视范围----
      let _extent = [currentExtent.minX, currentExtent.minY, currentExtent.maxX, currentExtent.maxY]
      let vectors = []
      let vector = null
      let sty = null
      for (var index in features) {
          let feature = features[index]
          let { geom, symbol, attributes } = feature
          if(symbol) {
              if (symbol.image && symbol.image.icon) {
                  let {icon, radius = 5, color = '#007979' , fillColor = '#007979' , StrokeColor = '#fff' } = symbol.image
                  sty = new Style({
                        image: new FontSymbol({
                            glyph: icon,
                            radius,
                            color,
                            fill: new Fill({
                                color: fillColor
                            }),
                            stroke: new Stroke({
                                color:StrokeColor,
                                width: 1
                            })
                        })
                    })       
              } else {
                sty = convertObjToStyle(symbol)
              }
          }
          let geometry = covertObjToGeometry(geom)
          let _coord = geometry.getCoordinates()
          if (isOnlyVisibleCurExtent) {
              if (containsCoordinate(_extent, _coord)) {
                  vector = new Feature()
                  vector.setGeometry(geometry)
              }
          } else {
              vector = new Feature()
              vector.setGeometry(geometry)
          }   
          if(attributes && attributes.id && vector) {
              vector.set('attributes', attributes)
              vector.setId(attributes.id)
          } 
          if(sty && vector) {
              vector.setStyle(sty)
          }
          vectors.push(vector)     
        }
        console.log('当前视图范围内点的数量:'+ vectors.length)
        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>
