<template>
  <div style="width:100%;height:100%">
    <div id="map" ref="rootmap"></div>
  </div>
</template>

<script>
import "ol/ol.css";
import Map from "ol/Map";
// import TileLayer from "ol/layer/Tile";
// import ImageLayer from "ol/layer/Image";
import View from "ol/View";
// import ol from "ol";

// import {getTopLeft, getWidth} from "ol/extent";

// import ImageWMS from "ol/source/ImageWMS";
// import WMTS from "ol/source/WMTS";
// import TileWMS from "ol/source/TileWMS";
// import WMTSTileGrid from "ol/tilegrid/WMTS";
// ol.source.TileImage
// ol.layer.Tile
import {get as getProjection, transform} from "ol/proj";
import {TileGrid} from "ol/tilegrid/TileGrid";
import {TileImage} from "ol/source/TileImage";
import {XYZ, Vector as SourceVec} from "ol/source";
import {Tile,Vector as LayerVec} from "ol/layer";

import {Circle as CircleStyle, Fill, Stroke, Style, Icon} from 'ol/style';
import {Draw, Modify, Snap} from 'ol/interaction';
// import {OSM, Vector as SourceVec} from 'ol/source';
// import {Tile as TileLayer, Vector as LayerVec} from 'ol/layer';
import {get} from 'ol/proj';
import { Feature } from "ol";



// import {Vector as SourceVec} from "ol/source";
// import {Feature} from "ol";
import {LineString, Point} from "ol/geom";
// import {Icon, Stroke, Style} from "ol/style";
// import {Vector as LayerVec} from "ol/layer";


export default {
  props: {
      pointObj:{type:Object},
      isEdit:false
  },
  data() {
    return {
      map: null,
      typeSelect:'Point',
      source:null,
      draw:null,
      snap:null,
      locations:[],
      vector:null,
      pointArry:new Map(),
     
    };
  },
  mounted() {

    this.initdev();
    this.initPoint();
    // this.addpoint(point);



    var that = this
    // this.map.on("click", function (e) {
    //        that.addMarker(e.coordinate,'专家站点.png',0.2);
    // });


    var view = this.map.getView();

    view.on('change:resolution', function (e) {

    });
    view.on('change:center', function (e) {

    });
    this.map.on('moveend', function (e) {

    });
  
  },
  methods: {
    initdev: function () {

      // function getWMTSLayer(url, layer) {
      //   let key = "98ec3e37b32974c2d58ea1a790640fe7"
      //   let projection = getProjection("EPSG:3857");
      //   let projectionExtent = projection.getExtent();
      //   let size = getWidth(projectionExtent) / 256;

      //   function getResolutions() {
      //     let resolutions = [];
      //     for (let z = 1; z < 19; ++z) {
      //       resolutions[z] = size / Math.pow(2, z);
      //     }
      //     return resolutions
      //   }

      //   return new TileLayer({
      //     source: new WMTS({
      //       url: url,
      //       layer: layer,
      //       style: "default",
      //       matrixSet: "w",
      //       format: "tiles",
      //       tileGrid: new WMTSTileGrid({
      //         origin: getTopLeft(projectionExtent),
      //         resolutions: getResolutions(),
      //         matrixIds: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
      //       }),
      //     }),

      //   })

      // }

      // var projection = getProjection("EPSG:3857");



      // const ign = getWMTSLayer('https://t{0-7}.tianditu.gov.cn/vec_w/wmts?tk=98ec3e37b32974c2d58ea1a790640fe7', 'vec');



      // var map = new Map({
      //   target: 'map',
      //   layers: [
      //     ign,
      //     getWMTSLayer('https://t{0-7}.tianditu.gov.cn/cva_w/wmts?tk=98ec3e37b32974c2d58ea1a790640fe7', 'cva'),
      //   ],
      //   view: new View({
      //     projection: projection
      //   })
      // });


      var projection = getProjection("EPSG:3857");
   const satellite = new Tile({ // 卫星地图
    visible: false, // 显示或隐藏（用于切换地图图层（卫星切换街道））
    source: new XYZ({
      attributions: '',
      url: 'https://webst0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=6&x={x}&y={y}&z={z}&scl=1&ltype=10'
    })
  })
  const street = new Tile({ // 街道地图
    visible: true, // 显示或隐藏（用于切换地图图层（卫星切换街道））
    source: new XYZ({
      attributions: '',
      url: 'https://webst0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}'
    })
  })

this.source = new SourceVec();
const vector = new LayerVec({
  source: this.source,
  style: new Style({
    fill: new Fill({
      color: 'rgba(255, 255, 255, 0.2)',
    }),
    stroke: new Stroke({
      color: '#ffcc33',
      width: 2,
    }),
    image: new CircleStyle({
      radius: 7,
      fill: new Fill({
        color: '#ffcc33',
      }),
    }),
  }),
});
  this.vector = vector;

  // 创建地图
  const map = new Map({
    target: 'map',
    layers: [ // 图层放置（类似有卫星图层，街道图层等）
      satellite,
      street,
      vector 
    ],
    view: new View({
      zoom: 11, // 当前缩放
      maxZoom: 16, // 最大缩放
      minZoom: 8, // 最小缩放
      projection: 'EPSG:4326',
      center: [121.65523,31.892831], // 中心坐标
    })
  })

  street.setVisible(false)
  satellite.setVisible(true)

    const modify = new Modify({source: this.source});
      map.addInteraction(modify);

      // map.getView().fit([75.0, 20.0, 135.0, 50.0], map.getSize());
      this.map = map;
      // this.addDrawLayer();
      if(this.isEdit){
           this.addInteractions();
      }
      var that = this;
  
      //  map.getView().setCenter(
      //     [118.642876, 31.970445]
      // );
      // map.getView().setCenter(this.transpoints([
      //   [118.642876, 31.970445]
      // ], 0)[0]);
      // map.getView().setZoom(13);
    },
    addInteractions() {
      var that = this
         let draw = new Draw({
          source: this.source,
          type: this.typeSelect,
        });
        draw.on('drawend',that.getLocation,this);
        draw.on('drawstar',that.removeDraw,this);
        //  draw.on('drawstart',that.removeDraw,this);
        this.draw = draw;
        this.map.addInteraction(draw);
        let snap = new Snap({source: this.source});
        this.snap = snap;
        this.map.addInteraction(snap);
      },
      getLocation(evt){
          var feature = evt.feature;
          var geo = feature.getGeometry();
          var cor = geo.getCoordinates();
          this.locations = cor;
      },
      changeAddInteractions(evt) {
         this.map.removeInteraction(this.draw);
         this.map.removeInteraction(this.snap);
         this.addInteractions();
      },
      removeDraw(evt){
          if(this.locations.length > 0){
              this.vector.getSource().clear()
          }
      },
      addMarker(lnglats,icon,size,id) {
            let tamarker = new Feature({
                tadata: {
                    sectionId: "point",
                    towerNumber: 22,
                }, //这里是用来传值用的，在接下来的一章里（事件）中我会讲到。
                geometry: new Point(lnglats) //这里是点坐标的位置，这里要注意fromLonLat
            });
            tamarker.setStyle(
                new Style({
                    image: new Icon({
                        color: "#eee",
                        crossOrigin: "anonymous",
                        src: require("../../assets/images/icons/" + icon) //本地的样式
                    })
                })
            ); //这里是样式
            var markerta = new LayerVec({
                source: new SourceVec({
                    features: [tamarker] //这里放的就是之前的那个点，如果要放置多个点直接push到这里面就行了
                })
            });
            this.pointArry.set(id,markerta);
            this.map.addLayer(markerta); //这里是执行，执行之后点就出来了
      }, 
        addline: function() {

            var points = [
                [118.78, 32.04],
                [118.88, 32.14]
            ]

            let line = new Feature({
                tadata: {
                    sectionId: "line",
                    towerNumber: 22
                },
                geometry: new LineString(points)
            }); //这里要注意写fromLonLat，很重要
            line.setStyle(new Style({
                stroke: new Stroke({
                    width: 3,
                    color: "#008000"
                })
            }));
            this.linevectorLayer = new LayerVec({
                source: new SourceVec({
                    features: [line] //要绘制多段线，直接push到这里面就行了
                })
            });
            this.map.addLayer(this.linevectorLayer); //这里是执行，执行之后点就出来了

        },
        initPoint(){
              var pointObj = this.pointObj;
               console.log(pointObj);
              if(pointObj){
                  if(pointObj.type == 2){
                    this.addMarker(pointObj.locations.split(','),'左侧-车站-高亮.png',0.2,'marker');
                  }
                  if(pointObj.type == 5){
                    this.addMarker(pointObj.locations.split(','),'专家站点.png',0.2,'marker');
                  }

                
              }
        },
        transpoints: function(points, type) {
            if (false) {
                return points;
            } else {
                if (type == 1) {
                    var pp = [];
                    points.forEach(point => {
                        pp.push(transform(point, "EPSG:3857", "EPSG:4326"));
                    });
                    return pp;
                } else {
                    var pp = [];
                    points.forEach(point => {
                        pp.push(transform(point, "EPSG:4326", "EPSG:3857"));
                    });
                    return pp;
                }
            }
        },
  }
};
</script>

<style scoped>
#map {
  height: 100%;
}

</style>
