<script lang="jsx">
import { defineComponent, onMounted, onUpdated, onUnmounted } from "vue";
import { mapState } from "vuex";
import ResizeObserver from "resize-observer-polyfill";
import debounce from "lodash/debounce";
import { getMapConfig } from "@/api/gis";
import { getLonLatByAllRoads, getTrackDriving } from "@/api/curingManage";
import { useStore } from "vuex";
import markerbg from "@/assets/images/roadtitbg.png";

const defaultBounds = [72.675311, 17.022993, 136.308124, 53.986993];
//                         m1:畅通 m2:轻度拥堵 m3:中度拥堵 m4:重度拥堵 m0:禁止通行
const defaultMileage = {
	//m1:畅通 m2:缓慢 m3:拥堵 m4:交通管制 m0:严重拥堵
	CQ: {
		// m: 1185.292,
		m: 1312.462, //含S53合璧津高速和S16黔江过境高速
		m0: 0,
		m1: 0,
		m2: 0,
		m3: 0,
		m4: 0,
		level1: "CQ",
	},
	S53合璧津高速: {
		id: "1612639944117981184",
		level1: "CQ",
		level2: "103",
		m: 86.47,
		m0: 0,
		m1: 0,
		m2: 0,
		m3: 0,
		m4: 0,
	},
	S16黔江过境高速: {
		id: "1627915514217107456",
		level1: "CQ",
		level2: "104",
		m: 40.7,
		m0: 0,
		m1: 0,
		m2: 0,
		m3: 0,
		m4: 0,
	},
	S7永泸高速: {
		id: "1430054414412025856",
		level1: "CQ",
		level2: "101",
		m: 41.886,
		m0: 0,
		m1: 0,
		m2: 0,
		m3: 0,
		m4: 0,
	},
	S34大内高速: {
		id: "1493834264024846336",
		level1: "CQ",
		level2: "102",
		m: 62.226,
		m0: 0,
		m1: 0,
		m2: 0,
		m3: 0,
		m4: 0,
	},
	G5515石黔高速: {
		id: "1430050859642916864",
		m: 166.36,
		m0: 0,
		m1: 0,
		m2: 0,
		m3: 0,
		m4: 0,
		level1: "CQ",
		level2: "104",
	},
	S9合安高速: {
		id: "1430053229818941440",
		m: 189.95,
		m0: 0,
		m1: 0,
		m2: 0,
		m3: 0,
		m4: 0,
		level1: "CQ",
		level2: "103",
	},
	G7521渝筑高速: {
		id: "1494144408961028096",
		m: 199.896,
		m0: 0,
		m1: 0,
		m2: 0,
		m3: 0,
		m4: 0,
		level1: "CQ",
		level2: "105",
	},
	S63秀松高速: {
		id: "1430051717893984256",
		m: 61.142,
		m0: 0,
		m1: 0,
		m2: 0,
		m3: 0,
		m4: 0,
		level1: "CQ",
		level2: "104",
	},
	G93渝遂高速: {
		id: "1430049550537723904",
		m: 186.92,
		m0: 0,
		m1: 0,
		m2: 0,
		m3: 0,
		m4: 0,
		level1: "CQ",
		level2: "101",
	},
	S55潼荣高速: {
		id: "1430052457714683904",
		m: 276.912,
		m0: 0,
		m1: 0,
		m2: 0,
		m3: 0,
		m4: 0,
		level1: "CQ",
		level2: "102",
	},
	SC: {
		m: 160.064,
		m0: 0,
		m1: 0,
		m2: 0,
		m3: 0,
		m4: 0,
		level1: "SC",
	},
	S53遂德高速: {
		id: "1551973634565787637",
		m: 160.064,
		m0: 0,
		m1: 0,
		m2: 0,
		m3: 0,
		m4: 0,
		level1: "SC",
		level2: "201",
	},
	YN: {
		m: 217.142,
		m0: 0,
		m1: 0,
		m2: 0,
		m3: 0,
		m4: 0,
		level1: "YN",
	},
	G5621昆楚高速: {
		id: "1551973630102081536",
		m: 217.142,
		m0: 0,
		m1: 0,
		m2: 0,
		m3: 0,
		m4: 0,
		level1: "YN",
		level2: "401",
	},
};
export default defineComponent({
	components: {},
	provide() {
		return {
			mapVM: this,
			getMap: this.getMap,
		};
	},
	props: {
		config: {
			type: Object,
			default: null,
		},
		center: {
			type: [Array, Object],
			default: null,
		},
		zoom: {
			type: Number,
			default: 8,
		},
		minZoom: {
			type: Number,
			default: 0,
		},
		maxZoom: {
			type: Number,
			default: 17,
		},
		bounds: {
			type: Array,
			default: null,
		},
		maxBounds: {
			type: Array,
			default: null,
		},
		fitBoundsOptions: {
			type: Object,
			default: null,
		},
	},
	data() {
		return {
			loaded: false,
			layers: [],
			videoPonit: null, //摄像头聚合点
			selectLevel: "",
			allRoadsLonglat: [], //包含经纬度的所有路段
			selectLineLayer: [], //已选择（已展示）的线路的id
			trafficInfo: {
				visibility: "none",
				date: new Date().getTime(),
				mileage: JSON.parse(JSON.stringify(defaultMileage)), // 1通畅 2轻度拥堵长度 3重度拥堵长度 4重度拥堵长度 0禁止通行长度,
			},

			markerList: {},
			markerDomListID: [],
			allRoadslanglat: [], //所有路段经纬度
			allRoadsIds: [], //所有路段的id
			timer: null,
		};
	},
	computed: {
		watchViewProps() {
			return [this.center, this.zoom, this.bounds, this.fitBoundsOptions];
		},
		selectRoad() {
			return this.$store.state.road.selectRoadId;
		},
		allRoads() {
			// 所有组织机构/路段
			return this.$store.state.road.allRoads;
		},
		// 路况路段的长度和显示隐藏
		getTrafficMileage() {
			return this.$store.state.trafficMileage;
		},
		//地图已有的layer(获取地图的时候就有的layer，比如千米桩百米桩....)
		mapConfigLayers() {
			return this.$store.state.map.layers;
		},
	},
	watch: {
		config() {
			this.init();
		},
		watchViewProps() {
			this.fitView();
		},
		selectRoad(newVal, oldVal) {
			if (newVal && newVal.length > 0) {
				//具体省、管理中心、路段
				this.getThatRows(
					newVal[this.$store.state.road.selectLevel - 1],
					this.$store.state.road.selectLevel
				);
			} else {
				//选的全国哦
				this.getThatRows("", 0);
			}
			// this.getRoadsLngLat(newVal[2])
		},
		getTrafficMileage(newVal, oldVal) {
			this.trafficInfo.visibility = newVal.visibility;
		},
		mapConfigLayers(newVal, oldVal) {
			let mapCL = {};
			if (newVal) {
				newVal.forEach((item) => {
					if (
						item.name == "千米桩" ||
						item.name == "百米桩" ||
						item.name == "路线"
					) {
						mapCL[item.code] = item.layerId;
					}
				});
			}
			localStorage.setItem("mapCLkmz", JSON.stringify(mapCL));
		},
	},
	created() {
		if (this.$route.name == "operationOverview") {
			this.trafficInfo.visibility = "visible";
		}
	},
	mounted() {
		this.getAllRoadsLangLat();
		this.init();
		//定时更新路况
		this.timer = setInterval(() => {
			this.setIntGetAddTrafficLayer();
		}, 90 * 1000);
	},
	beforeDestroy() {
		clearInterval(this.timer);
		this.timer = null;
	},
	methods: {
		// 加载地图
		init() {
			const { config, _initPromise } = this;
			if (!config || !config.key || _initPromise) {
				return;
			}
			const {
				key,
				domainUrl,
				dataDomainUrl,
				spriteUrl,
				serviceUrl,
				solution,
				style,
			} = config;
			const _that = this;
			this._initPromise = new Promise((resolve, reject) => {
				this.loadMinemapAPI()
					.then(() => {
						minemap.domainUrl =
							"https://map.hope.cmet1965.com:58000";
						minemap.dataDomainUrl =
							"https://map.hope.cmet1965.com:58000";
						minemap.serverDomainUrl =
							"https://map.hope.cmet1965.com:58000";
						minemap.serviceUrl =
							"https://map.hope.cmet1965.com:58000/service/";
						// minemap.spriteUrl =
						//   "https://map.hope.cmet1965.com:58000/minemapapi/zsxz/zsxz";
						minemap.spriteUrl = [
							"https://map.hope.cmet1965.com:58000/minemapapi/zsxz/zsxz",
							"./mapresource/sprite/sprite",
						];
						minemap.appKey = key;
						minemap.solution = solution;

						const options = this.getOptions();
						options.style = style;
						const map = new minemap.Map(options);
						map.on("load", () => {
							this._initPromise = null;
							this.loaded = true;
							map.repaint = true;
							this.$emit("load", { map, getMap: this.getMap });
							this.map = map;
							//隐藏地图上已有的线路(这个线路是做地图那边的人加上的，不是前端加的，所以先隐藏)
							// map.setLayoutProperty('466cb84ab4cacabe16ba0d1c269c0606', "visibility", "none");
							this.fitView();
							this.initEvent();
							this.observeResize();
							// ['videoSurveillance'].includes()
							if (this.$route.name == "videoSurveillance") {
								//除视频监控页面外
								// this.getThatRows('CQ', 1) //默认展示重庆
								this.getThatRows("", 0); //默认展示重庆
							} else {
								const orgId = localStorage.getItem("orgId");
								const orglen = localStorage.getItem("orglen");
								// 默认展示全国
								this.getThatRows("", 0);
								// if (orglen < 5) {
								//   this.getThatRows(orgId, 1);
								// } else {
								//   this.getThatRows("", 0);
								// }
							}
							const mapduc =
								document.getElementsByClassName("cm-map");
							var div = document.createElement("div");
							div.innerHTML =
								"世纪高通 - GS(2020)1186号 - 甲测资质11111333 - Data NavInfo";
							div.style.position = "absolute";
							div.style.left = "10px";
							div.style.bottom = "35px";
							div.style.fontSize = "12px";
							div.style.color = "#94a8c6";
							for (let i = 0; i < mapduc.length; i++) {
								mapduc[i].appendChild(div);
							}

							//监听层级显示隐藏路段浮出来的路段名marker
							map.on("zoom", function (e) {
								const zoomnum = map.getZoom();
								if (_that.markerDomListID.length > 0) {
									_that.markerDomListID.forEach((ele) => {
										const idv = ele
											.getAttribute("class")
											.indexOf("rodeMarkerDiv1"); //筛选出小图标
										if (zoomnum < 8) {
											let isshow = "none";
											if (zoomnum <= 6) {
												// 6~8级显示大图标 小于等于6级显示小图标
												if (idv > -1) {
													isshow = "block";
												} else {
													isshow = "none";
												}
											} else {
												if (idv > -1) {
													isshow = "none";
												} else {
													isshow = "block";
												}
											}
											ele.style.display = isshow;
										} else {
											ele.style.display = "none";
										}
									});
								}
							});
							resolve();
						});
					})
					.catch((err) => {
						reject("初始化地图失败", err);
					});
			});
		},
		async getAllRoadsLangLat() {
			const data = await getLonLatByAllRoads();
			this.allRoadslanglat = data.msgContent;
			//获取所有id
			this.allRoadsIds = [];
			this.allRoadslanglat.forEach((ele) => {
				this.allRoadsIds.push(ele.sectionId);
			});
		},
		initEvent() {
			const { map, $attrs } = this;
			const { ...attrs } = $attrs;
			if (!map) {
				return;
			}
			for (const evtKey in attrs) {
				if (evtKey !== "onLoad") {
					// map.on("click", id, (evt) => {
					//   this.$emit("click", { ...evt });
					// });\
					map.on("click", (evt) => {
						this.$emit("click", { ...evt });
					});
				}
			}

			// for (const evtKey in $listeners) {
			//   if (
			//     evtKey !== "load" &&
			//     Object.hasOwnProperty.call($listeners, evtKey)
			//   ) {
			//     map.on(evtKey, (evt) => {
			//       this.$emit(evtKey, { ...evt });
			//     });
			//   }
			// }
		},
		observeResize() {
			if (!ResizeObserver || !this.$refs.mapEl) {
				return;
			}
			const debouncedResize = debounce(() => {
				this.map.resize();
			}, 100);
			const observer = new ResizeObserver(debouncedResize);
			observer.observe(this.$refs.mapEl);
		},
		getOptions() {
			const options = {
				container: this.$refs.mapEl,
				logoControl: false,
				bounds: defaultBounds,
				maxBounds: defaultBounds,
				maxZoom: 17,
				minZoom: 3,
			};
			["center", "zoom", "pitch", "maxZoom", "minZoom"].forEach((key) => {
				const opt = this[key];
				if (opt !== null && opt !== undefined) {
					options[key] = opt;
				}
			});

			return options;
		},
		watchMapOptions() {
			["pitch", "maxZoom", "minZoom"].forEach((key) => {
				this.$watch(key, (newVal, oldVal) => {
					const { map } = this;
					if (!map) {
						return;
					}
					const fnName = `set${
						key.charAt(0).toUpperCase() + key.slice(1)
					}`;
					if (!map[fnName]) {
						return;
					}
					map[fnName](newVal);
				});
			});
		},
		fitView() {
			let { map, center, zoom, bounds, fitBoundsOptions } = this;
			if (!map) {
				return;
			}
			fitBoundsOptions = fitBoundsOptions || {};
			if (!fitBoundsOptions.padding) {
				fitBoundsOptions.padding = 40;
			}
			// if (center && center.length) {
			//   map.setZoom(zoom);
			//   map.setCenter(center);
			//   return;
			// }
			return;

			if (bounds) {
				map.fitBounds(bounds, fitBoundsOptions);
			}
		},
		getMap() {
			if (this.map) {
				return Promise.resolve(this.map);
			}
			if (this._initPromise) {
				return this._initPromise.then(() => this.map);
			}
			return Promise.reject("地图未初始化");
		},
		loadMinemapAPI() {
			if (window.minemap) {
				return Promise.resolve();
			}
			if (window.loadMinemapAPIPromise) {
				return window.loadMinemapAPIPromise;
			}
			window.loadMinemapAPIPromise = Promise.all([
				this.loadScript(),
				// this.loadStyle(),
			])
				.then((r) => {
					console.log("Minemap 资源加载成功", r);
					window.loadMinemapAPIPromise = null;
				})
				.catch((err) => {
					console.error("Minemap 资源加载错误:", err);
					window.loadMinemapAPIPromise = null;
				});
			return window.loadMinemapAPIPromise;
		},
		loadScript() {
			// return new Promise((resolve, reject) => {
			//   // 基础地图js
			//   const script = document.createElement("script");
			//   script.type = "text/javascript";
			//   script.async = true;
			//   script.defer = true;
			//   script.src = "https://minedata.cn/minemapapi/v2.1.0/minemap.js";
			//   script.onload = () => {
			//     console.log("Minemap JS加载成功");
			//     resolve();
			//   };
			//   script.onerror = (err) => {
			//     console.error("Minemap JS加载错误:", err);
			//     reject();
			//   };
			//   document.body.appendChild(script);
			//   //计算两点间的距离
			//   const script1 = document.createElement("script");
			//   script1.type = "text/javascript";
			//   script1.async = true;
			//   script1.defer = true;
			//   script1.src = "https://minedata.cn/minemapapi/v3.3.0/plugins/turf/turf.min.js";
			//   script1.onload = () => {
			//     console.log("Minemapturf工具 JS加载成功");
			//     resolve();
			//   };
			//   script1.onerror = (err) => {
			//     console.error("Minemapturf工具 JS加载错误:", err);
			//     reject();
			//   };
			//   document.body.appendChild(script1);
			// });
		},
		loadStyle() {
			return new Promise((resolve, reject) => {
				let link = document.createElement("link");
				link.rel = "stylesheet";
				link.type = "text/css";
				link.href =
					"https://map.hope.cmet1965.com:58000/minemapapi/v2.1.0/minemap-dark.css";
				link.onload = () => {
					console.log("Minemap CSS加载成功");
					resolve();
				};
				link.onerror = (err) => {
					console.error("Minemap CSS加载错误:", err);
					reject();
				};
				document.querySelector("head").appendChild(link);
			});
		},
		getThatRows(val, level) {
			console.log("getThatRows", val, level);
			if (val == "106") return;
			if (!this.map) return;
			this.selectLevel = level;
			//获取当前选择的组织结构下的所有路段id / 当前选择的路段id
			let ids = [];
			this.allRoads.forEach((ele) => {
				if (level == 0 && ele.level == "3") {
					ids.push(ele.organizationId);
				}
				if (level == 1 && ele.level == "3" && ele.provinceId == val) {
					ids.push(ele.organizationId);
				}
				if (level == 2 && ele.level == "3" && ele.pnode == val) {
					ids.push(ele.organizationId);
				}
			});
			if (level == 3) {
				ids.push(val);
			}
			//清除已有的线路的图层和路况
			if (this.selectLineLayer.length > 0) {
				for (
					let index = 0;
					index < this.selectLineLayer.length;
					index++
				) {
					const sid = this.selectLineLayer[index];
					this.map.getSource("linesource" + sid + "1") &&
						this.map.removeSource("linesource" + sid + "1");
					this.map.getSource("linesource" + sid + "2") &&
						this.map.removeSource("linesource" + sid + "2");
					this.map.getLayer("linelayer" + sid + "1") &&
						this.map.removeLayer("linelayer" + sid + "1");
					this.map.getLayer("linelayer" + sid + "2") &&
						this.map.removeLayer("linelayer" + sid + "2");
					this.map.getLayer("linesymbollayer" + sid + "1") &&
						this.map.removeLayer("linesymbollayer" + sid + "1");
					this.map.getLayer("linesymbollayer" + sid + "2") &&
						this.map.removeLayer("linesymbollayer" + sid + "2");

					// const vist = this.map.getLayoutProperty('trafficlayer' + sid + '1', 'visibility')
					// this.trafficVisibility = vist

					this.map.getSource("trafficsource" + sid + "1") &&
						this.map.removeSource("trafficsource" + sid + "1");
					this.map.getSource("trafficsource" + sid + "2") &&
						this.map.removeSource("trafficsource" + sid + "2");
					this.map.getLayer("trafficlayer" + sid + "1") &&
						this.map.removeLayer("trafficlayer" + sid + "1");
					this.map.getLayer("trafficlayer" + sid + "2") &&
						this.map.removeLayer("trafficlayer" + sid + "2");
					this.markerList["marker" + sid].remove();
					this.markerList["marker1" + sid].remove();
				}
			}
			this.markerDomListID = [];
			//重置路况长度
			this.trafficInfo.mileage = JSON.parse(
				JSON.stringify(defaultMileage)
			);
			this.selectLineLayer = [];

			// 需要绘制的线路
			let needDrawRoadList = [];
			if (ids.length > 0) {
				for (let i = 0; i < ids.length; i++) {
					// this.allRoadslanglat.forEach(item => {
					//   if(ids[i] == item.sectionId) {
					//     needDrawRoadList.push(item)
					//   }
					// });

					// console.log('需要绘制的路段')
					// console.log(needDrawRoadList)
					this.getRoadsLngLat(ids[i]);
				}
			}
		},
		//定时更新路况
		setIntGetAddTrafficLayer() {
			// 删掉已有的线路路况
			if (this.selectLineLayer.length > 0) {
				this.trafficInfo.mileage = JSON.parse(
					JSON.stringify(defaultMileage)
				);
				for (
					let index = 0;
					index < this.selectLineLayer.length;
					index++
				) {
					const sid = this.selectLineLayer[index];
					this.map.getSource("trafficsource" + sid + "1") &&
						this.map.removeSource("trafficsource" + sid + "1");
					this.map.getSource("trafficsource" + sid + "2") &&
						this.map.removeSource("trafficsource" + sid + "2");
					this.map.getLayer("trafficlayer" + sid + "1") &&
						this.map.removeLayer("trafficlayer" + sid + "1");
					this.map.getLayer("trafficlayer" + sid + "2") &&
						this.map.removeLayer("trafficlayer" + sid + "2");
					let sname = "";
					for (let key in defaultMileage) {
						if (sid == defaultMileage[key].id) {
							sname = key;
						}
					}
					//每条路的上行下行
					this.getAddTrafficLayer({
						sectionName: sname,
						sectionId: sid,
						dir: 1,
					});
					this.getAddTrafficLayer({
						sectionName: sname,
						sectionId: sid,
						dir: 2,
					});
				}
			}
		},

		// 获取单条路段的经纬度
		async getRoadsLngLat(id, leng, idx) {
			if (!id) return;
			const data = await getLonLatByAllRoads({
				sectionId: id,
				direction: 1,
			}); // 1上行
			const data1 = await getLonLatByAllRoads({
				sectionId: id,
				direction: 2,
			}); //2下行
			if (data.msgContent[0] && data1.msgContent[0]) {
				this.selectLineLayer.push(id);
				//上行
				let arr = "";
				let msgContent = data.msgContent[0];
				data.msgContent.forEach((ele, index) => {
					let dou = "";
					if (index > 0) {
						dou = ",";
					}
					arr = arr + dou + ele.linePoints;
				});
				msgContent.linePoints = arr;

				//下行
				let arr1 = "";
				let msgContent1 = data1.msgContent[0];
				data1.msgContent.forEach((ele, index) => {
					let dou = "";
					if (index > 0) {
						dou = ",";
					}
					arr1 = ele.linePoints + dou + arr1;
				});
				msgContent1.linePoints = arr1;
				this.getAddLineLayer(msgContent);
				this.getAddLineLayer(msgContent1);
				this.roadMarker(msgContent);
			}
		},
		//线路图层
		getAddLineLayer(item) {
			let linePoints = `[${item.linePoints}]`;
			linePoints = JSON.parse(linePoints);
			let { map } = this;
			//       linesource/linelayer/symbolLayerId(数据源/线路/线路上的文字) + 路段id + dir（1是上行 2是下行）
			const sourceId = "linesource" + item.sectionId + item.dir;
			const layeyId = "linelayer" + item.sectionId + item.dir;
			const symbolLayerId = "linesymbollayer" + item.sectionId + item.dir;
			var jsonData = {
				type: "FeatureCollection",
				features: [
					{
						type: "Feature",
						geometry: {
							type: "LineString",
							coordinates: linePoints,
						},
						properties: {
							title: item.sectionName,
							kind: item.sectionId,
						},
					},
				],
			};
			!this.map.getSource(sourceId) &&
				map.addSource(sourceId, {
					type: "geojson",
					data: jsonData,
				});

			let beforeIdtext = "";
			let beforeIdline = "";
			if (map.getLayer("point-outer-cluster-0")) {
				// point-outer-cluster-0 是视频监控的聚合图层
				beforeIdtext = "point-outer-cluster-0";
				beforeIdline = "point-outer-cluster-0";
			}
			//  设置addLayer的第二个参数beforeId，表示这个图层显示在beforeId的图层下面
			if (item.dir == 2) {
				beforeIdline = `linesymbollayer${item.sectionId}1`;
			}
			// 线路图层
			!this.map.getLayer(layeyId) &&
				map.addLayer(
					{
						id: layeyId,
						type: "line",
						source: sourceId,
						layout: {
							"line-join": "round",
							"line-cap": "round",
							"border-visibility": "visible", //是否开启线边框
						},

						paint: {
							"line-width": 6,
							"line-color": {
								type: "categorical",
								property: "kind",
								stops: [
									[1, "#7FAFFD"],
									[2, "#7FAFFD"],
								],
								default: "#7FAFFD", //4DBCFA
							},
							"line-border-width": 1, //设置线边框宽度
							"line-border-opacity": 0.5, //设置线边框透明度
							"line-border-color": "#fff", //设置线边框颜色
						},
					},
					beforeIdline
				);
			//绘制线路图层
			this.getAddTrafficLayer(item);
			//文字（高速路名称）图层
			!this.map.getLayer(symbolLayerId) &&
				map.addLayer(
					{
						id: symbolLayerId,
						type: "symbol",
						source: sourceId,
						layout: {
							"text-field": "{title}",
							"text-size": 14,
							"symbol-placement": "line",
						},
						paint: {
							"text-color": "#ffffff",
							"text-halo-color": "#ffffff",
							"text-halo-width": 0.3,
						},
					},
					beforeIdtext
				);
			if (this.selectLevel == 3) {
				const centerNum = Math.ceil(linePoints.length / 2);
				let centerPoint = linePoints[centerNum];
				// 跳转至该线路
				map.flyTo({
					center: centerPoint,
					zoom: 9,
				});
			}
			const qmz = JSON.parse(localStorage.getItem("mapCLkmz"));
			// this.map.moveLayer(layeyId, 'b5ebe9f4b52d23fb83170b4936b56429') //千米桩
			this.map.moveLayer(layeyId, qmz.MILESTONE_KM); //千米桩
			this.map.moveLayer(layeyId, qmz.MILESTONE_HM); //百米桩
		},
		//路况图层
		async getAddTrafficLayer(item) {
			// console.log('aaaaaaaaaa',item.sectionName)
			let { map } = this;
			const _that = this;
			// const linePoints = JSON.parse(`[${item.linePoints}]`)
			// const starlanglat = linePoints[0][0] + ',' + linePoints[0][1]
			// const endlanglat = linePoints[linePoints.length - 1][0] + ','+linePoints[linePoints.length - 1][1]
			const sourceId = "trafficsource" + item.sectionId + item.dir;
			const layeyId = "trafficlayer" + item.sectionId + item.dir;
			// const msgcont = await getTrackDriving({startIndex: starlanglat, endIndex: endlanglat})
			getTrackDriving({
				sectionCode: item.sectionId,
				direction: item.dir,
			})
				.then((msgcont) => {
					// 计算里程
					const options = { units: "kilometers" };
					// console.log(this.trafficInfo)
					const sectionName = item.sectionName;

					msgcont?.features?.forEach((val) => {
						let distance = 0;
						const langlatList = val.geometry.coordinates;
						for (let i = 0; i < langlatList.length - 1; i++) {
							const start = langlatList[i];
							const end = langlatList[i + 1];
							let newDistance = turf.distance(
								turf.point(start),
								turf.point(end),
								options
							);
							distance += newDistance;
						}
						const start1 = val.geometry.coordinates[0];
						const end1 =
							val.geometry.coordinates[
								val.geometry.coordinates.length - 1
							];
						let newDistance1 = turf.distance(
							turf.point(start1),
							turf.point(end1),
							options
						);
						// distance = Number(distance.toFixed(2))
						if (val.properties.kind == 1) {
							// _that.trafficInfo.mileage.all.m1 += distance
							_that.trafficInfo.mileage[item.sectionName].m1 +=
								distance;
						} else if (val.properties.kind == 2) {
							// _that.trafficInfo.mileage.all.m2 += distance
							_that.trafficInfo.mileage[item.sectionName].m2 +=
								distance;
						} else if (val.properties.kind == 3) {
							// _that.trafficInfo.mileage.all.m3  += distance
							_that.trafficInfo.mileage[item.sectionName].m3 +=
								distance;
						} else if (val.properties.kind == 7) {
							// _that.trafficInfo.mileage.all.m4 += distance
							_that.trafficInfo.mileage[item.sectionName].m4 +=
								distance;
						} else if (val.properties.kind == 0) {
							//  _that.trafficInfo.mileage.all.m0 += distance
							_that.trafficInfo.mileage[item.sectionName].m0 +=
								distance;
						} else {
						}
					});
					(this.trafficInfo.date = new Date().getTime()),
						this.$store.commit(
							"changeTrafficMileage",
							this.trafficInfo
						);
					// trafficInfo:{
					//   visibility: 'none',
					// }
					!this.map.getSource(sourceId) &&
						map.addSource(sourceId, {
							type: "geojson",
							data: {
								type: "FeatureCollection",
								features: msgcont.features,
							},
						});
					!this.map.getLayer(layeyId) &&
						map.addLayer({
							id: layeyId,
							type: "line",
							source: sourceId,
							layout: {
								"line-join": "round",
								"line-cap": "round",
								"border-visibility": "visible", //是否开启线边框
								visibility: _that.trafficInfo.visibility,
								// "visibility": "visible",
							},

							paint: {
								"line-width": 4,
								"line-color": {
									type: "categorical",
									property: "kind",
									stops: [
										[0, "#FF0000"],
										[1, "#3FFF00"],
										[2, "#FFF700"],
										[3, "#FFA500"],
										[7, "#710505"],
									],
									default: "#3FFF00", //4DBCFA
								},
							},
						});
					const qmz = JSON.parse(localStorage.getItem("mapCLkmz"));
					// this.map.moveLayer(layeyId, 'b5ebe9f4b52d23fb83170b4936b56429') //千米桩
					this.map.moveLayer(layeyId, qmz.MILESTONE_KM); //千米桩
					this.map.moveLayer(layeyId, qmz.MILESTONE_HM); //百米桩
				})
				.catch((err) => {
					console.log("交通:" + err);
				});
		},
		// 路段上浮起来的路段名
		roadMarker(item) {
			const linePoints = JSON.parse(`[${item.linePoints}]`);
			const zj = parseInt(linePoints.length / 2);
			const langlat = linePoints[zj];
			//大的marker
			var el = document.createElement("div");
			const w = item.sectionName.length * 16;
			el.id = "marker" + item.sectionId;
			// el.addClass("rodeMarkerDiv")
			el.className = "rodeMarkerDiv";
			el.style["background-image"] = `url(${markerbg})`;
			el.style["background-size"] = `100% 100%`;
			el.style["padding"] = "6px 0";
			el.style["height"] = "74px";
			el.style["width"] = w + "px";
			el.style["text-align"] = "center";
			el.style["font-size"] = "16px";

			var spn = document.createElement("span");
			spn.innerHTML = item.sectionName;
			spn.style["color"] = "#fff";
			spn.style["font-style"] = "italic";
			el.appendChild(spn);

			//小的marker
			var el1 = document.createElement("div");
			const w1 = item.sectionName.length * 12;
			el1.id = "marker" + item.sectionId;
			// el.addClass("rodeMarkerDiv")
			el1.className = "rodeMarkerDiv1";
			el1.style["background-image"] = `url(${markerbg})`;
			el1.style["background-size"] = `100% 100%`;
			el1.style["padding"] = "0";
			el1.style["height"] = "45px";
			el1.style["width"] = w1 + "px";
			el1.style["text-align"] = "center";
			el1.style["font-size"] = "12px";

			var spn1 = document.createElement("span");
			spn1.innerHTML = item.sectionName;
			spn1.style["color"] = "#fff";
			spn1.style["font-style"] = "italic";

			el1.appendChild(spn1);

			//全国显示小图标 否则显示大图标
			if (this.$store.state.road.selectRoadId) {
				el.style.display = "none";
				el1.style.display = "block";
			} else {
				el.style.display = "block";
				el1.style.display = "none";
			}

			const halfw = 0 - w / 2;
			const halfw1 = 0 - w1 / 2;
			var marker = new minemap.Marker(el, { offset: [halfw, -70] })
				.setLngLat(langlat)
				.addTo(this.map);
			var marker1 = new minemap.Marker(el1, { offset: [halfw1, -40] })
				.setLngLat(langlat)
				.addTo(this.map);
			this.markerList["marker" + item.sectionId] = marker;
			this.markerList["marker1" + item.sectionId] = marker1;
			this.markerDomListID.push(el);
			this.markerDomListID.push(el1);
		},
		fontLengthTowidth() {
			const obj = {};
		},
	},
	render() {
		const { loaded, $slots } = this;
		return (
			<div class="cm-map">
				<div
					ref="mapEl"
					class="cm-map__wrap"
				>
					{!loaded ? (
						<div class="cm-map__loading">Loading...</div>
					) : (
						$slots.default && $slots.default()
					)}
				</div>
			</div>
		);
	},
});
</script>

<style lang="scss">
@import "./style/map.scss";
.cm-map {
	position: absolute;
	width: 100%;
	height: 100%;
	left: 0;
	top: 0;
}
.cm-map__wrap {
	position: relative;
	width: 100%;
	height: 100%;
}
.cm-map__loading {
	position: absolute;
	top: 50%;
	left: 50%;
	max-width: 40%;
	font-size: 32px;
	color: #0f2a3f;
	transform: translate(-50%, -50%);
}
.cm-map__loading img {
	width: 100%;
}
</style>
