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

	import {
		inject
	} from "vue";

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

<template>
	<div class="jt-query-graphics">
		<el-row :gutter="20" style="margin-left: 0rem; margin-right: 0rem">
			<el-col :span="8" v-for="(item,index) in queryGraphics" @click="handleQueryGraphics(item.type,index)">
				<el-avatar shape="circle" :size="70" :class="currentIndex===index?'selectStyle':'defaultStyle'">
					<i :class="[item.icon,currentIndex===index?'selectFontStyle':'']" />
				</el-avatar>
				<div style="margin-top: 5rem; font-size: 14rem;" :class="currentIndex===index?'selectFontStyle':''">{{item.label}}</div>
			</el-col>
		</el-row>
	</div>
</template>

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

	import {
		Store
	} from '@/store/index'
	let store = Store();

	import {
		deepTree
	} from "@/utils/deepTree.js";

	export default {
		props: {

		},
		watch: {

		},

		/* 数据 */
		data() {
			return {
				currentIndex: -1,
				queryGraphics: [{
						label: '点查询',
						type: 'Point',
						number: 0,
						icon: 'iconfont icon-svgdianchaxun'
					},
					{
						label: '线查询',
						type: 'Line',
						number: 1,
						icon: 'iconfont icon-svgxianchaxun'
					},
					{
						label: '圆形查询',
						type: 'Circle',
						number: 2,
						icon: 'iconfont icon-svgyuanxingchaxun'
					},
					{
						label: '矩形查询',
						type: 'Rectangle',
						number: 3,
						icon: 'iconfont icon-svgjuxingchaxun'
					},
					{
						label: '多边形',
						type: 'Polygon',
						number: 4,
						icon: 'iconfont icon-svgduobianxingchaxun'
					},
					{
						label: '清除',
						type: 'clear',
						number: 5,
						icon: 'iconfont icon-shanchu'
					},
				],
			}
		},

		/* 方法 */
		methods: {
			/**
			 * 查询事件
			 * @param {Object} type 查询类型
			 * @param {Object} index 第几个被选中
			 */
			handleQueryGraphics(type, index) {
				let _self = this;
				this.currentIndex = index;

				//移除左键单击事件
				if (jt3d.handlerLeftClick) {
					jt3d.handlerLeftClick.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK); //移除事件
				}

				jt3d.CommonTools.clear();
				switch (type) {
					case "Point": //点查询
						jt3d.CommonTools.queryByPoint(function(coordinates) {
							console.log(coordinates)

							//还原左键单击事件
							_self.$parent.$parent.$refs.refMap3d.clickEntity(jt3d);

							/* 转换坐标 */
							let points = coordinates.split(',');

							_self.initQuery({
								spatialType: '点',
								coordinate: Number(points[0]) + " " + Number(points[1]),
								buffer: ''
							});

						});
						break;
					case "Line": //线查询
						jt3d.CommonTools.queryByLine(function(coordinates) {
							console.log(coordinates)

							//还原左键单击事件
							_self.$parent.$parent.$refs.refMap3d.clickEntity(jt3d);

							/* 转换坐标 */
							let points = coordinates.split(',');
							let pointsArray = [];
							for (let i = 0; i < points.length;) {
								pointsArray.push(Number(points[i]) + " " + Number(points[i + 1]));
								i = i + 2;
							}

							_self.initQuery({
								spatialType: '线',
								coordinate: pointsArray.join(','),
								buffer: ''
							});
						});
						break;
					case "Circle": //圆形查询
						jt3d.CommonTools.queryByCircle(function(coordinates, radius) {
							console.log("圆点：" + coordinates + "，半径：" + radius)

							//还原左键单击事件
							_self.$parent.$parent.$refs.refMap3d.clickEntity(jt3d);

							/* 转换坐标 */
							let points = coordinates.split(',');

							_self.initQuery({
								spatialType: '点',
								coordinate: Number(points[0]) + " " + Number(points[1]),
								buffer: radius
							});

						});
						break;
					case "Rectangle": //矩形查询
						jt3d.CommonTools.queryByRectangle(function(coordinates) {
							console.log(coordinates)

							//还原左键单击事件
							_self.$parent.$parent.$refs.refMap3d.clickEntity(jt3d);

							/* 转换坐标 */
							let points = coordinates.split(',');
							let pointsArray = [];
							for (let i = 0; i < points.length;) {
								pointsArray.push(Number(points[i]) + " " + Number(points[i + 1]));
								i = i + 2;
							}

							_self.initQuery({
								spatialType: '面',
								coordinate: pointsArray.join(','),
								buffer: ''
							});

						});
						break;
					case "Polygon": //多边形查询
						jt3d.CommonTools.queryByPolygon(function(coordinates) {
							console.log(coordinates)

							//还原左键单击事件
							_self.$parent.$parent.$refs.refMap3d.clickEntity(jt3d);

							/* 转换坐标 */
							let points = coordinates.split(',');
							let pointsArray = [];
							for (let i = 0; i < points.length;) {
								pointsArray.push(Number(points[i]) + " " + Number(points[i + 1]));
								i = i + 2;
							}

							_self.initQuery({
								spatialType: '面',
								coordinate: pointsArray.join(','),
								buffer: ''
							});

						});
						break;
					case "clear": //清除查询效果
						this.currentIndex = -1;

						//清除绘制
						jt3d.CommonTools.clear();

						//还原左键单击事件
						this.$parent.$parent.$refs.refMap3d.clickEntity(jt3d);

						//清除高亮显示
						let list = jt3d._dataSources.getByName("单击高亮显示")
						list.forEach(res => {
							jt3d._dataSources.remove(res)
						})

						//清除定位样式
						if (jt3d.LocateUtil._locationEntity) {
							window["viewer"].entities.remove(jt3d.LocateUtil._locationEntity);
						}
						break;
				}
			},

			/**
			 * @param {Object} options
			 */
			initQuery(options) {
				let _self = this;
				let treeNodes = [];

				//清除高亮显示
				let list = jt3d._dataSources.getByName("单击高亮显示")
				list.forEach(res => {
					jt3d._dataSources.remove(res)
				})

				//清除定位样式
				if (jt3d.LocateUtil._locationEntity) {
					window["viewer"].entities.remove(jt3d.LocateUtil._locationEntity);
				}

				//查询等待框
				loading = ElLoading.service({
					lock: true,
					text: 'Loading',
					background: 'rgba(0, 0, 0, 0.7)',
				});

				const getData = () => {
					let data = [];
					store.queryMapTables.forEach((itemTable, index) => {
						let result = getAxios(itemTable, options);
						data.push(result);
					})

					Promise.all(data).then(itemList => {

						console.log("itemList", itemList) //itemList返回的数据是按顺序的
						//执行自己接下来的操作
						//doSomething

						itemList.forEach((item, index) => {
							let field = item.table;
							let tableName = item.table[0].tableName;
							let tableDescription = item.table[0].tableDescription;

							if (item.data.features.length > 0) {
								//添加父节点
								let parentNode = {
									id: tableName,
									parentid: "CIM",
									label: tableDescription + "(" + item.data.features.length + ")",
								};
								treeNodes.push(parentNode);

								item.data.features.forEach((itemData, index) => {

									//**************高亮显示****************

									// /* 转换坐标 */
									// let positions = itemData.geometry.coordinates[0][0].map(point => {
									// 	return Cesium.Cartesian3.fromDegrees(point[0], point[1], point[2] || 0);
									// });

									// //先创建一个CustomDataSource源，然后把entity存入这里面
									// let Polygon = new Cesium.CustomDataSource("单击高亮显示");
									// jt3d._dataSources.add(Polygon);
									// //添加数据的方式
									// Polygon.entities.add({
									// 	polygon: {
									// 		hierarchy: new Cesium.PolygonHierarchy(positions),
									// 		material: Cesium.Color.fromCssColorString("rgba(255,0,255,.7)"),
									// 		classificationType: Cesium.ClassificationType.BOTH,
									// 	},
									// });

									//**************高亮显示****************

									let childNode = {
										id: itemData.properties["id"],
										parentid: tableName,
										field: field,
										data: itemData,
									};

									switch (tableName) {
										//==============规划管理数据-重要控制线=========================
										case "yjjbnt": //永久基本农田
											childNode.label = itemData.properties["cfzr"] + "(" + itemData.properties["zzsxmc"] + ")"
											break;
										case "yjtz": //永久基本农田调整
											childNode.label = itemData.properties["zldwmc"] + "(" + itemData.properties["dlmc"] + ")"
											break;
										case "bnrgdbh": //不纳入耕地保护目标
											childNode.label = itemData.properties["zldwmc"] + "(" + itemData.properties["dlmc"] + ")"
											break;
										case "gdbhrw": //耕地保护任务
											childNode.label = itemData.properties["zldwmc"] + "(" + itemData.properties["dlmc"] + ")"
											break;

											//==============规划管理数据-历史规划==============
										case "tdzgh": //土地利用总体规划
											childNode.label = itemData.properties["ghdlmc"]
											break;
										case "jsyd": //建设用地管制区
											childNode.label = itemData.properties["id"]
											break;

											//==============现状类数据-森林资源-森林资源调查==============
										case "slyzt": //2019年森林资源管理一张图
											childNode.label = itemData.properties["id"]
											break;

											//==============现状类数据-国土调查==============
										case "ed2009": //二调
											childNode.label = itemData.properties["zldwmc"] + "(" + itemData.properties["dlmc"] + ")"
											break;
										case "ed2020": //二调2020
											childNode.label = itemData.properties["zldwmc"] + "(" + itemData.properties["dlmc"] + ")"
											break;
										case "ed2021": //二调2021
											childNode.label = itemData.properties["zldwmc"] + "(" + itemData.properties["dlmc"] + ")"
											break;
										case "sddltb": //三调   
											childNode.label = itemData.properties["zldwmc"] + "(" + itemData.properties["dlmc"] + ")"
											break;
									}

									treeNodes.push(childNode);
								});
							}
						});

						//处理查询结果树
						if (treeNodes.length > 0) {

							_self.$parent.$parent.$refs.refQueryResult.expandedKeys = []
							_self.$parent.$parent.$refs.refQueryResultPopup.isshow = true;
							_self.$parent.$parent.$refs.refQueryResult.treeData = deepTree(treeNodes);

							//默认选中第一个节点并赋予选中样式
							_self.$nextTick(function() {
								let currentNode = _self.$parent.$parent.$refs.refQueryResult.treeData[0].children[0];
								let currentKey = currentNode.id;
								_self.$parent.$parent.$refs.refQueryResult.currentKey = currentKey;
								_self.$parent.$parent.$refs.refQueryResult.$refs.tree.setCurrentKey(currentKey);
								_self.$parent.$parent.$refs.refQueryResult.handleNodeClick(currentNode);
							});

							//expandedKeys默认展开treedata第一层，加载第一层数据
							_self.$parent.$parent.$refs.refQueryResult.expandedKeys.push(_self.$parent.$parent.$refs.refQueryResult.treeData[0].id)
						}

						//清除绘制
						jt3d.CommonTools.clear();

						//关闭等待框
						loading.close()

					})
				}

				const getAxios = (itemTable, options) => {
					return new Promise(function(resolve, reject) {
						_self.$http.get('/getSpatialQuery', {
							tableName: itemTable,
							spatialType: options.spatialType,
							coordinate: options.coordinate,
							buffer: options.buffer
						}).then(res => {
							resolve(res)
						});
					}).catch(err => {

					})
				}

				getData();
			},
		},

		mounted() {

		}
	};
</script>

<style lang="scss" scoped>
	.jt-query-graphics {
		.el-col {
			padding: 10rem;
			// color: rgba(90, 172, 255, 1.0);
			//color: #55ffff;
			color: #fff;
		}

		i {
			display: inline-block;
			width: 100%;
			height: 36rem;
			line-height: 36rem;
			text-align: center;
			border-radius: 5rem;
			font-size: 40rem;
			// color: rgba(90, 172, 255, 1.0);
			// color: #55ffff;
			color: #fff;
			transition: all .3s;
			-webkit-transition: all .3s
		}

		.selectStyle {
			// background: rgba(135, 182, 254, 0.5);
			background: rgb(0 44 126);
		}

		.defaultStyle {
			background: #ffffff00;
		}

		.selectFontStyle {
			color: #fff;
		}
	}
</style>
