<template>
	<MapMap ref="mapMap" @ready="handleMapReady" />
</template>

<script setup>
	import MapMap from "@/components/Map/map";
	import Fill from "ol/style/Fill";
	import Text from "ol/style/Text";
	import VectorLayer from "ol/layer/Vector";
	import VectorSource from "ol/source/Vector";
	import {
		Feature,
		Overlay
	} from "ol";
	import {
		Point
	} from "ol/geom";
	import {
		Style,
		Icon
	} from "ol/style";
	import markerIcon3 from "@/assets/images/ship3.png";
	import markerIcon4 from "@/assets/images/ship4.png";
	import markerIcon5 from "@/assets/images/ship5.png";
	import markerIcon6 from "@/assets/images/ship6.png";
	import selectIcon from "@/assets/images/ship_tblr.png";

	const {
		proxy
	} = getCurrentInstance();

	const map = ref(null);

	let shipListSource = new VectorSource({
		features: [],
	});

	let shipListLayer = new VectorLayer({
		source: shipListSource,
	});

	watch(
		() => proxy.$store.state.data.shipList,
		(newValue, oldValue) => {
			if (map.value != null) {
				if (newValue.length != oldValue.length && oldValue.length == 0) {
					proxy.$refs["mapMap"].moveToShipBySn(proxy.$store.state.data.curAnalogSn);
				}
				updateFeatures();
			}
		}
	);

	watch(
		() => proxy.$store.state.data.curAnalogSn,
		(newValue) => {
			if (map.value != null) {
				updateFeatures();
				proxy.$refs["mapMap"].moveToShipBySn(newValue);
			}
		}
	);

	const handleMapReady = () => {
		map.value = proxy.$refs["mapMap"].map;
		map.value.addLayer(shipListLayer);
		updateFeatures();

		map.value.on("pointermove", function(evt) {
			// console.log(evt)
			proxy.$emit("pointermove", evt);
			var pixel = this.getEventPixel(evt.originalEvent);
			var feature = this.forEachFeatureAtPixel(pixel, function(feature) {
				return feature;
			});
			if (feature == undefined) {
				this.getTargetElement().style.cursor = "auto";
			} else {
				// console.log(feature);
				if (feature.id_ && feature.id_.indexOf("3800") == 0) {
					this.getTargetElement().style.cursor = "pointer";
				}
			}
		});

		map.value.on("singleclick", function(evt) {
			// console.log("singleclick");

			var pixel = this.getEventPixel(evt.originalEvent);
			var feature = this.forEachFeatureAtPixel(pixel, function(feature) {
				return feature;
			});
			// console.log(feature);

			if (feature == undefined) {} else {
				console.log(feature);
				proxy.$store.state.data.curAnalogSn = feature.id_;
				// moveToShipBySn(proxy.$store.state.data.curAnalogSn, zoom);
				// if (feature.id_.indexOf("3800") == 0) {
				//   proxy.$router.push(`/view/ship?sn=${feature.id_}`);
				//   proxy.$emit("singleclick", feature);
				// }
			}
		});
	};

	/**
	 * 设置Style
	 */
	const getStyls = (feature, analog) => {
		//////////// console.log(feature);
		//////////// console.log(analog);
		let rotation = Number(analog["0aA"]) * (Math.PI / 180);
		rotation = isNaN(rotation) ? 0 : rotation;
		let Styles = [];
		if (analog.sn == proxy.$store.state.data.curAnalogSn) {
			Styles.push(
				new Style({
					image: new Icon({
						src: selectIcon,
						scale: map.value.getView().getZoom() / 20,
						anchor: [0.5, 0.7], // 偏移的 x 与 y 方向值，注意此值与 Cesium 等GIS库偏向方向正好相反
						rotation: rotation,
					}),
				})
			);
		}
		Styles.push(
			new Style({
				image: new Icon({
					src: (analog["isSail"] == 1?markerIcon3:(analog["isSail"] == 2?markerIcon4:(analog["isSail"] == 3?markerIcon5:markerIcon6))),
					scale: map.value.getView().getZoom() / 20,
					anchor: [0.5, 0.7], // 偏移的 x 与 y 方向值，注意此值与 Cesium 等GIS库偏向方向正好相反
					rotation: rotation,
				}),
			})
		);
		Styles.push(
			new Style({
				text: new Text({
					textAlign: "center",
					text: `  ${feature.values_.name}  `,
					offsetX: 0,
					offsetY: 15,
					fill: new Fill({
						//文字填充色
						color: "#2520ff",
					}),
					backgroundFill: new Fill({
						color: "rgba(255,255,255,0)",
					}),
				}),
			})
		);
		return Styles;
	};

	/**
	 * 添加一个新的标注（矢量要素）
	 * @param {ol.Coordinate} coordinate 坐标点 [x,y]
	 */
	const addFeature = (analog) => {
		//新建一个要素 Feature
		var newFeature = new Feature({
			//几何信息
			geometry: new Point([Number(analog["0a4"]), Number(analog["0a5"])]),
			//名称属性
			name: analog["iboatName"],
		});

		// 设置ID
		newFeature.setId(analog["sn"]);
		// 设置样式
		newFeature.setStyle(getStyls(newFeature, analog));
		//将新要素添加到数据源中
		shipListSource.addFeature(newFeature);

		//////////// console.log(shipListSource.idIndex_[analog["sn"]]);
		// setTimeout(() => {
		//   shipListSource.idIndex_[analog["sn"]].setGeometry(new Point([118.766, 32]));
		// }, 3000);
	};

	const setFeature = (analog) => {
		shipListSource.idIndex_[analog["sn"]].setStyle(
			getStyls(shipListSource.idIndex_[analog["sn"]], analog)
		);
		shipListSource.idIndex_[analog["sn"]].setGeometryName(analog["iboatName"]);
		shipListSource.idIndex_[analog["sn"]].setGeometry(
			new Point([Number(analog["0a4"]), Number(analog["0a5"])])
		);
	};

	const updateFeatures = () => {
		//// console.log(`updateFeatures`);
		for (let i = 0; i < proxy.$store.state.data.shipList.length; i++) {
			let item = proxy.$store.state.data.shipList[i];
			if (
				shipListSource.idIndex_[item["sn"]] != undefined &&
				map.value.getOverlayById(item["sn"])
			) {
				setFeature(item);
				let className;
				if (
					item["isSail"] == 1 &&
					new Date().getTime() - new Date(item["time"]).getTime() <
					proxy.$store.state.data.timeout
				) {
					////// console.log("online isSail");
					className = `animation breathe sm sn-${item["sn"]}`;
				} else {
					className = `sn-${item["sn"]}`;
				}
				map.value.getOverlayById(item["sn"]).element.children[0].className =
					className;
				map.value
					.getOverlayById(item["sn"])
					.setPosition([Number(item["0a4"]), Number(item["0a5"])]);
			} else {
				let breatheAnimationPoint = document.createElement("div");
				// breatheAnimationPoint.className = `animation breathe sn-${item["sn"]}`
				let className;
				if (
					item["isSail"] == 1 &&
					new Date().getTime() - new Date(item["time"]).getTime() <
					proxy.$store.state.data.timeout
				) {
					////// console.log("online isSail");
					className = `animation breathe sm sn-${item["sn"]}`;
				} else {
					className = `sn-${item["sn"]}`;
				}
				breatheAnimationPoint.className = className;
				breatheAnimationPoint.id = `${item["sn"]}`;
				breatheAnimationPoint.onclick = (e) => {
					// console.log(e);
					proxy.$store.state.data.curAnalogSn = e.target.id;
				};
				let point_overlay = new Overlay({
					id: item["sn"],
					element: breatheAnimationPoint,
					positioning: "center-center",
				});
				// console.log(map);
				map.value.addOverlay(point_overlay);
				point_overlay.setPosition([Number(item["0a4"]), Number(item["0a5"])]);
				addFeature(item);
			}
		}
	};
</script>