<template>
</template>

<script>


import Graphic from '@arcgis/core/Graphic';
import Polygon from '@arcgis/core/geometry/Polygon';
import wktParser from 'terraformer-wkt-parser';
import Polyline from '@arcgis/core/geometry/Polyline';
import Point from '@arcgis/core/geometry/Point';
import Editor from '@arcgis/core/widgets/Editor';
import Sketch from '@arcgis/core/widgets/Sketch';
import SketchViewModel from '@arcgis/core/widgets/Sketch/SketchViewModel';
import SpatialReference from '@arcgis/core/geometry/SpatialReference';
import geodesicUtils from '@arcgis/core/geometry/support/geodesicUtils';
import projection from '@arcgis/core/geometry/projection';
import Extent from '@arcgis/core/geometry/Extent';
import Viewpoint from '@arcgis/core/Viewpoint';

export default {
  name: 'LocateByGeoinfo',
  props: {
    doClean: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      sketch: '',
      spatialReference: SpatialReference.WGS84,
      edit: false,
      isFlash: true,
      type: '',
      extent: ''
    };
  },
  inject: ['basicMap'],
  mounted() {

  },
  methods: {
    locate(options) {
      this.edit = options.edit;
      if(options.isFlash===false){
        this.isFlash=false;
      }else {
        this.isFlash=true;
      }
      if (!options) {
        return;
      }
      if (options.lng && options.lat) {
        this.locateByCoords([parseFloat(options.lng), parseFloat(options.lat)], options.scale);
        return;
      }
      if (options.WKT) {
        options.wkt = options.WKT;
      }
      let geomInfo = options.geoinfo ? options.geoinfo : options.wkt;
      if (!geomInfo) {
        this.$message.warn('没有空间信息');
        return;
      }
      let type;
      let geojson;
      let bsIndex = geomInfo.indexOf('(');
      if (bsIndex != -1) {
        type = geomInfo.slice(0, bsIndex).trim().toUpperCase();
        geojson = new wktParser.parse(geomInfo);
      } else {
        type = JSON.parse(options.geoinfo).type.toUpperCase();
        geojson = JSON.parse(options.geoinfo);
      }
      this.type = type;
      switch (type) {
        case 'MULTIPOLYGON': {
          if (this.doClean && this.basicMap.mapView.graphics&&!options.isMultiple) {
            this.basicMap.mapView.graphics.removeAll();
          }
          let lng = [], lat = [];
          geojson.coordinates.forEach((coordinates) => {
            console.log('坐标数组',coordinates)
            coordinates.forEach((coords)=>{
              coords.forEach((item, index) => {
                lng.push(item[0]);
                lat.push(item[1]);
              });
              let rings = [];
              for (let i = 0; i < coords.length; i++) {
                let ring = [];
                let vertexes = coords[i];
                for (let j = 0; j < vertexes.length; j++) {
                  let vertex = vertexes[j];
                  ring.push(vertex);
                }
                rings.push(ring);
              }
              console.log('坐标拼接',rings)
              let polygon = new Polygon({
                rings: rings,
                spatialReference: this.spatialReference
              });
              this.locateByGeometry(polygon);
            })
          });
          lng.sort();
          lat.sort();
          if(!this.isFlash) return;
          this.extent = new Extent(
            lng[0], lat[0], lng[lat.length - 1], lat[lat.length - 1]
          );
          let m_scale = this.basicMap.mapView.scale * 2;
          debugger
          this.basicMap.mapView.goTo({
            scale: m_scale
          }, {
            duration: 600
          });
          setTimeout(() => {
            this.basicMap.mapView.extent = this.extent;
            this.basicMap.mapView2.extent = this.extent;
          }, 500);
          break;
        }
        case 'POLYGON': {
          let rings = [];
          let ring = [];
          let coords = geojson.coordinates;
          for (let i = 0; i < coords.length; i++) {
            ring = [];
            let vertexes = coords[i];
            for (let j = 0; j < vertexes.length; j++) {
              let vertex = vertexes[j];
              ring.push(vertex);
            }
            rings.push(ring);
          }
          let polygon = new Polygon({
            rings: rings,
            spatialReference: this.spatialReference
          });
          if (options.isMultiple) {
            this.locateByGeometryUnClean(polygon, { isAll: true });
          } else {
            this.locateByGeometry(polygon);
          }
          break;
        }
        case 'LINESTRING': {
          let paths = [];
          let path = [];
          let coords = geojson.coordinates;
          for (let i = 0; i < coords.length; i++) {
            path = [];
            let vertexes = coords[i];
            for (let j = 0; j < vertexes.length; j++) {
              let vertex = vertexes[j];
              path.push(vertex);
            }
            paths.push(path);
          }
          let lineString = new Polyline({
            paths: paths,
            spatialReference: this.spatialReference
          });
          var satrtGraphic = new Graphic({
            geometry: new Point({
              hasZ: false,
              hasM: false,
              x: coords[0][0],
              y: coords[0][1],
              spatialReference: this.spatialReference
            }),
            symbol: {
              // 类型有 图片标记 和 点
              type: 'picture-marker',
              // 图片地址，可以网络路径或本地路径（PS：base64亦可）
              url: require('@/assets/start.png'),
              // 图片的大小
              width: '24px',
              height: '24px'
            }
          });
          var endGraphic = new Graphic({
            geometry: new Point({
              hasZ: false,
              hasM: false,
              x: coords[coords.length - 1][0],
              y: coords[coords.length - 1][1],
              spatialReference: this.spatialReference
            }),
            symbol: {
              // 类型有 图片标记 和 点
              type: 'picture-marker',
              // 图片地址，可以网络路径或本地路径（PS：base64亦可）
              url: require('@/assets/end.png'),
              // 图片的大小
              width: '24px',
              height: '24px',
              displacement: [0, 16.5]
            }
          });
          this.locateByGeometry(lineString, { name: options.name, isAll: options.isAll });
          // 将绘制的图形添加到view
          if (options && options.name == 'path') {
            this.basicMap.path_GraphicsLayer.addMany([satrtGraphic, endGraphic]);
          } else {
            this.basicMap.mapView.graphics.addMany([satrtGraphic, endGraphic]);
          }
          break;
        }
        default:
          break;
      }
    },
    locateByCoords(coords, scale) {
      if (this.doClean) {
        this.basicMap.mapView.graphics.removeAll();
      }
      let point_symbol = {
        type: 'picture-marker',
        url: require('../static/locate-red.png'),
        width: '48px',
        height: '48px',
        yoffset: '24px'      //图片默认定位在中心，所以Y方向需要设置一下偏移量
      };
      let point = {
        type: 'point',
        longitude: coords[0],
        latitude: coords[1]
      };
      let pointGraphic = new Graphic({
        geometry: point,
        symbol: point_symbol
      });
      this.basicMap.mapView.graphics.add(pointGraphic);
      let m_scale = this.basicMap.mapView.scale * 2;
      this.basicMap.mapView.goTo({
        scale: m_scale
      }, {
        duration: 600
      });
      if (scale === null || scale === undefined) {
        scale = 2000;
      }
      setTimeout(() => {
        this.basicMap.mapView.goTo({
          center: coords,
          scale: scale
        }, {
          duration: 1400
        });
        this.basicMap.mapView2.goTo({
          center: coords,
          scale: scale
        }, {
          duration: 1400
        });
      }, 500);
    },
    locateByGeometryUnClean(geom, option) {
      const lineSymbol = {
        type: 'simple-line',
        color: [255, 255, 255],
        width: 3
      };
      const polygonSymbol = {
        type: 'simple-fill',  // autocasts as new SimpleFillSymbol()
        // color: [128, 128, 128, 0.5],
        color: [0, 255, 255],
        outline: {  // autocasts as new SimpleLineSymbol()
          color: [255, 0, 0],
          width: '6px',
          style: 'short-dot'
        }
      };

      let cur_symbol = '';
      if (geom.type !== 'polyline') {
        cur_symbol = polygonSymbol;
        if (this.type === 'MULTIPOLYGON'||this.edit||!this.isFlash) {
          cur_symbol={
            type: 'simple-fill',  // autocasts as new SimpleFillSymbol()
            // color: [128, 128, 128, 0.5],
            color: [0, 255, 255,0.2],
            outline: {  // autocasts as new SimpleLineSymbol()
              color: [255, 0, 0],
              width: '6px',
              style: 'short-dot'
            }
          }
        }
      } else {
        cur_symbol = lineSymbol;
      }

      let graphic = new Graphic({
        geometry: geom,
        symbol: cur_symbol
      });

      if (this.edit) {
        this.sketchAddGraphic(graphic);
      } else if (option && option.name == 'path') {
        this.basicMap.path_GraphicsLayer.add(graphic);
      } else {
        this.basicMap.mapView.graphics.add(graphic);
      }
      if (option && option.isAll) return;
      if (this.type === 'MULTIPOLYGON'||!this.isFlash) {
        return;
      }
      // this.basicMap.layerSketch.add(graphic);
      // let center = geom.centroid;
      let m_scale = this.basicMap.mapView.scale * 2;
      this.basicMap.mapView.goTo({
        scale: m_scale
      }, {
        duration: 600
      });
      setTimeout(() => {
        this.basicMap.mapView.goTo(
          geom, {
            duration: 1400
          }).then((evt) => {
          let cur_scale = this.basicMap.mapView.scale;
          this.basicMap.mapView.goTo({
              scale: cur_scale * 1.5
            }, {
              duration: 500
            }
          );
          if(geom.type !== 'polygon'||this.edit||!this.isFlash) return
          let temp = 0;
          let handler = setInterval(function() {
            if (temp === 6) {
              if (handler) {
                if (!graphic.visible)
                  //graphic.show();
                  graphic.visible = true;
                clearInterval(handler);
                handler = null;
                graphic.symbol = {
                  type: 'simple-line',
                  color: [255, 0, 0],
                  width: 5,
                  style: 'short-dot'
                };
              }
              return;
            }
            if (graphic.visible) {
              graphic.visible = false;
            } else {
              graphic.visible = true;
            }
            temp++;
          }, 400);
          /*let polygonSym = {
            type: 'simple-fill',  // autocasts as new SimpleFillSymbol()
            // color: [128, 128, 128, 0.5],
            color: [255, 255, 255, 0.8],
          };
          let graphic = new Graphic({
            geometry: geom,
            symbol: polygonSym
          });
          this.basicMap.locate_GraphicsLayer.add(graphic);*/
        });
        this.basicMap.mapView2.goTo(
          geom, {
            duration: 1400
          }).then((evt) => {
          let cur_scale = this.basicMap.mapView2.scale;
          this.basicMap.mapView2.goTo({
              scale: cur_scale * 1.5
            }, {
              duration: 500
            }
          );
        });
      }, 500);
    },
    locateByGeometryWithClean(geom, option){
      this.clear();
      this.locateByGeometryUnClean(geom, option);
    },
    locateByGeometry(geom, option) {
      if (this.type !== 'MULTIPOLYGON' && this.doClean && this.basicMap.mapView.graphics) {
        this.clear();
      }
      this.locateByGeometryUnClean(geom, option);
    },
    locateToExtent(extent, geoConfigs) {
      if (extent !== null && JSON.stringify(extent) !== '{}') {
        let vp = new Viewpoint({
          targetGeometry: extent
        });
        this.basicMap.mapView.goTo({
          target: vp
        }, {
          duration: 600
        }).then((evt) => {
          let cur_scale = this.basicMap.mapView.scale;
          this.basicMap.mapView.goTo({
              scale: cur_scale * 1.5
            }, {
              duration: 500
            }
          ).then((evt) => {
            if (geoConfigs && geoConfigs.length > 0) {
              for (let i = 0; i < geoConfigs.length; i++) {
                let geoConfigItem = geoConfigs[i];
                geoConfigItem.isMultiple = true;
                geoConfigItem.isFlash = false;
                this.locate(geoConfigItem);
              }
            }
          });
        });
      }
    },
    _sketchViewModel(callback) {
      var self = this;
      if (!self.sketchViewModel) {
        self.sketchViewModel = new SketchViewModel({
          layer: self.layerSketch,
          view: self.mapView
        });
        self.sketchViewModel.on('create', function(event) {
          if (event.state == 'start') {
            self.layerSketch.removeAll();   //删除全部
          } else if (event.state == 'complete') {
            // console.log(event.vertices)
          }
        });
      }
      callback();
    },
    //添加编辑要素
    sketchAddGraphic(graphic) {
      this.layerSketch = this.basicMap.layerSketch;
      this.mapView = this.basicMap.mapView;
      var self = this;
      this._sketchViewModel(function() {
        self.layerSketch.removeAll();
        self.layerSketch.add(graphic);
      });
    },
    //激活绘制面工具
    sketchPolygonTools() {
      var self = this;
      this._sketchViewModel(function() {
        self.sketchViewModel.create('polygon', { mode: 'click' });
      });

    },
    //前进
    sketchRedo() {
      var self = this;
      this._sketchViewModel(function() {
        self.sketchViewModel.redo();
      });
    },
    //回退
    sketchUndo() {
      var self = this;
      this._sketchViewModel(function() {
        self.sketchViewModel.undo();
      });
    },
    //删除全部
    sketchDelete() {
      var self = this;
      this._sketchViewModel(function() {
        self.layerSketch.removeAll();   //删除全部
      });
    },

    clear() {
      this.basicMap.mapView.graphics.removeAll();
    }
  }

};
</script>

<style scoped>
.ss {
  background-color: rgb(128, 128, 128);
}
</style>
