<script setup>
	import {
		inject
	} from "vue";
	const getMapInstance = inject("getMapInstance");
	jt3dRight = getMapInstance();

	import {
		Store
	} from '@/store/index'
	store = Store()
	import {
		deepTree
	} from "@/utils/deepTree.js";
</script>

<template>
	<div class="jt-layer">
		<el-tree :data="treeData" :default-expanded-keys="expandedKeys" :default-checked-keys="checkedkeys" node-key="id" class="tree-line" ref="treeRef">
			<template #default="{ node, data }">
				<!-- 复选框 -->
				<el-checkbox v-if="data.ischeck === '1' && store.userport == 'PC'" v-model="node.checked" :indeterminate="node.indeterminate" :disabled="!!node.disabled" @change="handleCheckBoxChange($event, data, node)">
				</el-checkbox>
				<el-switch v-else-if="data.ischeck == 1 && store.userport == 'APP'" width="30rem" size="small" v-model="node.checked" @change="handleCheckBoxChange($event, data, node)" />
				<span class="custom-tree-node" @click="handleClick(data)" style="width: 150rem;text-align: left;">
					<!-- 字体、图标 -->
					<!-- <span>
						<img src="@/assets/images/logo16x16.ico" />
					</span> -->
					<span class="overflowtext">
						{{ data.layername }}
					</span>
				</span>

				<!-- 透明度 -->
				<template v-if="node.checked && data.opacity >0">
					<div style="width: 80rem; padding: 0 20rem; position: absolute; right: 0">
						<el-slider v-model="data.opacity" @input="handleSliderChange($event, data)" :max="1" :min="0.1" :step="0.1" />
					</div>
				</template>
			</template>
		</el-tree>
	</div>
</template>

<script>
	let store = undefined;
	let jt3dRight = undefined;
	let jt3dLeft = undefined;
	
	export default {

		/* 数据 */
		data() {
			return {
				treeData: [],
				inittree: [], //初始化图层数组
				expandedKeys: [], //对应要展开的节点id
				checkedkeys: [] //默认打开节点的id
			}
		},

		/* 方法 */
		methods: {
			/**
			 * 单击图层名称触发服务定位
			 * @param {Object} data 传递给 data 属性的数组中该节点所对应的对象
			 */
			handleClick(data) {
				this.$parent.$parent.$refs.refLayer.mark = "serviceLeft";
				this.$parent.$parent.$refs.refLayer.setLayersLocation(jt3dLeft, data);
			},

			/**
			 * el-slider 值改变时触发
			 * 地图服务的透明度调整
			 */
			handleSliderChange($event, data) {
				this.$parent.$parent.$refs.refLayer.mark = "serviceLeft";
				this.$parent.$parent.$refs.refLayer.setLayersAlpha(jt3dLeft, $event, data)
			},
			/**
			 * el-checkbox 当绑定值变化时触发的事件
			 * @param {Object} checked 复选框状态
			 * @param {Object} data 对应于节点点击的节点对象
			 * @param {Object} node TreeNode 的 node 属性
			 */
			handleCheckBoxChange(checked, data, node) {
				this.$parent.$parent.$refs.refLayer.mark = "serviceLeft";
				let _node = this.$refs.treeRef.getNode(data);
				if (_node.isLeaf) {
					this.$parent.$parent.$refs.refLayer.setLayersControl(jt3dLeft, data, checked);
					this.$refs.treeRef.setChecked(_node, checked); //是否设置子节点，默认为false，利用tree组件渲染后带有的isLeaf(是否为叶子节点)属性，如果为叶子节点就选中。利用tree的API就实现了正确的回显效果	
				}

				//控制子节点
				this.childNodesChange(node, checked);
			},
			/**
			 * 控制子节点
			 * @param {Object} node
			 * @param {Object} checked
			 */
			childNodesChange(node, checked) {
				let _self = this;
				node.childNodes.forEach(item => {
					_self.$parent.$parent.$refs.refLayer.setLayersControl(jt3dLeft, item.data, checked);
					_self.$refs.treeRef.setChecked(item, checked);
					_self.childNodesChange(item, checked);
				});
			},

			/**
			 * 分屏对比初始化
			 */
			initSplitScreen() {
				let _self = this;

				//这样做会跑偏
				// let cesiumContainerDiv = document.getElementById("cesiumContainer2");
				// if (cesiumContainerDiv == null) {
				// 	cesiumContainerDiv = document.createElement('div');
				// 	cesiumContainerDiv.id = "cesiumContainer2";
				// 	cesiumContainerDiv.classList.add("ViewerSplitScreen");
				// 	cesiumContainerDiv.style.float = "left";
				// 	cesiumContainerDiv.style.width = "calc(50% - 1rem)";
				// 	cesiumContainerDiv.style.height = "100vh";
				// 	cesiumContainerDiv.style.margin = "0";
				// 	cesiumContainerDiv.style.borderRight = "2rem solid red";

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

				let mapView1 = document.getElementById("cesiumContainer");
				let mapView2 = document.getElementById("cesiumContainer2");
				mapView1.className = "ViewerSplitScreen";
				mapView2.style.display = "block";
				//加载分屏左侧大球
				this.initMap3d();
				//同步相机状态
				this.syncViewer();
				//绑定图层控制
				this.initTree();

			},

			/**
			 * 移除分屏对比
			 */
			removeSplitScreen() {
				let mapView1 = document.getElementById("cesiumContainer");
				let mapView2 = document.getElementById("cesiumContainer2");

				mapView1.className = "jt-map";
				mapView2.style.display = "none";
				mapView2.innerHTML = "";

				if (jt3dLeft) {
					jt3dLeft._viewer.entities.removeAll(); // 删除全部
					jt3dLeft._viewer.imageryLayers.removeAll();
					jt3dLeft._viewer.scene.primitives.removeAll(); //谨慎使用，可能删除不必要的primitive
					// jt3dLeft._viewer.destroy();
					jt3dLeft = undefined;
				}
			},

			/**
			 * 加载分屏左侧大球
			 */
			initMap3d() {
				jt3dLeft = new this.jt3dSDK.jtMap3d({
					container: "cesiumContainer2",
				});

				//底部工具
				jt3dLeft.statusBar.show = true;
				//图层
				jt3dLeft.layer = new this.jt3dSDK.layer(jt3dLeft._viewer);

				//测量工具
				jt3dLeft.CommonTools = new this.jt3dSDK.CommonTools(jt3dLeft._viewer);
				//绘图工具
				jt3dLeft.SketchViewModel = new this.jt3dSDK.SketchViewModel(jt3dLeft._viewer, {
					isClear: false,
					isDrawPoint: true,
					isRetainDrawPoint: true,
					iconType: 'blue',
				});
				//定位工具
				jt3dLeft.LocateUtil = new this.jt3dSDK.LocateUtil(jt3dLeft._viewer);

				//二三维标绘
				jt3dLeft.DrawTools = new this.jt3dSDK.DrawTools(jt3dLeft._viewer);
				//军事标绘
				jt3dLeft.DrawMilitaryPlot = new this.jt3dSDK.DrawMilitaryPlot(jt3dLeft._viewer);

				//天空盒子
				jt3dLeft.SceneEffects = {};
				jt3dLeft.SceneEffects.SkyBox = new this.jt3dSDK.SceneEffects.SkyBox(jt3dLeft._viewer);

				//线对象
				jt3dLeft.PolylineObject = new this.jt3dSDK.PolylineObject(jt3dLeft._viewer);

				//比例尺、指南针
				this.$parent.$parent.$refs.refNavigation.initNavigation(jt3dLeft);

				//设置默认视图
				this.$parent.$parent.$refs.refMap3d.setView(jt3dLeft);

				// 初始化项目区域范围视角
				this.$parent.$parent.$refs.refMap3d.fullMap(jt3dLeft);

				//加载天空盒子
				this.$parent.$parent.$refs.refMap3d.addSkybox(jt3dLeft);

				//添加镇街边界线——精灵线
				// this.$parent.$parent.$refs.refMap3d.addBoundaryLine(jt3dLeft);

			},

			/**
			 * 同步相机状态
			 */
			syncViewer() {
				let _self = this;

				let viewerL = jt3dLeft._viewer;
				let viewerR = jt3dRight._viewer;

				var sceneL = viewerL.scene;
				var sceneR = viewerR.scene;

				var handlerL = new Cesium.ScreenSpaceEventHandler(sceneL.canvas);
				var ellipsoidL = sceneL.globe.ellipsoid;
				var handlerR = new Cesium.ScreenSpaceEventHandler(sceneR.canvas);
				var ellipsoidR = sceneR.globe.ellipsoid;

				handlerL.setInputAction((movement) => {
					this.isLeftTrigger = true;
					this.isRightTrigger = false;
				}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

				handlerR.setInputAction((movement) => {
					this.isLeftTrigger = false;
					this.isRightTrigger = true;
				}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

				var syncViewerL = function() {
					if (_self.isLeftTrigger) {
						viewerR.camera.flyTo({
							destination: viewerL.camera.position,
							orientation: {
								heading: viewerL.camera.heading,
								pitch: viewerL.camera.pitch,
								roll: viewerL.camera.roll
							},
							duration: 0.0
						});
					}
				}
				viewerR.camera.changed.addEventListener(syncViewerL);
				viewerR.scene.preRender.addEventListener(syncViewerL);

				var syncViewerR = function() {
					if (_self.isRightTrigger) {
						viewerL.camera.flyTo({
							destination: viewerR.camera.position,
							orientation: {
								heading: viewerR.camera.heading,
								pitch: viewerR.camera.pitch,
								roll: viewerR.camera.roll
							},
							duration: 0.0
						});
					}
				}
				viewerR.camera.changed.addEventListener(syncViewerR);
				viewerR.scene.preRender.addEventListener(syncViewerR);
			},

			/**
			 * 加载图层控制树
			 */
			initTree() {
				this.$parent.$parent.$refs.refLayer.mark = "serviceLeft";

				//在这获取图层列表
				let _this = this
				//权限查询条件语句
				let atlasLayersSqlWhere = undefined

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

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

							//透明度
							res.opacity = Number(res.opacity);

							//默认展开
							if (res.isexpand === '1') {
								_this.expandedKeys.push(res.id);
							}

							// 复选框默认选中
							if (res.isinit === '1') {
								_this.checkedkeys.push(res.id);
								_this.$parent.$parent.$refs.refLayer.setLayersControl(jt3dLeft, res, true);
							}
						})

						_this.treeData = deepTree(_this.inittree)
						resolve(_this.treeData)
					})
				}


				//获取图集
				this.$http.get('/getTableList', {
					tableName: 'sys_map_atlas_layers', //表名
					sqlWhere: atlasLayersSqlWhere, //
					orderByField: ''
				}).then(res => {
					console.log('所有图层', res.data)
					//初始图层列表
					this.inittree = res.data
					init(res.data).then(item => {
						console.log('图层控制树列表', _this.treeData)

						//复选框初始化选中
						_this.$nextTick(() => {
							_this.$refs.treeRef.setCheckedKeys(_this.checkedkeys, true);
						});
					})
				})
			}
		},

		mounted() {

		},
	};
</script>

<style lang="scss">
	.el-switch--small .el-switch__core .el-switch__action {
		width: 12rem;
		height: 12rem;
	}

	.el-switch--small.is-checked .el-switch__core .el-switch__action {
		margin-left: calc(-1rem - 12rem);
	}

	.el-switch__core .el-switch__action {
		top: 0;
	}

	.el-slider__button {
		width: 20rem;
		height: 20rem;
	}

	.el-tree-node__content {
		height: 26rem;
	}

	.el-switch--small .el-switch__core {
		height: 16rem;
	}

	.el-switch--small {
		padding: 0 5rem;
	}

	.jt-layer {
		padding-left: 10rem;

		.el-tree {
			background: none;
			color: #fff;
			--el-tree-node-hover-bg-color: #2a67c3;

			.overflowtext {
				width: auto !important;
				padding: 0;
			}
		}

		.tree-line {
			.el-tree-node {
				position: relative;
				// padding-left: 16rem; // 缩进量
			}

			.el-tree-node__children {
				padding-left: 16rem !important; // 缩进量

				.el-tree-node__content {
					padding-left: 18rem !important;
				}
			}

			// 竖线
			.el-tree-node::before {
				content: "";
				height: 100%;
				width: 1rem;
				position: absolute;
				left: -3rem;
				top: -26rem;
				border-width: 1rem;
				border-left: 1rem dashed rgba(255, 255, 255, .8);
			}

			// 当前层最后一个节点的竖线高度固定
			.el-tree-node:last-child::before {
				height: 38rem; // 可以自己调节到合适数值
			}

			// 横线
			.el-tree-node::after {
				content: "";
				width: 24rem;
				height: 20rem;
				position: absolute;
				left: -3rem;
				top: 12rem;
				border-width: 1rem;
				border-top: 1rem dashed rgba(255, 255, 255, .8);
			}

			// 去掉最顶层的虚线，放最下面样式才不会被上面的覆盖了
			&>.el-tree-node::after {
				border-top: none;
			}

			&>.el-tree-node::before {
				border-left: none;
			}

			// 展开关闭的icon
			.el-tree-node__expand-icon {
				font-size: 16rem;

				// 叶子节点（无子节点）
				&.is-leaf {
					color: transparent;
					display: none; // 也可以去掉
				}
			}
		}
	}
</style>
