<template>
	<div :style="{'height':mapHeight,'width':'100%','position':'relative'}">
		<div id="maps" class="map" :style="{'height':'100%'}">
		</div>
		<!-- 弹框 -->
		<div ref="popup" class="popup" v-show="shopPopup">
		  <div class="info">
			<div>点位名称：{{pointObj.name}}</div>
		    <div class="address">地址：{{pointObj.address}}</div>
		    <div class="showinfo">经度：{{pointObj.longitude}}</div>
			<div>纬度:{{pointObj.latitude}}</div>
		  </div>
		</div>
	</div>


</template>
<script>
	import "ol/ol.css";
	import {
		Tile as TileLayer,
		Vector as VectorLayer
	} from "ol/layer";
	import XYZ from "ol/source/XYZ";
	import {
		TileArcGISRest
	} from "ol/source"
	import tilegrid from "ol/tilegrid/TileGrid"
	import {
		defaults as defaultControls
	} from "ol/control";
	import {
		get as getprojection
	} from "ol/proj"
	import {
		Projection,
		addProjection
	} from "ol/proj"
	import Map from "ol/Map.js";
	import View from "ol/View.js";

	// 标注点位
	import {
		Vector as VectorSource
	} from "ol/source";
	import * as olProj from "ol/proj";
	import {
		Feature,
		Overlay
	} from "ol"
	import {
		Point
	} from "ol/geom";
	import {
		Style,
		Fill,
		Stroke,
		Circle as sCircle
	} from "ol/style";


	import proj4 from 'proj4'


	export default {
		components: {

		},
		data() {
			return {
				map: null,
				projection: "EPSG:4490",
				mapHeight: "400px",
				mapConfigs: {
					Map_Code: "EPSG:4490", //坐标系名
					// Map_extent: [390000, 3500000, 490000, 3360000], //范围框
					Map_units: "degrees", //单位  m/degrees等
					Map_axisOrientation: "neu", //轴
					Map_global: false, //全球
					MAP_center: [120.582031, 31.304329], //定义中心点
					Map_Zooms: [13, 23, 10], //定义地图初始层级、最大层级、最小层级
					Map_ID: "maps", //地图标识ID
				},
				featuresArr: [],
				flagLayer: null,
				pointArr: [],
				shopPopup: false,
				pointaddress:"",
				pointObj:{}
			};

		},
		created() {},
		mounted() {
			//  转换坐标系
			proj4.defs("EPSG:4490", '+proj=longlat +ellps=GRS80 +no_defs')
			this.projection = new Projection({
				code: this.mapConfigs.Map_Code,
				units: this.mapConfigs.Map_units,
				axisOrientation: this.mapConfigs.Map_axisOrientation,
				global: this.mapConfigs.Map_global,
			});
			addProjection(this.projection);

			this.initLoad();
		},
		watch: {
		pointArr(newval, oldval) {
		  if (newval) {
		    // this.resetPointArr()
		    this.pointArr = newval
		    this.$nextTick(function() {
		      this.setMarker()
		    })
		  }
		},
		},
		methods: {
			initLoad() {
				var that = this;
				var clientHeight = document.documentElement.clientHeight
				let tableHeight = clientHeight;
				that.mapHeight = tableHeight + "px";
				this.showMaps()
			},
			showMaps() {
				this.$nextTick(function() {
					this.initMap();
				})
			},
			initMap() {
				let map = new Map({
					target: "maps",
					view: new View({
						center: this.mapConfigs.MAP_center, //中心点经纬度
						zoom: this.mapConfigs.Map_Zooms[0], //图层缩放大小
						maxZoom: this.mapConfigs.Map_Zooms[1],
						minZoom: this.mapConfigs.Map_Zooms[2],
						projection: this.projection,
					}),
					layers: [],
					// interactions: defaultControls({
					//     doubleClickZoom: false,
					// }),
				});
				this.map = map;
				// 添加天地图
				let url = "http://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}";
				url = `${url}&T=vec_c&tk=2eecd3d615e01cf6dbe6d4b8b686d264`;
				let tdtLayer = new TileLayer({
					title: "天地图",
					id: "M2",
					type: "overlay",
					visible: true,
					layerType: "TD地图",
					opacity: 1,
					source: new XYZ({
						crossOrigin: 'anonymous',
						url: url,
						projection: "EPSG:4326"
					})
				});
				this.map.addLayer(tdtLayer);
				this.addOverlay()
				this.singleclick()
				// // 添加天地图标注
				// let urls = "http://t0.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=2eecd3d615e01cf6dbe6d4b8b686d264";
				// // urls = `${urls}&T=cva_w&tk=2eecd3d615e01cf6dbe6d4b8b686d264`;
				// let tdtLayers = new TileLayer({
				// 	title: "天地图",
				// 	id: "M22",
				// 	type: "overlay",
				// 	visible: true,
				// 	layerType: "TD地图2",
				// 	opacity: 1,
				// 	source: new XYZ({
				// 		crossOrigin: 'anonymous',
				// 		url: urls,
				// 		projection: "EPSG:4326"
				// 	})
				// });
				// this.map.addLayer(tdtLayers);
				
				// this.ShowLayers()
				// this.map.layer2.setVisible(false)
			},
			//加载图层
			ShowLayers() {
				let projection = getprojection("EPSG:4490");
				let origin = [-400.0, 399.9999999999998];
				let resolutions = [0.0027465820824835565, 0.0013732910412417782, 6.866455206208891E-4,
					3.4332276031044456E-4, 1.7166138015522228E-4, 8.583069007761114E-5, 4.291534503880557E-5,
					2.1457672519402785E-5, 1.0728836259701392E-5
				];

				let fullExtent = [118.63622216442072, 30.12564516975147, 122.81217622965288, 32.74305227616479];

				let tileGrid = new tilegrid({
					tileSize: 256,
					origin: origin,
					extent: fullExtent,
					resolutions: resolutions
				});
				let layer = new TileLayer({
					title: "河道图",
					id: "H1",
					type: "overlay",
					visible: false,
					layerType: "GIS地图",
					opacity: 1,
					source: new XYZ({
						tileGrid: tileGrid,
						url: "http://172.17.50.65:6080/arcgis/rest/services/hcdt/%E8%8B%8F%E5%B7%9E%E6%B0%B4%E7%B3%BB%E5%9B%BE%E9%AB%98%E4%BA%AE%E7%89%88/MapServer/tile/{z}/{y}/{x}",
						projection: projection
					})
				})
				this.map.addLayer(layer);
				
			},
			// 设置巡查 点位
			setMarker() {
			  // 设置图层
			  if(this.flagLayer!=null){
				  this.map = null
				  let _that = this;
				  this.flagLayer
				    .getSource()
				    .getFeatures()
				    .forEach(function(feature) {
				      _that.flagLayer.getSource().removeFeature(feature);
				    });
				  this.featuresArr = [];
				  this.flagLayer.getSource().clear();
			  }
			  
			  this.flagLayer = new VectorLayer({
			    source: new VectorSource()
			  });
			  // 添加图层
			  this.map.addLayer(this.flagLayer);
			  // 循环添加feature
			  for (let i = 0; i < this.pointArr.length; i++) {
			    // 创建feature，一个feature就是一个点坐标信息
			    let feature = new Feature({
			      geometry: new Point([this.pointArr[i].longitude, this.pointArr[i].latitude])
			    });
			    // 设置展示 地址
			    feature.set('pointObj', this.pointArr[i])
			    // feature.set('types', this.pointArr[i][4])
			    // 设置 巡查ID
			    // feature.setId(this.pointArr[i][3])
			    feature.setStyle(
			      new Style({
			        image: new sCircle({
			          fill: new Fill({
			            color: '#000',
			          }),
			          radius: 10,
			        }),
			      })
			    );
			    this.featuresArr.push(feature);
			  } // for 结束
			  this.flagLayer.getSource().addFeatures(this.featuresArr);
			},
			
			addOverlay() {
			  // 创建Overlay
			  let elPopup = this.$refs.popup;
			  this.popup = new Overlay({
			    element: elPopup,
			    positioning: "bottom-center",
			    stopEvent: false,
			    offset: [0, -20],
			  });
			  this.map.addOverlay(this.popup);
			},
			singleclick() {
			  // 点击
			  this.map.on("singleclick", (e) => {
			    // 判断是否点击在点上
			    let feature = this.map.forEachFeatureAtPixel(
			      e.pixel,
			      (feature) => feature
			    );
			    if (feature) {
			      this.shopPopup = true;
			      // 设置弹窗位置
			      let coordinates = feature.getGeometry().getCoordinates();
			      this.pointObj = feature.get('pointObj');
			      this.popup.setPosition(coordinates);
				  // 打卡
				  this.$emit("getPoint",this.pointObj)
			    } else {
			      this.shopPopup = false;
			    }
			  });
			},
			moveto(longitude, latitude) {
			  this.map.getView().animate({
			    center: [longitude, latitude], // 中心点
			    rotation: undefined,
			    duration: 1000
			  })
			}
		},
	}
</script>
<style scoped>
	/deep/ .ol-zoom {
		display: none;
	}
	.popup {
	  width: 200px;
	  background-color: white;
	  padding: 18px;
	  border-radius: 10px;
	  box-shadow: 0 0 15px rgb(177, 177, 177);
	  }
</style>
