<template>
	<div>
		<!-- cesiumContainer ref='cesiumContainer' style="display: none"-->
		<div id="cesiumContainer" style="cursor: auto"></div>
		<div class="bottom-bar">
			<div class="bottom-bar-item" id="tool-clickQuery" v-on:click="clickQuery()">
				<div class="bottom-bar-item-ps"></div>
				<span>点选查询</span>
			</div>
			<div class="bottom-bar-item" id="tool-dis" v-on:click="measureDistance()">
				<div class="bottom-bar-item-dis"></div>
				<span>距离测量</span>
			</div>
			<div class="bottom-bar-item" id="tool-area" v-on:click="measureArea()">
				<div class="bottom-bar-item-area"></div>
				<span>面积测量</span>
			</div>
			<div class="bottom-bar-item" id="tool-CircleQuery">
				<div class="bottom-bar-item-yxcx"></div>
				<span>圆形查询</span>
			</div>
			<div class="bottom-bar-item" id="tool-SquarenessQuery">
				<div class="bottom-bar-item-jxxz"></div>
				<span>矩形查询</span>
			</div>
			<div class="bottom-bar-item" id="tool-ScopeQuery">
				<div class="bottom-bar-item-spatial"></div>
				<span>范围查询</span>
			</div>
			<div class="bottom-bar-item" id="tool-dmfx">
				<div class="bottom-bar-item-dmfx"></div>
				<span>断面分析</span>
			</div>
			<div class="bottom-bar-item" id="tool-kwLine">
				<div class="bottom-bar-item-pzfx"></div>
				<span>碰撞分析</span>
			</div>
			<div class="bottom-bar-item" id="tool-ftfx">
				<div class="bottom-bar-item-ftfx"></div>
				<span>覆土分析</span>
			</div>
			<div class="bottom-bar-item" id="tool-ltfx">
				<div class="bottom-bar-item-ltfx"></div>
				<span>连通分析</span>
			</div>
			<div class="bottom-bar-item" id="tool-layerCtrl" v-on:click="layerCtrl()">
				<div class="bottom-bar-item-layers"></div>
				<span>图层管理</span>
			</div>
			<div class="bottom-bar-item" id="tool-clear" v-on:click="clearLays()">
				<div class="bottom-bar-item-clear"></div>
				<span>清除量算</span>
			</div>
			<div class="bottom-bar-item" id="tool-fullscreen" v-on:click="toggleFullScreen()">
				<div class="bottom-bar-item-fs"></div>
				<span>全屏显示</span>
			</div>
		</div>
		<div id="tips" style="        margin-left: 800px;        top: 300px;        position: absolute;        display: none;        background-color: #fff;        border: 2px solid #69b4fd;        z-index: 999;      ">
			<font color="#000000"><strong>点击地图，双击结束编辑</strong></font>
		</div>
		<!-- cesiumContainer end-->
	</div>
</template>
<script></script>

<script>
	import $ from 'jquery'
	import proj4 from 'proj4'
	import L from 'leaflet'
	import 'leaflet-draw'
	import * as mapclient from '@supermap/iclient-leaflet'
	import * as turf from '@turf/turf'
	import Vue from 'vue'
	import 'leaflet/dist/leaflet.css'
	import 'leaflet-draw/dist/leaflet.draw.css'
	import 'layui-src/dist/layui.js'
	import 'layui-src/dist/css/layui.css'
	// import "layui-src/dist/css/modules/layer/cool/cool.css";
	// layui.use(["layer"], function () {
	//   let layer = layui.layer;
	//   layer.config({
	//     extend: "cool/cool.css",
	//     skin: "layui-ext-coolskin",
	//   });
	// });
	Vue.prototype.$mapclent = mapclient
	window.jQuery = $
	window.panels = {}
	// const layuilayer = require("layui-layer");
	L.drawLocal = {
		draw: {
			toolbar: {
				// #TODO: this should be reorganized where actions are nested in actions
				// ex: actions.undo  or actions.cancel
				actions: {
					title: '取消绘图', //'Cancel drawing',
					text: '', //'Cancel'
				},
				finish: {
					title: '完成绘图', //'Finish drawing',
					text: 'Finish',
				},
				undo: {
					title: '删除最后绘制的点', //'Delete last point drawn',
					text: '', //'Delete last point'
				},
				buttons: {
					polyline: '绘制一个多段线', //'Draw a polyline',
					polygon: '绘制一个多边形', //'Draw a polygon',
					rectangle: '绘制一个矩形', //'Draw a rectangle',
					circle: '绘制一个圆', //'Draw a circle',
					marker: '绘制一个标记', //'Draw a marker',
					circlemarker: '绘制一个圆形标记', //'Draw a circlemarker'
				},
			},
			handlers: {
				circle: {
					tooltip: {
						start: '单击并拖动以绘制圆', //'Click and drag to draw circle.'
					},
					radius: 'Radius',
				},
				circlemarker: {
					tooltip: {
						start: '单击“地图”以放置圆标记', //'Click map to place circle marker.'
					},
				},
				marker: {
					tooltip: {
						start: '单击“地图”以放置标记', //'Click map to place marker.'
					},
				},
				polygon: {
					tooltip: {
						start: '单击开始绘制形状', //'Click to start drawing shape.',
						cont: '单击继续绘制形状', //'Click to continue drawing shape.',
						end: '单击第一个点关闭此形状', //'Click first point to close this shape.'
					},
				},
				polyline: {
					error: '<strong>错误:</strong>形状边缘不能交叉！', //'<strong>Error:</strong> shape edges cannot cross!',
					tooltip: {
						start: '单击开始绘制线', //'Click to start drawing line.',
						cont: '单击以继续绘制线', //'Click to continue drawing line.',
						end: '单击“最后一点”以结束线', //'Click last point to finish line.'
					},
				},
				rectangle: {
					tooltip: {
						start: '单击并拖动以绘制矩形', //'Click and drag to draw rectangle.'
					},
				},
				simpleshape: {
					tooltip: {
						end: '释放鼠标完成绘图', //'Release mouse to finish drawing.'
					},
				},
			},
		},
		edit: {
			toolbar: {
				actions: {
					save: {
						title: '保存更改', //'Save changes',
						text: '保存', //'Save'
					},
					cancel: {
						title: '取消编辑，放弃所有更改', //'Cancel editing, discards all changes',
						text: '取消', //'Cancel'
					},
					clearAll: {
						title: '清除所有图层', //'Clear all layers',
						text: '清除所有', //'Clear All'
					},
				},
				buttons: {
					edit: '编辑图层', //'Edit layers',
					editDisabled: '无可编辑的图层', //'No layers to edit',
					remove: '删除图层', //'Delete layers',
					removeDisabled: '无可删除的图层', //'No layers to delete'
				},
			},
			handlers: {
				edit: {
					tooltip: {
						text: '拖动控制柄或标记以编辑要素', //'Drag handles or markers to edit features.',
						subtext: '单击“取消”撤消更改', //'Click cancel to undo changes.'
					},
				},
				remove: {
					tooltip: {
						text: '单击要删除的要素', //'Click on a feature to remove.'
					},
				},
			},
		},
	}
	export default {
		name: 'gisMapVue',
		data() {
			// data() 为变量赋值等

			return {
				// GX_Map_BaseUrl: '',
				GX_Datas_BaseUrl:
					'http://192.168.17.44:8090/iserver/services/data-weiweiGIS110/rest/data',
				GX_Plot_BaseUrl:
					'http://192.168.17.44:8090/iserver/services/plot-TY/rest/plot/',
				GX_Spatialanalyst_BaseUrl:
					'http://192.168.17.44:8090/iserver/services/spatialAnalysis-weiweiGIS110/restjsr/spatialanalyst',
				GX_TransportationAnalyst_BaseUrl:
					'http://192.168.17.44:8090/iserver/services/transportationAnalyst-weiweiGIS110/rest/networkanalyst/weiweiGIS110_Network@weiweiGIS110',
				GX_CZ: [
					'全部',
					'铸铁',
					'钢',
					'PVC',
					'PE',
					'PP-R',
					'铜',
					'陶制',
					'铝塑复合管',
					'不锈钢复合管',
					'PP-B',
				],
				GX_GJ: [
					'全部',
					'110',
					'160',
					'200',
					'300',
					'400',
					'500',
					'600',
					'700',
					'800',
					'900',
					'1000',
				],
				GX_GK: [
					'全部',
					'200×200',
					'300×300',
					'400×400',
					'500×500',
					'600×600',
					'800×800',
					'1000×1000',
				],
				GX_DataSourceName: 'weiweiGIS110',
				GX_DataSetName: 'gsGX',
				JD_DataSourceName: 'weiweiGIS110',
				JD_DataSetName: 'gsGD',
				SP_Min: '1.00',
				CZ_Min: '0.11',
				QUERY_BufferDistance: '1',
				GX_Datas: [
					{
						id: 'waterLine',
						name: '供水管线',
						dataSourceName: 'weiweiGIS110',
						dataSetName: 'gsGX',
						tableName: 'SMDTV_5',
						dataType: 'line',
						showZoom: 0,
						cols: 'SMID:实体编号,BSM:管段编号,QSDH:起始点号,ZDDH:终点点号,CZ:材质,GJ:管径(MM),QDMS:起点埋深(M),ZDMS:终点埋深(M),CD:长度(M),DZMS:地址描述,LRRQ:录入日期,MSRQ:埋设日期,MSFS:埋设方式,GCBH:工程编号,ZCBH:资产编号,QSDW:权属单位,CQBH:测区编号,TCDW:探测单位,BZ:备注,FLDM:分类代码,TZBM:特征编码,ENABLED:是否可用,YL:压力,LX:流向',
					},
					{
						id: 'waterPoint',
						name: '管网节点',
						dataSourceName: 'weiweiGIS110',
						dataSetName: 'dvJD',
						tableName: 'SMDTV_9',
						dataType: 'point',
						showZoom: 15,
						cols: 'SMID:实体编号,BSM:管点编号,FSW:附属物,TZ:特征,CZ:材质,GG:规格,DMGC:地面高程(M),DINGGC:管顶高程(M),MS:埋深(M),X:X坐标,Y:Y坐标,TFH:图幅号,DZMS:地址描述,LRRQ:录入日期,MSRQ:埋设日期,MSFS:埋设方式,QSDW:权属单位,SSBH:设施编号,XH:型号,BZ:备注,CQBH:测区编号,WTH:物探号,FLDM:分类代码,YL:压力,DMT:多媒体',
					},
					{
						id: 'xfsPoint',
						name: '消防栓',
						dataSourceName: 'weiweiGIS110',
						dataSetName: 'dvXFS',
						tableName: 'SMDTV_11',
						dataType: 'point',
						showZoom: 15,
						cols: 'SMID:实体编号,BSM:管点编号,FSW:附属物,TZ:特征,CZ:材质,GG:规格,DMGC:地面高程(M),DINGGC:管顶高程(M),MS:埋深(M),X:X坐标,Y:Y坐标,TFH:图幅号,DZMS:地址描述,LRRQ:录入日期,MSRQ:埋设日期,MSFS:埋设方式,QSDW:权属单位,SSBH:设施编号,XH:型号,BZ:备注,CQBH:测区编号,WTH:物探号,FLDM:分类代码,YL:压力,DMT:多媒体',
					},
					{
						id: 'fmPoint',
						name: '阀门',
						dataSourceName: 'weiweiGIS110',
						dataSetName: 'dvFM',
						tableName: 'SMDTV_10',
						dataType: 'point',
						showZoom: 15,
						cols: 'SMID:实体编号,BSM:管点编号,FSW:附属物,TZ:特征,CZ:材质,GG:规格,DMGC:地面高程(M),DINGGC:管顶高程(M),MS:埋深(M),X:X坐标,Y:Y坐标,TFH:图幅号,DZMS:地址描述,LRRQ:录入日期,MSRQ:埋设日期,MSFS:埋设方式,QSDW:权属单位,SSBH:设施编号,XH:型号,BZ:备注,CQBH:测区编号,WTH:物探号,FLDM:分类代码,YL:压力,DMT:多媒体',
					},
					{
						id: 'waterMeter',
						name: '水表',
						dataSourceName: 'weiweiGIS110',
						dataSetName: 'dvSB',
						tableName: 'SMDTV_15',
						dataType: 'point',
						showZoom: 15,
						cols: 'SMID:实体编号,BSM:管点编号,FSW:附属物,TZ:特征,CZ:材质,GG:规格,DMGC:地面高程(M),DINGGC:管顶高程(M),MS:埋深(M),X:X坐标,Y:Y坐标,TFH:图幅号,DZMS:地址描述,LRRQ:录入日期,MSRQ:埋设日期,MSFS:埋设方式,QSDW:权属单位,SSBH:设施编号,XH:型号,BZ:备注,CQBH:测区编号,WTH:物探号,FLDM:分类代码,YL:压力,DMT:多媒体',
					},
					{
						id: 'jyzPoint',
						name: '加压站',
						dataSourceName: 'weiweiGIS110',
						dataSetName: 'dvJY',
						tableName: 'SMDTV_28',
						dataType: 'point',
						showZoom: 15,
						cols: 'SMID:实体编号,BSM:管点编号,FSW:附属物,TZ:特征,CZ:材质,GG:规格,DMGC:地面高程(M),DINGGC:管顶高程(M),MS:埋深(M),X:X坐标,Y:Y坐标,TFH:图幅号,DZMS:地址描述,LRRQ:录入日期,MSRQ:埋设日期,MSFS:埋设方式,QSDW:权属单位,SSBH:设施编号,XH:型号,BZ:备注,CQBH:测区编号,WTH:物探号,FLDM:分类代码,YL:压力,DMT:多媒体',
					},
					{
						id: 'pqfPoint',
						name: '排气阀',
						dataSourceName: 'weiweiGIS110',
						dataSetName: 'dvPQF',
						tableName: 'SMDTV_17',
						dataType: 'point',
						showZoom: 15,
						cols: 'SMID:实体编号,BSM:管点编号,FSW:附属物,TZ:特征,CZ:材质,GG:规格,DMGC:地面高程(M),DINGGC:管顶高程(M),MS:埋深(M),X:X坐标,Y:Y坐标,TFH:图幅号,DZMS:地址描述,LRRQ:录入日期,MSRQ:埋设日期,MSFS:埋设方式,QSDW:权属单位,SSBH:设施编号,XH:型号,BZ:备注,CQBH:测区编号,WTH:物探号,FLDM:分类代码,YL:压力,DMT:多媒体',
					},
					{
						id: 'cldPoint',
						name: '流量监测点',
						dataSourceName: 'weiweiGIS110',
						dataSetName: 'dvLL',
						tableName: 'SMDTV_13',
						dataType: 'point',
						showZoom: 15,
						cols: 'SMID:实体编号,BSM:管点编号,FSW:附属物,TZ:特征,CZ:材质,GG:规格,DMGC:地面高程(M),DINGGC:管顶高程(M),MS:埋深(M),X:X坐标,Y:Y坐标,TFH:图幅号,DZMS:地址描述,LRRQ:录入日期,MSRQ:埋设日期,MSFS:埋设方式,QSDW:权属单位,SSBH:设施编号,XH:型号,BZ:备注,CQBH:测区编号,WTH:物探号,FLDM:分类代码,YL:压力,DMT:多媒体',
					},
					{
						id: 'cydPoint',
						name: '压力监测点',
						dataSourceName: 'weiweiGIS110',
						dataSetName: 'dvYL',
						tableName: 'SMDTV_12',
						dataType: 'point',
						showZoom: 15,
						cols: 'SMID:实体编号,BSM:管点编号,FSW:附属物,TZ:特征,CZ:材质,GG:规格,DMGC:地面高程(M),DINGGC:管顶高程(M),MS:埋深(M),X:X坐标,Y:Y坐标,TFH:图幅号,DZMS:地址描述,LRRQ:录入日期,MSRQ:埋设日期,MSFS:埋设方式,QSDW:权属单位,SSBH:设施编号,XH:型号,BZ:备注,CQBH:测区编号,WTH:物探号,FLDM:分类代码,YL:压力,DMT:多媒体',
					},
					{
						id: 'szdPoint',
						name: '水质监测点',
						dataSourceName: 'weiweiGIS110',
						dataSetName: 'dvSZ',
						tableName: 'SMDTV_14',
						dataType: 'point',
						showZoom: 15,
						cols: 'SMID:实体编号,BSM:管点编号,FSW:附属物,TZ:特征,CZ:材质,GG:规格,DMGC:地面高程(M),DINGGC:管顶高程(M),MS:埋深(M),X:X坐标,Y:Y坐标,TFH:图幅号,DZMS:地址描述,LRRQ:录入日期,MSRQ:埋设日期,MSFS:埋设方式,QSDW:权属单位,SSBH:设施编号,XH:型号,BZ:备注,CQBH:测区编号,WTH:物探号,FLDM:分类代码,YL:压力,DMT:多媒体',
					},
					{
						id: 'scPoint',
						name: '水厂',
						dataSourceName: 'weiweiGIS110',
						dataSetName: 'dvSC',
						tableName: 'SMDTV_16',
						dataType: 'point',
						showZoom: 15,
						cols: 'SMID:实体编号,BSM:管点编号,FSW:附属物,TZ:特征,CZ:材质,GG:规格,DMGC:地面高程(M),DINGGC:管顶高程(M),MS:埋深(M),X:X坐标,Y:Y坐标,TFH:图幅号,DZMS:地址描述,LRRQ:录入日期,MSRQ:埋设日期,MSFS:埋设方式,QSDW:权属单位,SSBH:设施编号,XH:型号,BZ:备注,CQBH:测区编号,WTH:物探号,FLDM:分类代码,YL:压力,DMT:多媒体',
					},
				],
				ImgCLD: require('./images/style/cld.png'),
				ImgCYD: require('./images/style/cyd.png'),
				ImgFM: require('./images/style/fm.png'),
				ImgJYZ: require('./images/style/jyz.png'),
				ImgPQF: require('./images/style/pqf.png'),
				ImgSB: require('./images/style/sb.png'),
				ImgSC: require('./images/style/sc.png'),
				ImgSZD: require('./images/style/szd.png'),
				ImgXFS: require('./images/style/xfs.png'),
				markerIcon: L.icon({
					iconUrl: require('leaflet/dist/images/marker-icon.png'),
					iconSize: [25, 41],
					iconAnchor: [13, 41],
				}),
				map: undefined,
				mapLayer: undefined,
				lableLayer: undefined,
				crsProj: undefined,
				FTFX_MINS: undefined,
				layerStyles: undefined,
				allLayers: undefined,
				maps: undefined,
				// panels: undefined,
				utils: undefined,
				resultLayer: undefined,
				TempLayer: undefined,
				subLayers: undefined,
				plotting: undefined,
				plottingLayer: undefined,
				drawMapControl: undefined,
				drawLayer: undefined,
				drawType: undefined,
			}
		},
		created() {
			// created 在模板渲染成html前调用，即通常初始化某些属性值，然后再渲染成视图

			// 覆土分析标准埋深
			this.FTFX_MINS = new Map([
				['PE', 0.7],
				['铸铁', 0.7],
				['PVC', 1.0],
				['砼', 1.0],
				['钢', 1.0],
				['PPR', 1.0],
			])
			// 各个图层的样式
			this.layerStyles = new Map()
			// 节点样式
			var waterPointStyle = L.supermap.circleStyle({
				color: '#953716',
				fill: true,
				fillColor: 'green',
			})
			this.layerStyles.set('waterPoint', waterPointStyle)
			var imgNew = new Image()
			imgNew.src = this.ImgXFS
			this.layerStyles.set('xfsPoint', L.supermap.imageStyle({ img: imgNew }))
			imgNew = new Image()
			imgNew.src = this.ImgFM
			this.layerStyles.set('fmPoint', L.supermap.imageStyle({ img: imgNew }))
			imgNew = new Image()
			imgNew.src = this.ImgSB
			this.layerStyles.set('waterMeter', L.supermap.imageStyle({ img: imgNew }))
			imgNew = new Image()
			imgNew.src = this.ImgJYZ
			this.layerStyles.set('jyzPoint', L.supermap.imageStyle({ img: imgNew }))
			imgNew = new Image()
			imgNew.src = this.ImgPQF
			this.layerStyles.set('pqfPoint', L.supermap.imageStyle({ img: imgNew }))
			imgNew = new Image()
			imgNew.src = this.ImgCLD
			this.layerStyles.set('cldPoint', L.supermap.imageStyle({ img: imgNew }))
			imgNew = new Image()
			imgNew.src = this.ImgCYD
			this.layerStyles.set('cydPoint', L.supermap.imageStyle({ img: imgNew }))
			imgNew = new Image()
			imgNew.src = this.ImgSC
			this.layerStyles.set('scPoint', L.supermap.imageStyle({ img: imgNew }))
			imgNew = new Image()
			imgNew.src = this.ImgSZD
			this.layerStyles.set('szdPoint', L.supermap.imageStyle({ img: imgNew }))

			proj4.defs(
				'EPSG:4549',
				'+proj=tmerc +lat_0=0 +lon_0=120 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs'
			)
			this.crsProj = L.Proj.CRS('EPSG:4549')
			this.allLayers = new Map()
		},
		methods: {
			// methods 编写js函数
			clickQuery() { },
			layerCtrl() {
				that.clearLays();
				panels.openLayerTreePanel();
			},
			measureDistance() {
				that.clearLays();
				that.map.off('click');
				that.map.off('dblclick');
				$('#tips').css('display', 'block');

				var isFirstPoint = true; //判断是否是起始点
				var latLngTemp = null; //存储上一点击点临时变量
				var resultDis = 0;//总距
				that.map.on('click', function (ev) {
					that.TempLayer.clearLayers();
					$('#tips').css('display', 'none')
					var polyLine
					if (isFirstPoint) {
						L.marker([ev.latlng.lat, ev.latlng.lng], {
							icon: that.markerIcon,
						}).addTo(that.resultLayer) //起始点
						var texticon = L.divIcon({
							//定义图标
							html: '起点',
							iconSize: [30, 20],
							iconAnchor: [15, 0],
						})
						L.marker([ev.latlng.lat, ev.latlng.lng], { icon: texticon }).addTo(
							that.resultLayer
						) //marker实现文本框显示

						latLngTemp = ev.latlng //存储上一点击点
						isFirstPoint = false
					} else {
						if (!latLngTemp.equals(ev.latlng)) {
							//避免出现结束双击，导致距离为0
							polyLine = L.polyline(
								[
									//与上一点连线
									[latLngTemp.lat, latLngTemp.lng],
									[ev.latlng.lat, ev.latlng.lng],
								],
								{
									color: 'red',
								}
							)

							that.resultLayer.addLayer(polyLine)
							L.marker([ev.latlng.lat, ev.latlng.lng], {
								icon: that.markerIcon,
							}).addTo(that.resultLayer) // 最后点击点经纬度

							var from = turf.point([latLngTemp.lng, latLngTemp.lat])
							var to = turf.point([ev.latlng.lng, ev.latlng.lat])
							var options = { units: 'kilometers' }
							var jl11 = turf.distance(from, to, options) * 1000

							latLngTemp = ev.latlng //更新临时变量为新点

							resultDis += jl11
							// 距离根据地图单位进行换算成米或者千米
							var content =
								'距上点：' +
								Number(jl11).toFixed(2) +
								'米' +
								'<br>总距：' +
								Number(resultDis).toFixed(2) +
								'米'
							var texticon = L.divIcon({
								html: content,
								iconSize: [110, 40],
								iconAnchor: [55, -5], //设置标签偏移避免遮盖
							})
							L.marker([ev.latlng.lat, ev.latlng.lng], {
								icon: texticon,
							}).addTo(that.resultLayer)
							that.TempLayer.clearLayers()
						}
					}
					that.map.on('mousemove', function (ev) {
						that.TempLayer.clearLayers()
						var TempLine = L.polyline(
							[
								//虚线临时线段
								[latLngTemp.lat, latLngTemp.lng],
								[ev.latlng.lat, ev.latlng.lng],
							],
							{
								color: 'red',
								dashArray: '5,5',
							}
						)
						that.TempLayer.addLayer(TempLine)

						// 对坐标系进行转换
						var pt1 = that.crsProj.project(latLngTemp)
						var pt2 = that.crsProj.project(ev.latlng)
						var TempLineDis = L.polyline([
							//与上一点连线
							[pt1.y, pt1.x],
							[pt2.y, pt2.x],
						])
						var from = turf.point([latLngTemp.lng, latLngTemp.lat])
						var to = turf.point([ev.latlng.lng, ev.latlng.lat])
						var options = { units: 'kilometers' }
						var jl11 = turf.distance(from, to, options) * 1000

						var texticon = L.divIcon({
							html: Number(jl11).toFixed(2) + '米',
							iconSize: 90,
							className: 'my-div-icon',
							iconAnchor: [45, -5],
						})
						L.marker([ev.latlng.lat, ev.latlng.lng], {
							icon: texticon,
						}).addTo(that.TempLayer)
					})
				})
				that.map.on('dblclick', function (ev) {
					that.map.off('click')
					that.map.off('dblclick')
					that.map.off('mousemove')
				})
			},
			measureArea() {
				that.drawType = 'measureArea'
				// 创建绘制控件，并启用
				var handler = new L.Draw.Polygon(that.map)
				handler.enable()

				that.map.on(L.Draw.Event.CREATED, function (e) {
					if (that.drawType != 'measureArea') {
						return
					}
					var type = e.layerType,
						layer = e.layer
					if (type === 'marker') {
						layer.bindPopup('A popup!')
					}

					//将图形信息传给下一步，进行查询功能
					var locationArray = e.layer.getLatLngs()[0]
					var polygonArray = Array()
					var turfPolygonArray = Array()
					var midArray = Array()
					var turfMidArray = Array()
					var firstX = locationArray[0].lat
					var firstY = locationArray[0].lng

					for (var i = 0; i < locationArray.length; i++) {
						var x = locationArray[i].lat
						var y = locationArray[i].lng
						midArray.push(x)
						midArray.push(y)
						turfMidArray.push(y)
						turfMidArray.push(x)
						polygonArray.push(midArray)
						turfPolygonArray.push(turfMidArray)
						midArray = Array()
						turfMidArray = Array()
					}
					midArray.push(firstX)
					midArray.push(firstY)
					turfMidArray.push(firstY)
					turfMidArray.push(firstX)
					polygonArray.push(midArray)
					turfPolygonArray.push(turfMidArray)

					var polygon = L.polygon(polygonArray, { color: '#00FF00' })

					var polygonTurf = turf.polygon([turfPolygonArray])
					var area = turf.area(polygonTurf)

					that.resultLayer.addLayer(polygon)

					var content = '面积：' + Number(area).toFixed(2) + '平方米'
					polygon.bindPopup(content).openPopup(polygon.getCenter())
				})
			},
			clearLays() {
				this.resultLayer.clearLayers()
				this.TempLayer.clearLayers()
				// this.plottingLayer.removeFeatures(drawLayer);
			},
			loadLayerTrees() {
				// 添加地图服务
				that.map = L.map('cesiumContainer', {
					preferCanvas: true,
					center: [45.507908, 124.290565],
					zoom: 14,
					crs: L.CRS.EPSG4326,
				}) //TianDiTu_WGS84
				that.mapLayer = L.supermap.tiandituTileLayer({
					key: 'f988d9c24e2e2d432266d5578ffbc1b0',
					attribution: '',
				})
				that.map.addLayer(that.mapLayer)
				var lableLayer = L.supermap.tiandituTileLayer({
					isLabel: true,
					key: 'f988d9c24e2e2d432266d5578ffbc1b0',
					attribution: '',
				})
				that.map.addLayer(lableLayer)

				var thisLayer = {}
				thisLayer.layer = this.mapLayer
				thisLayer.isShow = true
				that.allLayers.set('baseMap', thisLayer)

				var lyrs = that.GX_Datas
				for (var index = 0; index < lyrs.length; index++) {
					var lyr = lyrs[index]
					var lyrid = lyr.id
					var dataSourceName = lyr.dataSourceName
					var dataSetName = lyr.dataSetName
					that.addLayerData(dataSourceName, dataSetName, lyrid, '')
				}

				// // 添加鹰眼
				// var osm2 = L.supermap.tiandituTileLayer({ key: '1d109683f4d84198e37a38c442d68311' });
				// L.control.minimap(osm2, {mapOptions: { logoControl: false}, toggleDisplay: true}).addTo(this.map);

				// 添加比例尺
				//L.control.scale({ imperial: false }).addTo(this.map);

				// 启动绘制功能
				this.InitDraw()

				that.map.on('zoomend', function (e) {
					var nowZoom = e.target.getZoom()
					var lyrs = that.GX_Datas
					for (var index = 0; index < lyrs.length; index++) {
						var lyr = lyrs[index]
						var layId = lyr.id
						var showZoom = lyr.showZoom
						if (showZoom === undefined || showZoom === 0) {
							continue
						}
						var thisLayer = that.allLayers.get(layId)
						var isShow = thisLayer.isShow
						var layTmp = thisLayer.layer
						if (nowZoom >= showZoom) {
							if (isShow && !that.map.hasLayer(layTmp)) {
								that.map.addLayer(layTmp)
							}
						} else {
							if (isShow && that.map.hasLayer(layTmp)) {
								that.map.removeLayer(layTmp)
							}
						}
					}
					that.map.invalidateSize(true)
				})

				that.resultLayer = L.featureGroup().addTo(that.map)
				that.TempLayer = L.featureGroup().addTo(that.map)

				$('body').append("<div id='layerTree' ></div>")
				let openThePanel = function () {
					if ($('#layerTree').html().length > 0) {
						that.panelsloadLayerTreePanelByDom('layerTree')
						return
					}
					that.panelsloadLayerTreePanelByDom('layerTree', function () {
						var allLayersTemp = []
						for (var index = 0; index < lyrs.length; index++) {
							var lyr = lyrs[index]
							var nodeLayerInScene = {
								title: lyr.name,
								id: lyr.id,
								layer: lyr,
								checked: true,
							}
							allLayersTemp.push(nodeLayerInScene)
						}
						var nodeLayerInScene = {
							title: '地图服务',
							id: 'baseMap',
							layer: that.mapLayer,
							checked: true,
						}
						allLayersTemp.push(nodeLayerInScene)

						layui.use('tree', function () {
							const tree = layui.tree
							tree.render({
								elem: '#layerTree',
								data: allLayersTemp,
								showCheckbox: true,
								showLine: true,
								oncheck: function (obj) {
									var layId = obj.data.id
									var thisLayer = that.allLayers.get(layId)
									var layTmp = thisLayer.layer
									if (obj.checked) {
										if (!that.map.hasLayer(layTmp)) {
											that.map.addLayer(layTmp)
											thisLayer.isShow = true
											that.allLayers.set(layId, thisLayer)
											if (layId == 'baseMap' && lableLayer != null) {
												that.map.addLayer(lableLayer)
											}
										}
									} else {
										if (that.map.hasLayer(layTmp)) {
											that.map.removeLayer(layTmp)
											thisLayer.isShow = false
											that.allLayers.set(layId, thisLayer)
											if (layId == 'baseMap' && lableLayer != null) {
												that.map.removeLayer(lableLayer)
											}
										}
									}
									// 重新指定一下中心点，解决不刷新图层的问题
									that.map.panTo(that.map.getCenter())
								},
							})
						})
					})
				}
				panels.openLayerTreePanel = openThePanel
			},
			panelsloadLayerTreePanelByDom(domID, callback) {
				layui.use('layer', function () {
					const layer = layui.layer
					panels.layerTreePanelIndex = layer.open({
						anim: 3,
						id: 'layerTreePanel',
						area: '280px',
						title: ['全部图层', 'font-size:14px;'],
						offset: ['65px', that.panelsSideWidth() + 5 + 'px'],
						shade: 0,
						type: 1,
						content: $('#' + domID), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
						cancel: function () { },
						success: function (layero, index) { },
					})
					if (callback != undefined) {
						callback()
					}
				})
			},
			panelsSideWidth() {
				return $('.layui-side').width()
			},
			addLayerData(dataSourceName, dataSetName, lyrid, showCss) {
				// var that = this;
				that.queryBySql(
					dataSetName,
					dataSourceName,
					'SmID > 0',
					0,
					2000000,
					'',
					function (rs) {
						if (rs.result === undefined) return
						var result = L.Util.transform(
							rs.result.features,
							that.crsProj,
							L.CRS.EPSG4326
						)
						var rsLayer
						var thisLayer = {}
						if (lyrid === 'waterLine') {
							rsLayer = L.geoJSON(result, { style: { color: '#070af3' } })
							that.map.addLayer(rsLayer)
						} else {
							var circleStyle = that.layerStyles.get(lyrid)
							var graphics = []
							// 设置每个点的经纬度和传入样式
							for (var i = 0; i < result.features.length; i++) {
								var feature = result.features[i]
								var coordinates = feature.geometry.coordinates
								var pointVector = L.supermap.graphic({
									id: i + 1,
									latLng: L.latLng(coordinates[1], coordinates[0]),
									style: circleStyle.getStyle(),
								})
								graphics.push(pointVector)
							}
							// 将管点要素画在地图上
							//rsLayer = L.supermap.graphicLayer(graphics, {render: 'canvas'});
							rsLayer = L.supermap.graphicLayer(graphics)
						}

						thisLayer.layer = rsLayer
						thisLayer.isShow = true
						that.allLayers.set(lyrid, thisLayer)
					}
				)
			},
			InitDraw() { },
			toggleFullScreen() {
				var el = document.body
				var isFullscreen =
					document.fullScreen ||
					document.mozFullScreen ||
					document.webkitIsFullScreen
				if (!isFullscreen) {
					//进入全屏,多重短路表达式
					; (el.requestFullscreen && el.requestFullscreen()) ||
						(el.mozRequestFullScreen && el.mozRequestFullScreen()) ||
						(el.webkitRequestFullscreen && el.webkitRequestFullscreen()) ||
						(el.msRequestFullscreen && el.msRequestFullscreen())
				} else {
					//退出全屏,三目运算符
					document.exitFullscreen
						? document.exitFullscreen()
						: document.mozCancelFullScreen
							? document.mozCancelFullScreen()
							: document.webkitExitFullscreen
								? document.webkitExitFullscreen()
								: ''
				}
			},
			// #region queryBySql queryByBounds queryByGeometry
			queryBySql(
				datasetName,
				wsName,
				sql,
				fromIndex,
				toIndex,
				aggregations,
				callback
			) {
				var sqlParam = new this.$mapclent.GetFeaturesBySQLParameters({
					queryParameter: {
						name: datasetName + '@' + wsName,
						attributeFilter: sql,
					},
					datasetNames: [wsName + ':' + datasetName],
					fromIndex: fromIndex,
					toIndex: toIndex,
					maxFeatures: toIndex,
				})
				L.supermap
					.featureService(this.GX_Datas_BaseUrl)
					.getFeaturesBySQL(sqlParam, function (sr) {
						if (callback === undefined) return
						else callback(sr)
					})
			},
			queryByBounds(title, datasetName, wsName, bounds, callback) {
				var paramsTmp = {}
				paramsTmp.title = title
				paramsTmp.dataSetName = datasetName
				paramsTmp.dataSourceName = wsName
				var geometryParam = new this.$mapclent.GetFeaturesByGeometryParameters({
					datasetNames: [wsName + ':' + datasetName],
					geometry: bounds,
					spatialQueryMode: 'INTERSECT',
				})
				L.supermap
					.featureService(this.GX_Datas_BaseUrl)
					.getFeaturesByGeometry(geometryParam, function (serviceResult) {
						if (callback !== undefined) {
							callback(serviceResult, paramsTmp)
						}
					})
			},
			queryByGeometry(
				title,
				distanceTmp,
				datasetName,
				wsName,
				geometry,
				callback
			) {
				var paramsTmp = {}
				paramsTmp.title = title
				paramsTmp.dataSetName = datasetName
				paramsTmp.dataSourceName = wsName
				if (distanceTmp === undefined) {
					distanceTmp = this.QUERY_BufferDistance
				}
				var bufferParam = new this.$mapclent.GetFeaturesByBufferParameters({
					datasetNames: [wsName + ':' + datasetName],
					bufferDistance: distanceTmp,
					geometry: geometry,
				})
				L.supermap
					.featureService(this.GX_Datas_BaseUrl)
					.getFeaturesByBuffer(bufferParam, function (serviceResult) {
						if (callback !== undefined) {
							callback(serviceResult, paramsTmp)
						}
					})
			},
			// #endregion
		},

		mounted() {
			// mounted在模板渲染成html后调用，通常是初始化页面完成后，再对html的dom节点进行一些需要的操作
			window.that = this
			layui.use(['layer'], function () {
				let layer = layui.layer
				layer.config({
					extend: 'cool/cool.css',
					skin: 'layui-ext-coolskin',
				})
			})
			this.loadLayerTrees()
			setTimeout(() => {
				this.map.invalidateSize(true)
			}, 1000)
		},
	}
</script>
<style scoped>
	@import url(css/styles.css);
</style>
