<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 { Select,Translate } from 'ol/interaction'
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'
// const WKTF = require('terraformer-wkt-parser');
export default {
  name: 'sl-drawModify',
  render () { },
  mixins: [commonMixin('interaction')],
  //从这块获取到 this.map = $parent.olmap;this.$rootComponent为父组件
  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) {//监控画图的状态，当变化时去
      if(this.originInstance==undefined) return;
      this.originInstance.setActive(flag)
      // this.reload()
    },
    type (value) {
      this.reload()
    },
    drawStyle: {
        handler(newVal, oldVal){
           this.reload()     
        },
        deep: true
    }
  },
  methods: {
    load () {
      if(this.map==undefined){
          this.map = this.$map;
      }
      if(this.$rootComponent==undefined){
        this.$rootComponent = this.$parent.$parent.$parent;
      }
      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)
          event.feature.set('id', true)
      })
      map.removeInteraction(this.originInstance);//首先移除原来的Draw实例
      // 实例化绘制组件======
      this.originInstance = new Draw({
          id:this.id,
          source: drawLayer.getSource(), // 绘制层数据源
          type: drawType/** @type {ol.geom.GeometryType} */,
          style: convertObjToStyle(drawStyle),
          geometryFunction
      })
      // this.modify = new Modify({//这样定义的话,每次只能改最后画的那个几何体，如果以var定义的话，相当于地图中要添加很多的modify实例，可以修改多个几何体
      //       source: drawLayer.getSource()
      // });
      var modify = new Modify({
            id:this.id,
            source: drawLayer.getSource()
      })
      if(this.id.indexOf('freeHand')>-1){

      }else{
        map.addInteraction(modify);
      }
      //添加选择和移动
      // var select = new Select({
      //        id:id,
      //        layers:[drawLayer],
      //     });
      // map.addInteraction(select);
      // select.on("select", (evt)=> {
      //     this.map
      //     if (evt.selected[0] == null) return;
      //     //取消选中要素高亮
      //     // select.getFeatures().clear();
      //     //设置选中颜色
      //     // let style = new  Style({
      //     //     fill: new Fill({
      //     //       color: 'rgba(255, 255, 255, 0.2)' // 填充颜色
      //     //     }),
      //     //     stroke: new Stroke({
      //     //       color: '#ffcc33', // 边框颜色
      //     //       width: 2 // 边框宽度
      //     //     })
      //     //   })
      //     // select.getFeatures().array_[0].setStyle(style)
      // });
      var _this = this;
      modify.on("modifyend",function (evt) {
        const feature = evt.feature
        let geometry = evt.features.array_[0].getGeometry()
        let result;
        if(evt.features.array_[0].getGeometry().getType()=="Circle"){
               let radius = geometry.getRadius()*100000
              if(radius>1000){
                  // alert("半径大于1000,请缩小范围")
                  //  map.removeInteraction(_this.originInstance)
                   geometry.setRadius(0.01)
                  //geometry = fromCircle(geometry)
                  _this.$emit('modifyfinish', geometry)
                  
              }
        }
        if(evt.features.array_[0].getGeometry().getType()=="Polygon"){
            result = wkt.writeGeometry(geometry)
            _this.$emit('editFinish',  {'wkt':result,'id':evt.features.array_[0].id_})//WKTF将wkt字符串转为geojson
        }else if(evt.features.array_[0].getGeometry().getType()=="LineString"){
            result = wkt.writeGeometry(geometry)
            _this.$emit('editFinish',  {'wkt':result,'id':evt.features.array_[0].id_})//WKTF将wkt字符串转为geojson
        }
        else{
            result = wkt.writeGeometry(fromCircle(geometry))
            _this.$emit('editFinish',  {'wkt':result,'id':evt.features.array_[0].id_})//WKTF将wkt字符串转为geojson
        }
    });
      // 添加绘制交互组件----------------
      $rootComponent.addInteraction(this.originInstance, actived)
      // 添加绘制组件绘制完成后的回调函数----
      this.originInstance.on('drawend', (evt) => {
        // 清除上一次绘制的要素------
        this.originInstance.setActive(false);/***画图主要两步，一是给地图添加DraW实例，二是将实例设为true,画完后设为false,画完不remove实例，这样可以不用load继续画***/
        const feature = evt.feature
        feature.id_ = this.guid2()
        let geometry = feature.getGeometry()
        const type = geometry.getType()
        let result = {}
        // let uuid = this.guid2();
        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)
              // return false;
               //let radius = geometry.getRadius()
               this.$emit('drawed1000', radius)
               geometry.setRadius(0.01)
               geometry = fromCircle(geometry)
              
            }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)
        }
        this.$emit('drawFinish',{'wkt':result.wkt,'id':feature.id_})
        result.coods = geometry.getCoordinates()
        result.type = type
        result.feature = feature
        result.extent = geometry.getExtent()
        this.$emit('drawend', result)
      })
    },
    guid2() {
        function S4() {
          return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }
        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    },
    drawCircle1000(center,radius,map){
      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 () {
      this.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>
