<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 {boundingExtent,getCenter} from 'ol/extent'
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 {clearSpatial} from '../base/poiQuery'
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 { 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-drawlx',
  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
    },
    typeFlag:{
      type: Boolean
    },
    drawStyle: {
      type: Object,
      default: function () {
        return SymbolConfig['defaultDrawStyle']
      }
    }
  },
  data () {
    return {
      modify:{},
      modify1000:{},
      count:0,
      timer:{}
    }
  },
  watch: {
    actived (flag) {//监控画图的状态，当变化时去
      this.originInstance.setActive(flag)
      this.reload()
    },
    type (value) {
      this.reload()//type变化的时候重新加载load
    },
    typeFlag(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
      sessionStorage.setItem("type",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)
      })
      map.removeInteraction(this.originInstance);//首先移除原来的Draw实例
      // map.removeInteraction(this.modify)
      // 实例化绘制组件======
      this.originInstance = new Draw({
        source: drawLayer.getSource(), // 绘制层数据源
        type: drawType/** @type {ol.geom.GeometryType} */,
        style: convertObjToStyle(drawStyle),
        geometryFunction
      })
      //  map.removeInteraction(this.originInstance)
      //  map.removeInteraction(this.modify);
      // this.modify = new Modify({
      //       source: drawLayer.getSource()
      // });
     
      // //clearInteraction(map)
      // map.addInteraction(this.modify);
      var _this = this;
      //  _this.modify.on("modifyend",function (evt) {
      //     const feature = evt.feature
      //     let geometry = evt.features.array_[0].getGeometry()
      //     //const feature = evt.feature
      //     //let geometry = feature.getGeometry()
      //     if(geometry.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', radius)
                  
      //         }
      //     }
      //     let result;
      //     if(evt.features.array_[0].getGeometry().getType()=="Polygon"){
      //         let polygonArea = geometry.getArea()*100000;
      //         if(polygonArea>31.41592653){//当面积大于1000米圆的面积直接返回
      //               _this.$emit("ModifyPolygonArea",polygonArea)
      //         }
      //         result = wkt.writeGeometry(geometry)
      //         _this.$emit('editFinish', result)
      //     }else{
      //         result = wkt.writeGeometry(fromCircle(geometry))
      //         _this.$emit('editFinish', result)
      //     }
      // });
      //drawLayer.getSource().clear()
      // 添加绘制交互组件----------------
      //首先移除原来的Draw实例,移除完成后添加新的实例，active为true;
      $rootComponent.addInteraction(this.originInstance, actived);//$rootComponent为地图组件,this.originInstance为绘制对象
      this.$emit("mapVueComponent",$rootComponent)//初始化的时候将地图组件传递给前端业务层
      // 添加绘制组件绘制完成后的回调函数----
      this.originInstance.on('drawend', (evt) => {
          // 清除上一次绘制的要素------
          this.originInstance.setActive(false);/***画图主要两步，一是给地图添加DraW实力，二是将实例设为true,画完后设为false,画完不remove实力，这样可以不用load继续画***/
          //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];
            let centerLogLat,radius;
            let circle = evt.feature.getGeometry();
            centerLogLat = circle.getCenter()
            radius = circle.getRadius();
            // console.log("11111111111111111111")
            // console.log("圆心坐标:"+centerLogLat+";半径:"+radius*100000+"m")
            let radius1 = radius*100000;
            this.$emit("radiusAndCenter",{centerLogLat,radius1})
            this.$emit("drawTwoPoints",evt.target.sketchCoords_)
            this.$emit("CircleGeometry",evt.feature.values_.geometry)
            // 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.02).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.02).geometry.coordinates.join(",")
                result.isSelfInteraction = false            
            }   
          }
          if (type === GeometryType.POLYGON) {//多边形
            let typeFlag = sessionStorage.getItem("type")
            if(typeFlag=="Box"){//矩形
                let centerLon = (evt.target.sketchCoords_[0][0]+evt.target.sketchCoords_[1][0])/2
                let centerLat = (evt.target.sketchCoords_[0][1]+evt.target.sketchCoords_[1][1])/2
                this.$emit("boxCenter",[centerLon,centerLat])
            }else{//不规则形状获取中心点坐标
                let extent = boundingExtent(evt.feature.getGeometry().getCoordinates()[0]);
                let center = getCenter(extent)
                // var extent = ol.extent.boundingExtent(feature.getGeometry().getCoordinates()[0]); //获取一个坐标数组的边界，格式为[minx,miny,maxx,maxy]
                // var center = ol.extent.getCenter(extent);   //获取边界区域的中心位置
                this.$emit("polygonCenter",center)
            }
            let polygonArea = feature.values_.geometry.getArea()*100000;
            //  this.$emit("pologonGeometry",feature.values_.geometry)
            if(polygonArea>31.41592653){//当面积大于1000米圆的面积直接返回
                  this.$emit("getPolygonArea",polygonArea)
            }
            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();
          //画圆或者多边形闪烁
          if(result.coods[0]!=undefined){
            let flashingArr = result.coods[0]
          }
          result.type = type
          result.feature = feature
          result.extent = geometry.getExtent()
          let coords = result.coods;

          let geojson = this.arrayToJson(coords);
          // let finalgeojson = "{
          //  "type": "FeatureCollection",
          //     "crs": "{
          //         "type": "name",
          //         "properties": "{
          //             "name": "EPSG:4326"
          //         }"
          //     }",
          //     'features': "[{
          //         'type': 'Feature',
          //         'geometry': {
          //             'type': 'LineString',
          //             'coordinates': "[
          //                 '+geojson+'
          //             ]"
          //         }
          //     }]"
          // }";
          let finalgeojson = '{"type":"LineString","coordinates":'+geojson+'}'
          console.log("******************")
          console.log(finalgeojson)
          this.$emit('drawend', result)
          //this.clearSpatial("nearbySearch",this.poiMap)
        })
    },
    arrayToJson(o) {     
        var r = [];     
        if (typeof o == "string") return "\"" + o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";     
        if (typeof o == "object") {     
          if (!o.sort) {     
            for (var i in o)     
            r.push(i + ":" + this.arrayToJson(o[i]));     
            if (!!document.all && !/^\n?function\s*toString\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) {     
            r.push("toString:" + o.toString.toString());     
            }     
            r = "{" + r.join() + "}";     
          } else {     
            for (var i = 0; i < o.length; i++) {     
            r.push(this.arrayToJson(o[i]));     
            }     
            r = "[" + r.join() + "]";     
          }     
          return r;     
        }     
        return o.toString();     
    },

    // task(centerLogLat,radius,map){
    //   this.clearSpatial("temp",map)
    //   this.count++;
    //   if(this.count==6){
    //       clearInterval(this.timer);
    //   }else{
    //      if((this.count)%2==0){ 
    //         this.clearSpatial("nearbySearch",map)
    //         this.drawCircle1000(centerLogLat,radius,map,'#FF0000')
    //       }else{//刚开始画  画完再清除
    //         this.clearSpatial("nearbySearch",map)
    //         this.drawCircle1000(centerLogLat,radius,map,'#0000FF')
    //       }
    //   }
     
    // },
    //创建样式
    createLabelStyle(feature) {
      //返回一个样式
      return new Style({
          //把点的样式换成ICON图标
          image: new Icon({
              //设置图标偏移
              anchor: [0.5, 1],
              //标注样式的起点位置
              anchorOrigin: 'top-right',
              //X方向单位：分数
              anchorXUnits: 'fraction',
              //Y方向单位：像素
              anchorYUnits: 'pixels',
              //偏移起点位置的方向
              offsetOrigin: 'top-right',
              //透明度
              opacity: 0.9,
              //图片路径
              //src: 'images/map.png'
              src:'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png'
          }),
          //文本样式
          text: new Text({
              //对齐方式
              textAlign: 'center',
              //文本基线
              textBaseline: 'middle',
              //字体样式
              font: 'normal 14px 思源黑体',
              //文本内容
              //text: feature.get('name'),
              text: "",
              //填充样式
              fill: new Fill({
                  color: '#aa3300'
              }),
              //笔触
              stroke: new Stroke({
                  color: '#ffcc33',
                  width: 2
              })
          }),
          //层
          zIndex: 20
      });
  },
    //添加矢量标签
     addVectorLabel(title, coordinate) {
        //初始化一个新的点要素
        var newFeature = new Feature({
            geometry: new Point(coordinate),
            name: title
        });
        //设置点的样式
        newFeature.setStyle(createLabelStyle(newFeature));

        //清楚坐标点
        layer.getSource().clear();

        //将当前要素添加到矢量数据源中
        layer.getSource().addFeature(newFeature);
    },
    drawCircle1000(center,radius,map,color,fill){
      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:fromCircle(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: color,
                        width: 1
                    }),
                    fill: new Fill({
                        color: fill
                    })
                })
            })
            map.addLayer(vectorLayer)
            // this.modify1000 = new Modify({
            //       source: vectorSource
            // });
            // this.poiMap.removeInteraction(this.modify1000);
            // map.removeInteraction(this.originInstance)
              //clearInteraction(map)
            // this.poiMap.addInteraction(this.modify1000);
            var _this = this;
            // _this.modify1000.on("modifyend",function (evt) {
            //     console.log("11111111111111111111")
            //     //_this.poiMap.removeInteraction(modify);//没有修改点了
            // })
            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>
