<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,
		Stroke
	} from "ol/style";
	import { Polygon, Circle, LineString } from "ol/geom";
	import markerIcon from "@/assets/images/ship3.png";
	import selectIcon from "@/assets/images/ship_tblr.png";

	const {
		proxy
	} = getCurrentInstance();

	const map = ref(null);
	const sourceVla = ref(null);
	let vector = new VectorLayer({
		source: sourceVla.value, 
		style: new Style({ 
			fill: new Fill({ 
				color: "rgba(37,241,239,0.2)" ,
			}), 
			stroke: new Stroke({ 
				color: "#264df6", 
				width:2 ,
			}) 
		}) 
	}); 
	let analogListSource = new VectorSource({
		features: [],
	});

	let analogListLayer = new VectorLayer({
		source: analogListSource,
	});

	watch(
		() => proxy.$store.state.data.analogList,
		(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(analogListLayer);
		sourceVla.value = new VectorSource({ wrapX: false }); 
		vector.setSource(sourceVla.value);
		map.value.addLayer(vector);
		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);
				// }
			}
		});
		getHysi()
	};

	/**
	 * 设置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: markerIcon,
					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));
		//将新要素添加到数据源中
		analogListSource.addFeature(newFeature);

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

	const setFeature = (analog) => {
		analogListSource.idIndex_[analog["sn"]].setStyle(
			getStyls(analogListSource.idIndex_[analog["sn"]], analog)
		);
		analogListSource.idIndex_[analog["sn"]].setGeometryName(analog["iboatName"]);
		analogListSource.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.analogList.length; i++) {
			let item = proxy.$store.state.data.analogList[i];
			if (
				analogListSource.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);
			}
		}
	};
	const showHysi = (_obj) => {
		var circle, plygon, Polygona = [];
		if(_obj.gpsInfo.lon.length){
			let _lon = _obj.gpsInfo.lon;
			let _lat = _obj.gpsInfo.lat;
			for(let i = 0;i<_lon.length;i++){
				Polygona.push([_lon[i],_lat[i]]);
			}
		}
		var plygon = new Polygon([Polygona]);
		var circle = new Circle(Polygona[0], parseFloat(_obj.gpsInfo.radius)/103360);
		map.value.getView().animate({
			center: Polygona[0],
			duration: 300,
		});
		var feature = new Feature({
			geometry: (_obj.fence_type == 0?circle:plygon)
		});
		sourceVla.value.addFeature(feature);
	}
	const getHysi = () => {
		let _obj = [
			// 圆形
		{
			"name": "易站001",
			"fence_type": 0,
			"gpsInfo": {
				"lon": [113.12786929774255],
				"lat": [22.13782107419196],
				"radius": 2211.1124010790627
			}
		},{//多边形
			"name": "易站002",
			"fence_type": 1,
			"gpsInfo": {
				"lon": [122.27364514766231, 122.38097317161841, 122.43951573013992, 122.34584763650551, 122.27104325617246, 122.27364514766231],
				"lat": [30.482269795850222, 30.504385873513904, 30.419173927221483, 30.400310213920108, 30.417872981476563, 30.482269795850222],
				"radius": 0,
			}
		},{
			"name": "易站003",
			"fence_type": 1,
			"gpsInfo": {
				"lon": [113.08004906171875, 113.11369469160157, 113.10435168909997, 113.06830279993981, 113.08004906171875],
				"lat": [22.178803607006838, 22.172452136059572, 22.134559508029852, 22.13936602658454, 22.178803607006838],
				"radius": 0,
			}
		}];
		_obj.forEach(item => {
			showHysi(item);
		})
	}
</script>