
<template>
	<view class="page">
		<u-navbar title="运维" :border-bottom="false" :background="bgc" title-color='#2E4975' title-size='36'
			height='45'></u-navbar>
		<map class="map" id="map" ref="map" :scale="zoomSize" :latitude="latitude" :longitude="longitude"
			:show-location="true" :markers="markers" :polygons="polyline" @markertap="onMarkerTap">
			<cover-view class="park" @click="toggleIconAndCallout">
				<cover-image class="img" src="https://lxnapi.ccttiot.com/bike/img/static/uRiYQZQEb3l2LsltEsyW"
					mode=""></cover-image>
			</cover-view>
		</map>
		<view class="btn_box">
			<view class="btn1" @click="qecodelock()">
				车辆扫码
			</view>
			<view class="btn2" @click="topages()">
				车辆搜索
			</view>
		</view>
		<view class="bot">
			<view class="btn" @click="topage()">
				维修换电
			</view>
			<view class="info">
				<view class="cont">
					<view class="cont_top">
						全部工单
					</view>
					<view class="cont_bot">
						{{infonum.allNum}}
					</view>
				</view>
				<view class="cont">
					<view class="cont_top">
						待换电
					</view>
					<view class="cont_bot">
						{{infonum.powerReplacementNum}}
					</view>
				</view>
				<view class="cont">
					<view class="cont_top">
						待维修
					</view>
					<view class="cont_bot">
						{{infonum.repairNum}}
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				bgc: {
					backgroundColor: "#F7FAFE",
				},
				latitude: '26.940805',
				longitude: '120.356157',
				isMap: false,
				zoomSize: 15,
				markers: [],
				polyline: [],
				polygons: [],
				fixdata: [],
				eledata: [],
				listData: [],
				infonum: {},
				areaId:0
			}
		},
		onShow() {
			// this.$store.dispatch('userInfo', this.$u).then(() => {
			// 	// 执行其他操作...
			// });
			
			
			
			
			this.getordernum()
		},
		onLoad() {
			if(uni.getStorageSync('adminAreaid')){
				this.areaId = uni.getStorageSync('adminAreaid')
				
			}
			this.getArea()
		},
		computed: {
			userId() {
				return this.$store.getters.userId;
			},
		},
		methods: {
			topages() {
				uni.navigateTo({
					url: '/pages_admin/order/search_device'
				})
			},
			qecodelock() {
				uni.scanCode({
					onlyFromCamera: true,
					scanType: ['qrCode'],
					success: res => {
			
						let sn = null;
						let queryParams = res.result.split('?')[1];
						if (queryParams) {
							let params = queryParams.split('&');
							params.forEach(param => {
								let [key, value] = param.split('=');
								if (key === 'sn') {
									sn = value;
								}
							});
						}
			
						this.sn = sn
						if (this.sn != '') {
							uni.navigateTo({
								url: '/pages_admin/order/device_detail?id=' + this.sn
							})
						}
			
					},
					fail: err => {
						console.error('扫描失败：', err);
						uni.showToast({
							title: '扫描失败',
							icon: 'none'
						});
					}
				});
			},
			toggleIconAndCallout() {
				this.showIconAndCallout = !this.showIconAndCallout;
				this.markers.forEach(marker => {
					if (marker.isParking) {
						marker.callout.display = this.showIconAndCallout ? 'ALWAYS' : 'BYCLICK';
					}
				});
			},
			getParking() {
				let data = {
					areaId: this.areaId
				};
				this.$u.get('/app/parking/list?', data).then((res) => {
					if (res.code === 200) {
						const newMarkers = [];
						const type1Data = [];
						const type2Data = [];
						const type3Data = [];
			
						res.rows.forEach(row => {
							if (row.type == 1) {
								type1Data.push(row);
							} else if (row.type == 2) {
								type2Data.push(row);
							} else if (row.type == 3) {
								type3Data.push(row);
							}
			
							newMarkers.push({
								id: parseFloat(row.parkingId),
								latitude: parseFloat(row.latitude),
								longitude: parseFloat(row.longitude),
								width: 20,
								height: 29,
								iconPath: row.type == 1 ?
									'https://lxnapi.ccttiot.com/bike/img/static/up2xXqAgwCX5iER600k3' :
									row.type == 2 ?
									'https://lxnapi.ccttiot.com/bike/img/static/u53BAQcFIX3vxsCzEZ7t' :
									'https://lxnapi.ccttiot.com/bike/img/static/uDNY5Q4zOiZTCBTA2Jdq',
								callout: {
									content: row.parkingName,
									color: '#ffffff',
									fontSize: 14,
									borderRadius: 10,
									bgColor: row.type == 1 ? '#3A7EDB' : row.type == 2 ?
										'#FFC107' : '#FF473E',
									padding: 6,
									display: 'BYCLICK'
								},
								isParking: true
							});
						});
			
						this.$set(this, 'markers', [...this.markers, ...newMarkers]);
			
						const validBoundaries1 = type1Data.map(row => row.boundaryStr).filter(boundary =>
							typeof boundary === 'string' && boundary.trim() !== '');
						const polylines1 = this.convertBoundaryToPolylines(validBoundaries1, 1);
			
						const validBoundaries2 = type2Data.map(row => row.boundaryStr).filter(boundary =>
							typeof boundary === 'string' && boundary.trim() !== '');
						const polylines2 = this.convertBoundaryToPolylines(validBoundaries2, 2);
			
						const validBoundaries3 = type3Data.map(row => row.boundaryStr).filter(boundary =>
							typeof boundary === 'string' && boundary.trim() !== '');
						const polylines3 = this.convertBoundaryToPolylines(validBoundaries3, 3);
			
						this.polyline = this.polyline.concat(polylines1, polylines2, polylines3);
			
					} else {
						console.error("Error fetching parking data:", res);
					}
				}).catch(error => {
					console.error("Error fetching parking data:", error);
				});
			},
			onMarkerTap(e) {
				console.log('点击了标记：', e);
				this.sn = e.detail.markerId;
				this.todetail();
			},
			todetail() {
				uni.navigateTo({
					url: '/page_shanghu/repair/repair_index?id=' + this.sn
				});
			},
			getmarks() {
				let data ={
						areaId:this.areaId
				}
				this.$u.get(`/appVerify/adminOrder/list?` ,data).then((res) => {
					if (res.code == 200) {
						console.log('调用了');
						this.listData = res.rows;
						this.fixdata = [];
						this.eledata = [];
						res.rows.forEach(item => {
							if (item.type == 1&&item.status==2) {
								this.fixdata.push(item);
							} else if (item.type == 2&&item.status==2) {
								this.eledata.push(item);
							}
						});
						this.updateMarkers();
						this.getParking()
					} else {
						console.error('接口返回错误:', res);
					}
				}).catch(error => {
					console.error("接口请求失败:", error);
				});
			},
			updateMarkers() {
					this.markers = [];
					const markerIds = new Set(); // 用于跟踪已添加的 id
			
					const addMarker = (item, iconPath) => {
						const id = parseFloat(item.sn);
						if (!markerIds.has(id)) {
							markerIds.add(id);
							this.markers.push({
								id: id,
								latitude: parseFloat(item.latitude),
								longitude: parseFloat(item.longitude),
								width: 40,
								height: 40,
								iconPath: iconPath,
							});
						}
					};
					this.fixdata.forEach(item => {
						addMarker(item, 'https://lxnapi.ccttiot.com/bike/img/static/u1UD93BU1vfshWFoDwgX');
					});
					this.eledata.forEach(item => {
						addMarker(item, 'https://lxnapi.ccttiot.com/bike/img/static/u4UKmB47AxOj3YKIaajM');
					});
					console.log(this.markers, '更新后的标记');
				},
			topage() {
				uni.navigateTo({
					url: '/page_shanghu/repair/repair_index'
				});
			},
			getordernum() {
				let data ={
					areaId:this.areaId
				}
				this.$u.get('/appVerify/adminOrder/num?' ,data).then((res) => {
					if (res.code === 200) {
						this.infonum = res.data;
					}
				}).catch(error => {
					console.error("获取订单数量数据失败:", error);
				});
			},
			getArea() {
				
				let id = this.areaId
				this.$u.get("/app/area/" + id).then((res) => {
				
					if (res.code == 200) {
						this.latitude =res.data.latitude
						this.longitude = res.data.longitude
						// this.areaInfo = res.data
						const polylines = this.convertBoundaryToPolyline(res.data.boundaryStr)
						this.polyline.push(polylines)
						this.getmarks()
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						});
					}
				});
			},
			convertBoundaryToPolylines(boundaries,num) {
				if(num==1){
					console.log('判断');
					return boundaries.map(boundary => {
						if (!boundary) return null;
						let coords;
						try {
							coords = JSON.parse(boundary);
						} catch (error) {
							console.error("Error parsing boundary JSON:", error);
							return null;
						}
						if (!Array.isArray(coords)) {
							console.error("Parsed boundary is not an array:", coords);
							return null;
						}
						const points = coords.map(coord => ({
							latitude: coord[1],
							longitude: coord[0]
						}));
						return {
							points: points,
							fillColor: "#3A7EDB40", //填充颜色
							strokeColor: "#3A7EDB", //描边颜色
							strokeWidth: 2, //描边宽度
							zIndex: 1, //层级
							
						};
					}).filter(polyline => polyline !== null); // 过滤掉无效的折线数据
				}else if(num==2){
					return boundaries.map(boundary => {
						if (!boundary) return null;
						let coords;
						try {
							coords = JSON.parse(boundary);
						} catch (error) {
							console.error("Error parsing boundary JSON:", error);
							return null;
						}
						if (!Array.isArray(coords)) {
							console.error("Parsed boundary is not an array:", coords);
							return null;
						}
						const points = coords.map(coord => ({
							latitude: coord[1],
							longitude: coord[0]
						}));
						return {
							points: points,
							fillColor: "#FFF5D640", //填充颜色
							strokeColor: "#FFC107", //描边颜色
							strokeWidth: 2, //描边宽度
							zIndex: 1, //层级
					
						};
					}).filter(polyline => polyline !== null); // 过滤掉无效的折线数据
				}else if(num==3){
					return boundaries.map(boundary => {
						if (!boundary) return null;
						let coords;
						try {
							coords = JSON.parse(boundary);
						} catch (error) {
							console.error("Error parsing boundary JSON:", error);
							return null;
						}
						if (!Array.isArray(coords)) {
							console.error("Parsed boundary is not an array:", coords);
							return null;
						}
						const points = coords.map(coord => ({
							latitude: coord[1],
							longitude: coord[0]
						}));
						return {
							points: points,
							fillColor: "#FFD1CF40", //填充颜色
							strokeColor: "#FF473E", //描边颜色
							strokeWidth: 2, //描边宽度
							zIndex: 1, //层级
					
						};
					}).filter(polyline => polyline !== null); // 过滤掉无效的折线数据
				}
				
			},
			
			convertBoundaryToPolyline(boundary) {
				if (!boundary) return null;
				const points = JSON.parse(boundary).map(coord => ({
					latitude: coord[1],
					longitude: coord[0]
				}));
				return {
					points: points,
					fillColor: "#55888840",
					strokeColor: "#22FF00",
					strokeWidth: 2,
					zIndex: 1,
				};
			},
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F7FAFE;
	}

	.page {
		width: 750rpx;
		height: 100vh;
		.map {
			position: relative;
			width: 750rpx;
			height: 65vh;
			
			.park {
				position: absolute;
				display: flex;
				align-items: center;
				justify-content: center;
				right: 30rpx;
				bottom: 200rpx;
				// background-color: #fff;
				border-radius: 50%;
				width: 82rpx;
				height: 82rpx;
				z-index: 10;
			
				.img {
					width: 82rpx;
					height: 82rpx;
				}
			}
		}
		.btn_box {
			width: 100%;
			display: flex;
			flex-wrap: nowrap;
			
			.btn1 {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 376rpx;
				height: 5vh;
				background: #D4ECFF;
				font-weight: 500;
				font-size: 40rpx;
				color: #4C97E7;
			}
		
			.btn2 {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 374rpx;
				height: 5vh;
				background: #4C97E7;
				font-weight: 500;
				font-size: 40rpx;
				color: #FFFFFF;
			}
		}
		.bot {
			padding: 40rpx 32rpx;
			width: 750rpx;
			height: 30vh;
			background: #fff;
			border-radius: 60rpx 60rpx 0 0;

			.btn {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 686rpx;
				height: 90rpx;
				background: #4C97E7;
				border-radius: 54rpx 54rpx 54rpx 54rpx;
				font-weight: 500;
				font-size: 40rpx;
				color: #FFFFFF;
			}

			.info {
				margin-top: 24rpx;
				display: flex;
				flex-wrap: nowrap;
				align-items: center;
				justify-content: space-around;

				.cont {
					width: 112rpx;
					display: flex;
					flex-wrap: wrap;
					justify-content: center;

					.cont_top {
						text-align: center;
						width: 112rpx;
						font-weight: 500;
						font-size: 28rpx;
						color: #3D3D3D;
					}

					.cont_bot {
						text-align: center;
						width: 112rpx;
						font-weight: 500;
						font-size: 28rpx;
						color: #3D3D3D;
					}
				}
			}
		}
	}
</style>