<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'
import turf_bbox  from '@turf/bbox-polygon'
import turf_linestring from 'turf-linestring'
import turf_polygon from 'turf-polygon'
import turf_point from 'turf-point'
import turf_boolean_contains from '@turf/boolean-contains'

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: 5
    }
  },
  watch: {
    features (val) {
      this.originInstance.getSource().clear()//不要清除图层，清除source源即可
      this.addFeatures()
    },
    visible (val) {
      this.originInstance.setVisible(val)
    },
    zIndex(val) {
      this.originInstance.setZIndex(val)
    }
  },
  methods: {
    // 初始化图层-----
    load () {
      const { id, name, styleConfig, $rootComponent, zIndex, visible} = 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', () => {
          this.originInstance.getSource().clear()
         // console.log("清除上一次视图范围内的所有点位")
          this.addFeatures()
      })
    },
    // 图层添加要素
    addFeatures () {
      const { features,  $rootComponent} = this
      let currentExtent =  $rootComponent.getCurrentExtent() // 获取地图的当前可视范围----
      let _extent = [currentExtent.minX, currentExtent.minY, currentExtent.maxX, currentExtent.maxY]
      let turf_poly = turf_bbox(_extent)
      let vectors = []
      for (var index in features) {
          let feature = features[index]
          let { geom, symbol, attributes } = feature
          let geometry = covertObjToGeometry(geom)
          let _coord = geometry.getCoordinates()
          let _type = geom.type
          let flag = false
          let turf_geom = null
          if(_type === 'Point') {
             turf_geom = turf_point(_coord)
          }
          if(_type === 'LineString') {
             turf_geom = turf_linestring(_coord)
          }
          if(_type === 'Polygon') {
             turf_geom = turf_polygon(_coord)
          }
          // if (turf_boolean_contains(turf_poly, turf_geom)) {
             let vector = new Feature()
             vector.setGeometry(geometry)
             let sty = null
             if(symbol) {
                if (symbol.image && symbol.image.icon) {
                    let {icon, radius = 5, color = '#007979' , fillColor = '#007979' , StrokeColor = '#fff', rotation = 0.0 } = symbol.image
                    sty = new Style({
                          image: new FontSymbol({
                              glyph: icon,
                              radius,
                              color,
                              fill: new Fill({
                                  color: fillColor
                              }),
                              stroke: new Stroke({
                                  color:StrokeColor,
                                  width: 1
                              })
                          })
                      })  
                  if (rotation) {
                     sty.getImage().setRotation(rotation)
                    }     
                } else {
                  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>
