<script>
import commonMixin from '../base/mixins/common.js'
import { GeometryType } from '../base/GeometryType.js'
import SymbolConfig from '../base/SymbolConfig.js'
import Draw, {createRegularPolygon, createBox} from 'ol/interaction/Draw'
import WKT from 'ol/format/WKT'
import Circle from 'ol/geom/Circle'
import  Feature  from 'ol/Feature'
import Modify from 'ol/interaction/Modify'
import { Vector as VectorLayer } from 'ol/layer'
import { Vector as VectorSource } from 'ol/source'
import { convertObjToStyle } from '../base/SymbolUtil.js'
import { fromCircle } from 'ol/geom/Polygon'
import turf_buffer from '@turf/buffer'
import turf_linestring from 'turf-linestring'
import turf_point from 'turf-point'
import turf_line_intersect from '@turf/line-intersect'
import { findSelfIntersections }from 'polygon-selfintersect'
import LineString from 'ol/geom/LineString'
// import {
//         clearSpatial
//     } from '../base/poiQuery'
import { Fill, Stroke, Style, Text, Icon, Circle as CircleStyle } from 'ol/style'
import {circular as circularPolygon, fromCircle as fromCirclePolygon} from 'ol/geom/Polygon.js'
import bus from '../eventBus.js'
export default {
  name: 'sl-drawModify',
  render () { },
  mixins: [commonMixin('interaction')],
  props: {
    type: {
      type: String,
      default: GeometryType.POINT
    },
    id: { type: String },
    name: { type: String },
    actived: {
      type: Boolean,
      default: false
    },
    poiMap:{
      type:Object
    },
    drawStyle: {
      type: Object,
      default: function () {
        return SymbolConfig['defaultDrawStyle']
      }
    }
  },
  data () {
    return {
    }
  },
  watch: {
    actived (flag) {//监控画图的状态，当变化时去
      this.originInstance.setActive(flag)
      //this.reload()
    },
    type (value) {
      this.reload()
    },
    drawStyle: {
        handler(newVal, oldVal){
           this.reload()     
        },
        deep: true
    }
  },
  methods: {
    load () {
      const { id, name, type, actived, map, $rootComponent, drawStyle } = this
      const wkt = new WKT()
      let geometryFunction
      let drawType = type
      if(drawType === GeometryType.SQUARE) {
        geometryFunction = createRegularPolygon(4)
        drawType = GeometryType.CIRCLE
      }
      if(drawType === GeometryType.BOX) {
        geometryFunction = createBox()
        drawType = GeometryType.CIRCLE
      }
      // 调用父组件方法添加图层=====
      // 添加无法拾取的标志----
      var drawLayer = $rootComponent.addLayer({ id, name })//添加图层
      drawLayer.getSource().on('addfeature', function(event) {
             event.feature.set('drawMark', true)
      })
      // 实例化绘制组件======
      this.originInstance = new Draw({
        source: drawLayer.getSource(), // 绘制层数据源
        type: drawType/** @type {ol.geom.GeometryType} */,
        style: convertObjToStyle(drawStyle),
        geometryFunction
      })
      var modify = new Modify({
            source: drawLayer.getSource()
      });
        //clearInteraction(map)
      map.addInteraction(modify);
      var _this = this;
       modify.on("modifyend",function (evt) {
          //_this.poiMap.removeInteraction(modify);
          const feature = evt.feature
          let geometry = evt.features.array_[0].getGeometry()
          let result;
          if(evt.features.array_[0].getGeometry().getType()=="Polygon"){
              result = wkt.writeGeometry(geometry)
              _this.$emit('editFinish', result)
          }else{
              result = wkt.writeGeometry(fromCircle(geometry))
              _this.$emit('editFinish', result)
          }
      });

      //drawLayer.getSource().clear()
      // 添加绘制交互组件----------------
      $rootComponent.addInteraction(this.originInstance, actived)
      // 添加绘制组件绘制完成后的回调函数----
      this.originInstance.on('drawend', (evt) => {
        // 清除上一次绘制的要素------
        //$rootComponent.addInteraction(this.originInstance, false)
        drawLayer.getSource().clear()
        const feature = evt.feature
        let geometry = feature.getGeometry()
        const type = geometry.getType()
        let result = {}
        if (type === GeometryType.CIRCLE) {//画圆
          let radius = evt.feature.values_.geometry.getRadius()*100000;
          let lon = evt.feature.values_.geometry.getCenter()[0];
          let lat = evt.feature.values_.geometry.getCenter()[1];
          if(radius>1000){
            this.drawCircle1000([lon,lat],1000)
            //$rootComponent.removeInteraction(this.originInstance, false)
            this.originInstance.setActive(false)
           // map.removeInteraction(this.originInstance)
            //this.poiMap.removeInteraction()
            drawLayer.getSource().clear()
            return false;
          }else{
            geometry = fromCircle(geometry)
          }
        } 
        if (type === GeometryType.POINT) {//点
           let point = turf_point(geometry.getCoordinates())
           result.buffer = turf_buffer(point, 0.2).geometry.coordinates.join(",")
        } 
        if (type === GeometryType.POLYLINE) {//线
           let intersects = this.isLineSelfIntersects(geometry.getCoordinates())
           if(intersects) {
               result.isSelfInteraction = true 
           } else {
               let line = turf_linestring(geometry.getCoordinates())
               result.buffer = turf_buffer(line, 0.2).geometry.coordinates.join(",")
               result.isSelfInteraction = false            
           }   
        }
        if (type === GeometryType.POLYGON) {//多边形
           let intersects = this.isPolygonSelfIntersects(geometry.getCoordinates()[0])
           result.isSelfInteraction = false 
           if(intersects) {
              result.isSelfInteraction = true 
           } 
        } 
        if(!result.isSelfInteraction) {
           result.wkt = wkt.writeGeometry(geometry)
        }
        result.coods = geometry.getCoordinates()
        result.type = type
        result.feature = feature
        result.extent = geometry.getExtent()
        this.$emit('drawend', result)
        //this.clearSpatial("nearbySearch",this.poiMap)
      })
    },
    drawCircle1000(center,radius,map){
      // this.clearSpatial("temp",this.poiMap)
      // this.clearSpatial("nearbySearch",this.poiMap)
      // this.originInstance.setActive(false)
      //this.type = GeometryType.Circle
      this.$emit('circleType', "Circle")
      this.$emit('circleDraw', true)
      if(radius!=undefined && radius!=''){
            let circle = new Circle(center,radius/100000)
            let feature = new Feature({
                    position:center,
                    radius:radius/100000,
                    type: 'circle',
                    id: 'N',
                    geometry:fromCirclePolygon(circle)
            })
            let vectorSource = new VectorSource({ 
                features:[feature],
                projection:'EPSG:4326'
            })
            let vectorLayer = new VectorLayer({
                id:'nearbySearch',
                source: vectorSource,
                style: new Style({
                    stroke: new Stroke({
                        color: '#ff3100',
                        width: 1
                    }),
                    fill: new Fill({
                        color: 'rgba(0, 0, 255, 0.1)'
                    })
                })
            })
            this.poiMap.addLayer(vectorLayer)
            let geometry = feature.getGeometry()//获取圆转为多边形后的范围
            let wkt = new WKT
            let wktgeometry = wkt.writeGeometry(geometry)
            this.$emit('drawend1000', "半径"+wktgeometry)
          }
    },
    finishDrawing() {
      this.originInstance.finishDrawing()
    },
    getOverlay () {
      return this.originInstance.getOverlay()
    },
    removeLastPoint () {
      his.originInstance.removeLastPoint()
    },
    clearDrawingFeatures () {
      this.originInstance.getOverlay().getSource().clear()
    },
    isLineSelfIntersects(coods) {
      var isInterset = false
      var paths = []
      for (let i = 0; i < coods.length-1; i++) {
          paths.push(new LineString([coods[i], coods[i+1]]))
      }
      let x_path = []
      let y_path = []
      for (let i = 0; i < coods.length; i++) {
          x_path.push(coods[i][0])
          y_path.push(coods[i][1])
      }
      let count_x = 0
      let count_y = 0
      if(x_path[x_path.length-1] < x_path[0]) {
        x_path.reverse()
      }
      if(y_path[y_path.length-1] < y_path[0]) {
        y_path.reverse()
      }
      for (let i = 0; i < x_path.length-1; i++) {
        if(x_path[i+1] > x_path[i]){
          count_x++
        }
      }
      for (let i = 0; i < y_path.length-1; i++) {
        if(y_path[i+1] > y_path[i]){
          count_y++
        } 
      }
      if(count_y === coods.length-1 || count_x === coods.length-1) {
            isInterset = false
      } else {
          for (var j = 0; j < paths.length; j++) {
            for (var k = paths.length-1; k >=0; k--) {
              if(Math.abs(k-j)>1) {          
                 if(paths[j].intersectsExtent(paths[k].getExtent())) {
                     isInterset = true
                     break
                 }   
              }
            }
            if(isInterset) {
                break
            }
        }
      }
      return  isInterset
    },
    isPolygonSelfIntersects(points) {
      return findSelfIntersections(points)
    }
  }
}
</script>
