<script setup>
	/**
	 * element-plus组件
	 */
	import {
		ElMessage
	} from 'element-plus';

	import {
		inject
	} from "vue";
	import {
		Store
	} from '@/store/index'
	store = Store()
	import {
		deepTree
	} from "@/utils/deepTree.js";

	const getMapInstance = inject("getMapInstance");
	jt3d = getMapInstance();
</script>

<template>
	<div class="jt-ImageLayerSplit">
		<div class="_left">
			<div style="line-height: 30rem;float: left;">左侧图层：</div>
			<el-tree-select v-model="leftValue" :data="leftData" :render-after-expand="true" @change="handleClickLeft" style="width: 160rem; float: left;" />
		</div>
		<div class="_right">
			<div style="line-height: 30rem;float: left;">右侧图层：</div>
			<el-tree-select v-model="rightValue" :data="rightData" :render-after-expand="true" @change="handleClickRight" style="width: 160rem; float: left;" />
		</div>
	</div>
</template>

<script>
	let jt3d = undefined;
	let store = undefined;

	let earthAtLeft = undefined;
	let earthAtRight = undefined;

	//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
	//例如：import 《组件名称》 from '《组件路径》';

	export default {
		//import引入的组件需要注入到对象中才能使用
		components: {},

		//这里存放数据
		data() {

			return {
				leftValue: {},
				leftData: [],
				rightValue: {},
				rightData: [],
			};
		},

		//监听属性 类似于data概念
		computed: {},

		//监控data中的数据变化
		watch: {},

		//方法集合
		methods: {
			/**
			 * 左侧图层控制
			 * @param {Object} data
			 */
			handleClickLeft(data) {
				let _self = this;

				let _serviceId = "service_" + data.layercode + data.layerorder;
				let layername = data.layername;
				let layertype = data.layertype;

				//透明度
				let _opacity = null;
				if (data.opacity == null) {
					_opacity = 1;
				} else {
					_opacity = Number(data.opacity);
					data.opacity = _opacity;

					if (_opacity == 0) {
						_opacity = 1;
					}
				}

				//参数集
				let parameterset = data.parameterset;
				if (data.parameterset instanceof Object) {
					parameterset = data.parameterset;
				} else if (data.parameterset != "" && data.parameterset != null && data.parameterset != undefined) {
					parameterset = JSON.parse(data.parameterset);
				}

				//设置参数
				let _options = {
					id: _serviceId,
					alpha: _opacity
				}

				this.removeSplitLayerLeft();

				switch (data.loadtype) {
					case "UrlTemplateImageryProvider": //加载URL模板服务

						//设置参数
						_options.url = data.datasource;
						if (parameterset) {
							if (parameterset.CRS) { //坐标系
								_options.CRS = parameterset.CRS;
							}
							if (parameterset.minimumLevel) { //最小层级
								_options.minimumLevel = parameterset.minimumLevel;
							}
							if (parameterset.maximumLevel) { //最大层级
								_options.maximumLevel = parameterset.maximumLevel;
							}
						}

						jt3d.layer.addUrlTemplateImagery(_options, function(serviceId) {
							earthAtLeft = window[_serviceId];
							earthAtLeft.splitDirection = Cesium.SplitDirection.LEFT;
						});
						break;
					case "WebMapTileServiceImageryProvider": // WMTS地图服务

						//设置参数
						_options.url = data.datasource;
						if (parameterset) {
							if (parameterset.layers) { //WMTS请求的层名
								_options.layers = parameterset.layers;

								if (parameterset.style) { //WMTS请求的样式名
									_options.style = parameterset.style;

									if (parameterset.tileMatrixSetID) { //用于WMTS请求的TileMatrixSet的标识符
										_options.tileMatrixSetID = parameterset.tileMatrixSetID;

										if (parameterset.minimumLevel) { //最小层级
											_options.minimumLevel = parameterset.minimumLevel;
										}
										if (parameterset.maximumLevel) { //最大层级
											_options.maximumLevel = parameterset.maximumLevel;
										}

										jt3d.layer.addWebMapTileService(_options, function(serviceId) {
											earthAtLeft = window[_serviceId];
											earthAtLeft.splitDirection = Cesium.SplitDirection.LEFT;
										});

									} else {
										ElMessage("请检测图层表parameterset字段是否设置tileMatrixSetID");
									}

								} else {
									ElMessage("请检测图层表parameterset字段是否设置style");
								}

							} else {
								ElMessage("请检测图层表parameterset字段是否设置layers");
							}
						} else {
							ElMessage("请检测图层表parameterset字段是否设置layers,style,tileMatrixSetID");
						}
						break;
					case "WebMapServiceImageryProvider": //WMS地图服务

						//设置参数
						_options.url = data.datasource;
						if (parameterset) {
							if (parameterset.layers) { //WMTS请求的层名
								_options.layers = parameterset.layers;

								if (parameterset.minimumLevel) { //最小层级
									_options.minimumLevel = parameterset.minimumLevel;
								}
								if (parameterset.maximumLevel) { //最大层级
									_options.maximumLevel = parameterset.maximumLevel;
								}

								jt3d.layer.addWebMapService(_options, function(serviceId) {
									earthAtLeft = window[_serviceId];
									earthAtLeft.splitDirection = Cesium.SplitDirection.LEFT;
								});
							} else {
								ElMessage("请检测图层表parameterset字段是否设置layers");
							}
						} else {
							ElMessage("请检测图层表parameterset字段是否设置layers");
						}

						break;
					case "ArcGisMapServerImageryProvider": // ArcGIS Online和Server的相关服务

						//设置参数
						_options.url = data.datasource;
						if (parameterset) {
							if (parameterset.layers) {
								_options.layers = parameterset.layers;
							}
						}

						//加载服务
						jt3d.layer.addArcGisMapServer(_options, function(serviceId) {
							earthAtLeft = window[_serviceId];
							earthAtLeft.splitDirection = Cesium.SplitDirection.LEFT;
						})

						break;
					case "TileMapServiceImageryProvider": // 2.5维度地图

						//设置参数
						_options.url = data.datasource;
						if (parameterset) {
							if (parameterset.minimumLevel) { //最小层级
								_options.minimumLevel = parameterset.minimumLevel;
							}
							if (parameterset.maximumLevel) { //最大层级
								_options.maximumLevel = parameterset.maximumLevel;
							}
						}

						jt3d.layer.addTileMapServiceImagery(_options, function(serviceId) {
							earthAtLeft = window[_serviceId];
							earthAtLeft.splitDirection = Cesium.SplitDirection.LEFT;
						});

						break;
					case "Cesium3DTileset": //加载3DTileset地图服务--实景

						let Tiles = [];

						let datasource = data.datasource.split("#")
						console.log('datasource', datasource)

						//加载实景
						datasource.forEach((res, index) => {
							//设置参数
							let _options = {
								id: _serviceId + index,
								url: res,
							}
							if (parameterset) {
								if (parameterset.height) {
									_options.height = parameterset.height;
								}
								if (parameterset.alpha) {
									_options.alpha = parameterset.alpha;
								}
							}

							jt3d.layer.addCesium3DTileset(_options, function(serviceId) {

								window[_serviceId + index] = window[serviceId];

								window[_serviceId + index].splitDirection = Cesium.SplitDirection.LEFT;

								Tiles.push(window[_serviceId + index]);
							});

							if (index === (datasource.length - 1)) {
								earthAtLeft = Tiles;
							}
						})
						break;
					case "Cesium3DTileset_BM": //加载3DTileset地图服务--白膜

						//设置参数
						_options.url = data.datasource;
						if (parameterset) {
							if (parameterset.color) {
								_options.color = parameterset.color;
							}
						}

						//加载白膜
						jt3d.layer.addCesium3DTilesetBm(_options, function(serviceId) {
							earthAtLeft = window[_serviceId];
							earthAtLeft.splitDirection = Cesium.SplitDirection.LEFT;
						});

						break;
					default:
						break;
				}
			},
			/**
			 * 
			 * 
			 * 右侧图层控制
			 * @param {Object} data
			 */
			handleClickRight(data) {
				let _self = this;

				let _serviceId = "service_" + data.layercode + data.layerorder;
				let layername = data.layername;
				let layertype = data.layertype;

				//透明度
				let _opacity = null;
				if (data.opacity == null) {
					_opacity = 1;
				} else {
					_opacity = Number(data.opacity);
					data.opacity = _opacity;

					if (_opacity == 0) {
						_opacity = 1;
					}
				}

				//参数集
				let parameterset = data.parameterset;
				if (data.parameterset instanceof Object) {
					parameterset = data.parameterset;
				} else if (data.parameterset != "" && data.parameterset != null && data.parameterset != undefined) {
					parameterset = JSON.parse(data.parameterset);
				}

				//设置参数
				let _options = {
					id: _serviceId,
					alpha: _opacity
				}

				this.removeSplitLayerRight();
				switch (data.loadtype) {
					case "UrlTemplateImageryProvider": //加载URL模板服务

						//设置参数
						_options.url = data.datasource;
						if (parameterset) {
							if (parameterset.CRS) { //坐标系
								_options.CRS = parameterset.CRS;
							}
							if (parameterset.minimumLevel) { //最小层级
								_options.minimumLevel = parameterset.minimumLevel;
							}
							if (parameterset.maximumLevel) { //最大层级
								_options.maximumLevel = parameterset.maximumLevel;
							}
						}

						jt3d.layer.addUrlTemplateImagery(_options, function(serviceId) {
							//设置透明度
							jt3d.layer.setLayersStyle({
								serviceId: serviceId,
								alpha: _opacity
							});

							earthAtRight = window[_serviceId];
							earthAtRight.splitDirection = Cesium.SplitDirection.RIGHT;
						});
						break;
					case "WebMapTileServiceImageryProvider": // WMTS地图服务

						//设置参数
						_options.url = data.datasource;
						if (parameterset) {
							if (parameterset.layers) { //WMTS请求的层名
								_options.layers = parameterset.layers;

								if (parameterset.style) { //WMTS请求的样式名
									_options.style = parameterset.style;

									if (parameterset.tileMatrixSetID) { //用于WMTS请求的TileMatrixSet的标识符
										_options.tileMatrixSetID = parameterset.tileMatrixSetID;

										if (parameterset.minimumLevel) { //最小层级
											_options.minimumLevel = parameterset.minimumLevel;
										}
										if (parameterset.maximumLevel) { //最大层级
											_options.maximumLevel = parameterset.maximumLevel;
										}

										jt3d.layer.addWebMapTileService(_options, function(serviceId) {
											//设置透明度
											jt3d.layer.setLayersStyle({
												serviceId: serviceId,
												alpha: _opacity
											});

											earthAtRight = window[_serviceId];
											earthAtRight.splitDirection = Cesium.SplitDirection.RIGHT;
										});

									} else {
										ElMessage("请检测图层表parameterset字段是否设置tileMatrixSetID");
									}

								} else {
									ElMessage("请检测图层表parameterset字段是否设置style");
								}

							} else {
								ElMessage("请检测图层表parameterset字段是否设置layers");
							}
						} else {
							ElMessage("请检测图层表parameterset字段是否设置layers,style,tileMatrixSetID");
						}
						break;
					case "WebMapServiceImageryProvider": //WMS地图服务

						//设置参数
						_options.url = data.datasource;
						if (parameterset) {
							if (parameterset.layers) { //WMTS请求的层名
								_options.layers = parameterset.layers;

								if (parameterset.minimumLevel) { //最小层级
									_options.minimumLevel = parameterset.minimumLevel;
								}
								if (parameterset.maximumLevel) { //最大层级
									_options.maximumLevel = parameterset.maximumLevel;
								}

								jt3d.layer.addWebMapService(_options, function(serviceId) {
									//设置透明度
									jt3d.layer.setLayersStyle({
										serviceId: serviceId,
										alpha: _opacity
									});

									earthAtRight = window[_serviceId];
									earthAtRight.splitDirection = Cesium.SplitDirection.RIGHT;
								});
							} else {
								ElMessage("请检测图层表parameterset字段是否设置layers");
							}
						} else {
							ElMessage("请检测图层表parameterset字段是否设置layers");
						}

						break;
					case "ArcGisMapServerImageryProvider": // ArcGIS Online和Server的相关服务

						//设置参数
						_options.url = data.datasource;
						if (parameterset) {
							if (parameterset.layers) {
								_options.layers = parameterset.layers;
							}
						}

						//加载服务
						jt3d.layer.addArcGisMapServer(_options, function(serviceId) {
							//设置透明度
							jt3d.layer.setLayersStyle({
								serviceId: serviceId,
								alpha: _opacity
							});

							earthAtRight = window[_serviceId];
							earthAtRight.splitDirection = Cesium.SplitDirection.RIGHT;
						})

						break;
					case "TileMapServiceImageryProvider": // 2.5维度地图

						//设置参数
						_options.url = data.datasource;
						if (parameterset) {
							if (parameterset.minimumLevel) { //最小层级
								_options.minimumLevel = parameterset.minimumLevel;
							}
							if (parameterset.maximumLevel) { //最大层级
								_options.maximumLevel = parameterset.maximumLevel;
							}
						}

						jt3d.layer.addTileMapServiceImagery(_options, function(serviceId) {
							//设置透明度
							jt3d.layer.setLayersStyle({
								serviceId: serviceId,
								alpha: _opacity
							});

							earthAtRight = window[_serviceId];
							earthAtRight.splitDirection = Cesium.SplitDirection.RIGHT;
						});

						break;
					case "Cesium3DTileset": //加载3DTileset地图服务--实景

						let Tiles = [];

						let datasource = data.datasource.split("#")
						console.log('datasource', datasource)

						//加载实景
						datasource.forEach((res, index) => {
							//设置参数
							let _options = {
								id: _serviceId + index,
								url: res,
							}
							if (parameterset) {
								if (parameterset.height) {
									_options.height = parameterset.height;
								}
								if (parameterset.alpha) {
									_options.alpha = parameterset.alpha;
								}
							}

							jt3d.layer.addCesium3DTileset(_options, function(serviceId) {

								window[_serviceId + index] = window[serviceId];

								window[_serviceId + index].splitDirection = Cesium.SplitDirection.RIGHT;

								Tiles.push(window[_serviceId + index]);
							});

							if (index === (datasource.length - 1)) {
								earthAtRight = Tiles;
							}
						})
						break;
					case "Cesium3DTileset_BM": //加载3DTileset地图服务--白膜

						//设置参数
						_options.url = data.datasource;
						if (parameterset) {
							if (parameterset.color) {
								_options.color = parameterset.color;
							}
						}

						//加载白膜
						jt3d.layer.addCesium3DTilesetBm(_options, function(serviceId) {
							earthAtRight = window[_serviceId];
							earthAtRight.splitDirection = Cesium.SplitDirection.RIGHT;
						});

						break;
					default:
						break;
				}
			},

			/**
			 * 卷帘对比初始化
			 */
			initSplitLayer() {
				let _self = this;
				this.viewer = jt3d._viewer;

				let sliderDiv = document.getElementById("image_slider");
				if (sliderDiv == null) {
					//创建画布
					sliderDiv = document.createElement('div');
					sliderDiv.id = "image_slider";
					sliderDiv.style.position = "absolute";
					sliderDiv.style.left = "50%";
					sliderDiv.style.top = "70rem";
					sliderDiv.style.backgroundColor = "#d3d3d3";
					sliderDiv.style.width = "5rem";
					sliderDiv.style.height = "calc(100% - 70rem)";
					sliderDiv.style.zIndex = "9999";

					sliderDiv.onmouseover = function() {
						//设置其背景颜色为黄色
						this.style.cursor = "ew-resize";
					};

					/* 加入到页面 */
					document.body.appendChild(sliderDiv);
				}

				// 设置图像拆分位置
				viewer.scene.splitPosition = sliderDiv.offsetLeft / sliderDiv.parentElement.offsetWidth; //确定分割点位置,占据父级容器的比例

				if (this.handler) {
					this.handler.destroy();
					this.handler = null;
				}
				//处理用户输入事件。可以添加自定义功能以在用户输入时执行；参数为任意
				this.handler = new Cesium.ScreenSpaceEventHandler(sliderDiv);
				var moveActive = false;

				// 计算拆分
				function move(movement) {
					if (!moveActive) {
						return;
					}

					//捕获滑动停止的位置
					var relativeOffset = movement.endPosition.x;
					var splitPosition = (sliderDiv.offsetLeft + relativeOffset) / sliderDiv.parentElement.offsetWidth;
					sliderDiv.style.left = `${100.0 * splitPosition}%`;
					viewer.scene.splitPosition = splitPosition;
				}

				//对分割条的操作
				this.handler.setInputAction(function() {
					moveActive = true;
				}, Cesium.ScreenSpaceEventType.LEFT_DOWN);
				this.handler.setInputAction(function() {
					moveActive = true;
				}, Cesium.ScreenSpaceEventType.PINCH_START);

				this.handler.setInputAction(move, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
				this.handler.setInputAction(move, Cesium.ScreenSpaceEventType.PINCH_MOVE);

				this.handler.setInputAction(function() {
					moveActive = false;
				}, Cesium.ScreenSpaceEventType.LEFT_UP);
				this.handler.setInputAction(function() {
					moveActive = false;
				}, Cesium.ScreenSpaceEventType.PINCH_END);

				_self.handleClickLeft(_self.leftValue);
				_self.handleClickRight(_self.rightValue);
			},

			/**
			 * 移除卷帘
			 */
			removeSplitLayer() {
				let sliderDiv = document.getElementById("image_slider");
				if (sliderDiv) {
					document.body.removeChild(sliderDiv);
				}
				this.removeSplitLayerLeft();
				this.removeSplitLayerRight();

				if (earthAtLeft) {
					earthAtLeft.splitDirection = Cesium.SplitDirection.NONE;
				}

				if (earthAtRight) {
					earthAtRight.splitDirection = Cesium.SplitDirection.NONE;
				}
			},
			/**
			 * 移除左侧图层
			 */
			removeSplitLayerLeft() {
				if (earthAtLeft) {
					if (earthAtLeft instanceof Cesium.ImageryLayer) {
						jt3d._viewer.imageryLayers.remove(earthAtLeft);
					}

					if (earthAtLeft instanceof Cesium.Cesium3DTileset) {
						jt3d._viewer.scene.primitives.remove(earthAtLeft);
					}

					if (earthAtLeft instanceof Array) {
						earthAtLeft.forEach((res, index) => {
							jt3d._viewer.scene.primitives.remove(res);
						})
					}
				}
			},
			/**
			 * 移除右侧图层
			 */
			removeSplitLayerRight() {
				if (earthAtRight) {
					if (earthAtRight instanceof Cesium.ImageryLayer) {
						jt3d._viewer.imageryLayers.remove(earthAtRight);
					}

					if (earthAtRight instanceof Cesium.Cesium3DTileset) {
						jt3d._viewer.scene.primitives.remove(earthAtRight);
					}

					if (earthAtRight instanceof Array) {
						earthAtRight.forEach((res, index) => {
							jt3d._viewer.scene.primitives.remove(res);
						})
					}
				}
			},
		},

		//生命周期 - 创建完成（可以访问当前this实例）
		created() {},

		//生命周期 - 挂载完成（可以访问DOM元素）
		mounted() {
			//在这获取图层列表
			let _self = this;
			//权限查询条件语句
			let atlasLayersSqlWhere = undefined;

			//获取地图图集id
			let roleId = store.roleId
			atlasLayersSqlWhere = '"roleId"' + " = " + roleId + " and " + '"atlasType"' + "='图层'"

			//Promise回调
			function init() {
				return new Promise((resolve, reject) => {
					_self.initData.forEach((res,index) => {
						let num = Number(res.layerorder)
						if (num < 10) {
							res.layerorder = '0' + res.layerorder
						}

						res.value = res;
						res.label = res.layername;

						if (index == 0) {
							_self.leftValue = res;
						}
						if (index == 1) {
							_self.rightValue = res;
						}

					})
					_self.leftData = _self.rightData = deepTree(_self.initData)
					console.log('图层控制树列表+++', _self.leftData)
					resolve(true)
				})
			}

			//获取图集
			this.$http.get('/getTableList', {
				tableName: 'sys_map_atlas_layers', //表名
				sqlWhere: atlasLayersSqlWhere, //查询条件  国土调查
				orderByField: '' //排序
			}).then(res => {
				//初始图层列表
				this.initData = res.data
				init().then(item => {})
			})
		},

		beforeCreate() {}, //生命周期 - 创建之前
		beforeMount() {}, //生命周期 - 挂载之前
		beforeUpdate() {}, //生命周期 - 更新之前
		updated() {}, //生命周期 - 更新之后
		beforeDestroy() {}, //生命周期 - 销毁之前
		destroyed() {}, //生命周期 - 销毁完成
		activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
	};
</script>

<style lang="scss" scoped>
	//整体样式
	.jt-ImageLayerSplit {
		padding: 10rem;

		//左侧
		._left {
			width: 240rem;
			float: left;
		}

		//右侧
		._right {
			width: 240rem;
			float: left;
			margin-left: 10rem;
		}
		.el-tree{
			width:300rem !important;
		}

		// .el-popper.is-light,
		// .el-dropdown__popper.el-popper {
		// 	background: rgb(255 255 255) !important;
		// 	border: 0 !important;
		// }

		// .el-select-dropdown {
		// 	background: rgb(255 255 255) !important;
		// }
	}
</style>
