<script>
import commonMixin from '../base/mixins/common.js'
import Modify from 'ol/interaction/Modify'
import Collection from 'ol/Collection'
import { convertObjToStyle } from '../base/SymbolUtil.js'
import SymbolConfig from '../base/SymbolConfig.js'
export default {
  name: 'sl-edit',
  render (h) { },
  mixins: [commonMixin('interaction')],
  props: {
    actived: {
      type: Boolean,
      default: false
    },
    features: {
      type: Array,
      required:true
    },
    layerId: {
      type: String,
    },
    editStyle:{
      type: Object,
      default: function () {
        return SymbolConfig['defaultEditStyle']
      }
    }
  },
  watch: {
    actived (flag) {
      if (this.originInstance) {
       this.originInstance.setActive(flag)
      }
    },
    features (val) {
      if (val && val.length>0) {
        this.reload()
      }
    }
  },
  methods: {
    load () {
      if(features && features.length===0){
        return 
      }
      const { $rootComponent, actived, features, layerId, editStyle } = this
      let modify
      if ( features ) {
         modify = new Modify({
          features: new Collection(features),
          style: convertObjToStyle(editStyle)
        })
      }
      if ( layerId ) {
        if( $rootComponent.getLayer(layerId) ) {
          modify = new Modify({
            source: $rootComponent.getLayer(layerId).getSource(),
            style: convertObjToStyle(editStyle)
           })
        }
      }
      this.originInstance = modify
      $rootComponent.addInteraction(modify, actived)
      modify.on('modifyend', (e) => {
        var vector = e.features.item(0)
        const coods = vector.getGeometry().getCoordinates()
        this.$emit('modifyend', coods)
      })
      modify.on('modifystart', (e) => {
        var vector = e.features.item(0)
        const coods = vector.getGeometry().getCoordinates()
        this.$emit('modifystart', coods)
      })
    },
    // 获取编辑所在的临时图层------
    getOverlay () {
      return this.originInstance.getOverlay()
    },
    // 删除正在编辑的节点
    removePoint () {
      this.originInstance.removePoint()
    },
    clearEditingFeatures () {
      this.originInstance.getOverlay().getSource().clear()
    }
  }
}
</script>
