<template>
	<view class="page">
		<!-- 用户首页显示 -->
		<view class="useryonghu">
			<u-navbar :is-back="false" title="首页" :border-bottom="false" :background="bgc" title-color='#fff'
				title-size='44' height='50'></u-navbar>
			<view class="ditu">
				<view class="dtxs">
					<map class='map' id="map" :latitude="latitude" :longitude="longitude" @markertap="handleMarkerClick"
						:show-location="true" :markers="covers" :scale="mapScale" />
				</view>
				<view class="fujin">
					<image src="https://api.ccttiot.com/smartmeter/img/static/uqv3e5ThWL8DqrRNBfoA" mode=""
						@click="btnindex(5)"></image>
					<image src="https://api.ccttiot.com/smartmeter/img/static/u7yxUJZqgPzESeI4tmiz" mode=""
						@click="btnindex(6)" v-if="isMch"></image>
					<image @click="onControltap" style="width: 76rpx;height: 76rpx;position: absolute;right: 40rpx;"
						src="https://api.ccttiot.com/smartmeter/img/static/uOS9p7Sy1K9WpVQgD3b9" mode=""></image>
				</view>
				<view class="tubiao">
					<view class="gr" @click="btnindex(1)">
						<image src="https://api.ccttiot.com/smartmeter/img/static/uJBKoGWpRH2lM1NpQU0I" mode=""
							style="width: 96rpx;height:98rpx;"></image>
						<!-- 个人中心 -->
					</view>
					<view class="gr" @click="btnindex(2)">
						<image src="https://api.ccttiot.com/smartmeter/img/static/u8rWtdPtHabALkII23Zr" mode=""
							style="width: 96rpx;height:102rpx;"></image>
						<!-- 我的订单 -->
					</view>
					<view class="gr" @click="btnindex(3)">
						<image src="https://api.ccttiot.com/smartmeter/img/static/uphoDfOVnT6VEyj6glfF" mode=""
							style="width: 96rpx;height:98rpx;"></image>
						<!-- 附近门店 -->
					</view>
					<view class="gr" @click="btnindex(4)">
						<image src="https://api.ccttiot.com/smartmeter/img/static/uBN46m7mPVlbbPth80FC" mode=""
							style="width: 96rpx;height:94rpx;"></image>
						<!-- 联系客服 -->
					</view>
				</view>
				<view class="guangg" @click="btnad">
					<image :src="imgad" mode=""></image>
				</view>
				<view class="saoma" @click="scanQRCode">
					<view>
						<image src="https://api.ccttiot.com/smartmeter/img/static/uBh15vzRx6gV0wRQj7gi" mode=""></image>
						扫一扫
					</view>
				</view>
			</view>

			<view class="tip_box" v-if="czflag">
				<view class="top">
					<view class="txt">
						系统检测到您的设备未联网或者为蓝牙版本,金额充值失败,请靠近设备进行蓝牙充值
					</view>
				</view>
				<view class="bot">
					<view class="bot_left" @click="czflag = false">
						取消
					</view>
					<view class="bot_right" @click="tocz()">
						蓝牙充值
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				params: {
					year: true,
					month: true,
					day: true,
					hour: false,
					minute: false,
					second: false
				},
				dateindex: 1,

				latitude: '', // 初始纬度  
				longitude: '', // 初始经度   
				covers: [], // 覆盖物数组  
				jinweidu: '',
				userType: '',
				isMch: false,
				imgad: '',
				listmap: [],
				mapScale: 15,
				czflag: false,
				datetime: 0,
				dingobj: '',
				mapContext: null,
				mapScaleInterval: null,
				bgc: {
					backgroundColor: "#8883F0",
				},
				deviceobj:{}
			};
		},
		onLoad(option) {
			if (option.flag) {
                let id = option.id
				this.$u.get(`/app/device/${id}/withSuitList`).then((res) => {
					if (res.code == 200) {
						this.deviceobj = res.data;
					}
				})
				let that = this
				uni.showModal({
					title: '提示',
					content: '该设备未被绑定,你需进行绑定吗？',
					success: function(res) {
						if (res.confirm) {
							let data = {
								deviceNo: id
							}
							that.$u.put("/app/device/bind", data).then(res => {
								if (res.code == 200) {
									uni.navigateTo({
										url: '/page_user/sbdetail?id=' +that.deviceobj.deviceId
									})
									// uni.showModal({
									// 	title: '提示',
									// 	content: '绑定成功，需前去设置吗？',
									// 	success: function(res) {
									// 		if (res.confirm) {
												
									// 		} else if (res.cancel) {

									// 		}
									// 	}
									// })
								} else {
									uni.showToast({
										title: res.msg,
										icon: 'none',
										duration: 1000
									})
								}
							})
						} else if (res.cancel) {
							// uni.navigateTo({
							// 	url: '/pages/shouye/index'
							// })
						}
					}
				})
			}
		},
		onShow() {
			this.logins()
			this.getad()
			this.gethuidaio()
		},
		onReady() {
			this.mapContext = uni.createMapContext('map', this)
			this.mapScaleInterval = setInterval(this.updateMarkers, 1000)
		},
		beforeDestroy() {
			// 在组件卸载前清除定时器  
			if (this.mapScaleInterval) {
				clearInterval(this.mapScaleInterval)
				this.mapScaleInterval = null
			}
		},
		methods: {
			btnad() {
				this.$u.get("/app/ad").then((res) => {
					if (res.code == 200) {
						if (res.data.urlType == 1) {
							uni.navigateTo({
								url: '/page_fenbao/webview?url=' + res.data.url
							})
						} else {
							uni.navigateTo({
								url: res.data.url
							})
						}
					}
				})
			},

			
			calculateAnchorX(name) {
				let chineseLength = 0
				let englishLength = 0
				for (let i = 0; i < name.length; i++) {
					const charCode = name.charCodeAt(i)
					if (charCode >= 0x4e00 && charCode <= 0x9fa5) {
						chineseLength++
					} else if (/[a-zA-Z]/.test(name[i])) {
						englishLength = englishLength + 0.3 // 英文长度加1，但视为两个中文字符长度  
					}
				}
				const totalLength = chineseLength + englishLength * 2;
				return -totalLength * 6.5 // 假设每个中文字符对应的 anchorX 偏移是 -6.5
			},

			scanQRCode() {
				uni.scanCode({
					onlyFromCamera: true,
					scanType: ['qrCode'],
					success: res => {
						function getQueryParam(url, paramName) {
							let regex = new RegExp(`[?&]${paramName}=([^&]*)`)
							let results = regex.exec(url);
							return results ? decodeURIComponent(results[1].replace(/\+/g, ' ')) : null
						}
						let sceneValue = res.result
						let decodedValue = decodeURIComponent(sceneValue)
						let id = getQueryParam(decodedValue, 's')
						// console.log(res, id)
						this.$u.get(`/app/device/${id}/withSuitList`).then((res) => {
							if (res.code == 200) {
								uni.navigateTo({
									url: '/page_components/fuwu/index?id=' + id
								})
							}
						})
					},
					fail: err => {
						console.error('扫描失败：', err)
						uni.showToast({
							title: '扫描失败',
							icon: 'none'
						});
					}
				});
			},

			getad() {
				this.$u.get("/app/ad").then((res) => {
					if (res.code == 200) {
						this.imgad = res.data.picture
					}
				})
			},


			btnindex(num) {
				if (num == 2) {
					uni.navigateTo({
						url: '/page_fenbao/statulist/question/index'
					})
				} else if (num == 3) {
					uni.navigateTo({
						url: '/page_fenbao/statulist/about/index'
					})
				} else if (num == 1) {
					uni.navigateTo({
						url: '/page_fenbao/statulist/myorder/index'
					})
				} else if (num == 4) {
					uni.navigateTo({
						url: '/page_fenbao/statulist/merchant/index'
					})
				} else if (num == 5) {
					uni.navigateTo({
						url: '/page_fenbao/statulist/nearby/index'
					})
				} else if (num == 6) {
					uni.switchTab({
						url: '/pages/index/index'
					})
				} else if (num == 7) {
					uni.navigateTo({
						url: '/page_fenbao/statulist/fault/yichang/index'
					})
				}
			},

			onControltap(control) {
				this.setMapScale()
			},
			// 地图回正
			async setMapScale(e, val) {
				let mapContext = uni.createMapContext('map', this);
				let setScale = () => {
					return new Promise((resolve, reject) => {
						mapContext.getScale({
							success: r => {
								resolve()
							}
						})
					})
				};
				await setScale();
				mapContext.moveToLocation({
					success: (res) => {
						const timer = setTimeout(() => {
							clearTimeout(timer);
						}, 500);
					}
				})
			},

			getMyLocation() {
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						// this.jinweidu = res.longitude + ',' + res.latitude;
						// this.latitude = res.latitude;
						// this.longitude = res.longitude;
						this.jinweidu = res.longitude + ',' + res.latitude
						this.latitude = Number(res.latitude.toFixed(5)) - 0.005
						this.longitude = Number(res.longitude.toFixed(5)) + 0.005
						this.setMapScale()
						// 请求附近的店铺  
						this.$u.get("/app/store/listNearBy?center=" + this.jinweidu + '&radius=' + 1000).then(res => {
								if (res.code == 200) {
									this.listmap = res.data
									res.data.forEach(item => {
										if (item.deviceCount !== null && item.deviceCount > 0){
											const shopCover = {
												id: parseFloat(item.storeId),
												latitude: item.lat,
												longitude: item.lng,
												width: 25,
												height: 30,
												iconPath: 'https://api.ccttiot.com/smartmeter/img/static/uZXgsJE6hXbRSwbKILB4',
												label: {
													content: item.name,
													anchorX: (() => {
														if (item.name.length <= 2) {
															return -12
														} else if (item.name.length <= 3) {
															return -20
														} else if (item.name.length <= 4) {
															return -25
														} else if (item.name.length <= 5) {
															return -30
														} else if (item.name.length <= 6) {
															return -35
														} else if (item.name.length <= 8) {
															return -40
														} else if (item.name.length <=
															10) {
															return -45
														} else {
															return -item.name.length * 6
														}
													})(),
													fontWeight: 700,
													color: '#8883F0',
													borderColor:'#fff',
													borderRadius:5,
													bgColor: 'rgba(255, 255, 255, 0.7)'
												}
											}
											this.covers.push(shopCover)
										}
									})
								}
							})
					},
					fail: (err) => {
						console.error('获取位置失败：', err);
					}
				});
			},
			updateMarkers() {
				this.mapContext.getScale({
					success: (res) => {
						this.covers = []; // 清空之前的覆盖物  
						if (res.scale <= 14) {
							this.addMarkersWithoutLabels();
						} else {
							this.addMarkersWithLabels();
						}
					},
					fail: (error) => {
						console.error('获取地图缩放级别失败：', error);
					},
				})
			},
			addMarkersWithoutLabels() {
				this.listmap.forEach((item) => {
					if (item.deviceCount !== null && item.deviceCount > 0){
						const shopCover = {
						id: parseFloat(item.storeId),
						latitude: item.lat,
						longitude: item.lng,
						width: 25,
						height: 30,
						iconPath: 'https://api.ccttiot.com/smartmeter/img/static/uZXgsJE6hXbRSwbKILB4',
						borderColor:'#fff',
						borderRadius:5,
						bgColor: 'rgba(255, 255, 255, 0.7)'
					};
					this.covers.push(shopCover);
					}
				});
			},
			addMarkersWithLabels() {
				this.listmap.forEach((item) => {
					if (item.deviceCount !== null && item.deviceCount > 0){
						const shopCover = {
						id: parseFloat(item.storeId),
						latitude: item.lat,
						longitude: item.lng,
						width: 25,
						height: 30,
						iconPath: 'https://api.ccttiot.com/smartmeter/img/static/uZXgsJE6hXbRSwbKILB4',
						label: {
							content: item.name,
							anchorX: this.calculateAnchorX(item.name),
							fontWeight: 700,
							color: '#8883F0',
							textShadow: '2px 2px 0px white, -2px -2px 0px white, 2px -2px 0px white, -2px 2px 0px white',
							borderColor:'#fff',
							borderRadius:5,
							bgColor: 'rgba(255, 255, 255, 0.7)'
						}
					}
					this.covers.push(shopCover);
					}
					
				});
			},

			handleMarkerClick(event) {
				let markerId = event.markerId;
				uni.navigateTo({
					url: '/page_user/mapditu/index?markerId=' + markerId
				})
			},

			logins() {
				if (uni.getStorageSync('userType')) {
					this.userType = uni.getStorageSync('userType')
					this.userType = '01'
					if (this.userType == '01') {
						this.getDeviceList()
					} else if (this.userType == '00') {
						this.getdevice()
					}
				} else {

				}
				this.getuserinfo()
			},
			getuserinfo() {
				this.$u.get("/app/user/userInfo").then((res) => {
					if (res.code == 200) {
						this.isMch = res.data.isMch
						uni.setStorageSync('userType', res.data.userType)
						this.userType = res.data.userType
						if (this.userType == '01') {
							this.getDeviceList()
						} else if (this.userType == '00') {
							this.getdevice()
						}
					} else {
						this.jmlogin()
					}
				})
			},
			
			jmlogin() {
				let taht = this
				wx.login({
					success(res) {
						if (res.code) {
							let data = {
								loginCode: res.code,
							};
							taht.$u.post('/app/auth/wxLogin', data).then(res => {
								if (res.code == 10003) {
									// uni.navigateTo({
									// 	url: '/pages/login/login'
									// })
								} else if (res.code == 200) {
									uni.setStorageSync('token', res.token);
									taht.logins()
								}
							});
						}
					},
				});
			},



			gethuidaio() {
				this.$u.get('/app/bill/recharge/device/fail/list').then(res => {
					if (res.code == 200) {
						if (res.data.length > 0) {
							this.czflag = true
							this.dingobj = res.data
						} else {
							uni.removeStorageSync('time')
						}
					}
				})
			},

			tocz() {
				this.czflag = false
				uni.navigateTo({
					url: '/page_fenbao/chongzhi?dingobj=' + JSON.stringify(this.dingobj)
				})
			},


		},
		mounted() {
			this.getMyLocation(); // 获取并设置自身位置的覆盖物  
		}
	};
</script>

<style lang="scss">
	/deep/ .u-title {
		padding-bottom: 22rpx;
	}

	/deep/ .u-icon__icon {
		padding-bottom: 22rpx;
	}

	/deep/ .map {
		width: 100%;
		height: 100%;
	}

	.dateactive {
		background: #E1F3ED;
	}

	page {
		background: linear-gradient(180deg, #8883F0 10%, rgba(255, 255, 255, 0) 100%);
		border-radius: 0rpx 0rpx 0rpx 0rpx;
	}

	.page {
		width: 750rpx;
		padding-left: 34rpx;
		padding-right: 34rpx;
		box-sizing: border-box;
		height: 100%;

		.tip_box {
			position: fixed;
			left: 72rpx;
			top: 700rpx;
			width: 610rpx;
			background: #F7FAFE;
			border-radius: 30rpx 30rpx 30rpx 30rpx;
			z-index: 10000000;

			.top {
				padding: 52rpx 38rpx 42rpx 36rpx;

				.txt {
					width: 100%;
					text-align: center;
					font-weight: 500;
					font-size: 32rpx;
					color: #3D3D3D;
				}
			}

			.bot {
				border-top: 2rpx solid #D8D8D8;
				display: flex;
				flex-wrap: nowrap;
				height: 100%;

				.bot_left {
					width: 50%;
					height: 98rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					font-weight: 500;
					font-size: 36rpx;
					color: #3D3D3D;
				}

				.bot_right {
					width: 50%;
					height: 98rpx;
					display: flex;
					align-items: center;
					justify-content: center;

					border-left: 2rpx solid #D8D8D8;
					font-weight: 500;
					font-size: 36rpx;
					color: #8883F0;

				}

			}
		}

		.userdaili {
			.gongneng {
				width: 680rpx;
				height: 304rpx;
				background: #FFFFFF;
				border-radius: 24rpx 24rpx 24rpx 24rpx;
				padding: 0 50rpx;
				box-sizing: border-box;

				.icons {
					display: inline-block;
					width: 145rpx;
					text-align: center;

					image {
						margin-top: 34rpx;
						width: 50px;
						height: 50px;
					}
				}

			}

			.ordertongji {
				width: 680rpx;
				height: 342rpx;
				background: #FFFFFF;
				border-radius: 24rpx 24rpx 24rpx 24rpx;

				.shuju {
					display: flex;
					justify-content: space-between;
					padding: 0 40rpx;
					box-sizing: border-box;
					margin-top: 24rpx;

					.ddje {
						text-align: center;

						.shu {
							font-weight: 500;
							font-size: 40rpx;
							color: #3D3D3D;
						}

						.sb {
							margin-top: 20rpx;
							font-weight: 500;
							font-size: 20rpx;
							color: #3D3D3D;
						}
					}
				}

				.date {
					padding-left: 80rpx;
					padding-right: 80rpx;
					box-sizing: border-box;
					display: flex;
					justify-content: space-between;
					margin-top: 26rpx;

					text {
						padding: 6rpx 18rpx;
						box-sizing: border-box;
						background: #eee;
						border-radius: 10rpx 10rpx 10rpx 10rpx;
						font-size: 26rpx;
						color: #808080;
					}
				}

				.orderday {
					display: flex;
					justify-content: space-between;
					width: 100%;
					padding: 10rpx 12rpx;
					box-sizing: border-box;

					text {
						margin-right: 10rpx;
						border-radius: 20rpx;
						text-align: center;
						display: inline-block;
						width: 148rpx;
						height: 84rpx;
						text-align: center;
						line-height: 84rpx;
					}
				}
			}

			.dttitle {
				margin: 36rpx 0;
				font-weight: 500;
				font-size: 36rpx;
				color: #3D3D3D;
			}

			.zhanghu {
				margin-top: 32rpx;
				width: 680rpx;
				height: 264rpx;
				background: #FFFFFF;
				border-radius: 24rpx 24rpx 24rpx 24rpx;
				padding: 36rpx 38rpx;
				box-sizing: border-box;

				.zhtitle {
					display: flex;
					justify-content: space-between;

					.sj {
						display: flex;
						justify-content: space-between;

						text {
							font-size: 26rpx;
							color: #3D3D3D;
						}
					}

					.tx {
						font-size: 26rpx;
						color: #27D089;
					}
				}

				.zhje {
					margin-top: 20rpx;
					display: flex;
					justify-content: space-between;
					border-bottom: 1px solid #ccc;
					padding-bottom: 20rpx;

					text {
						font-weight: 500;
						font-size: 48rpx;
						color: #3D3D3D;
					}

					.btntx {
						width: 156rpx;
						height: 42rpx;
						background: linear-gradient(270deg, #54DAA1 0%, #19CD82 100%);
						border-radius: 40rpx 40rpx 40rpx 40rpx;
						font-size: 26rpx;
						color: #FFFFFF;
						text-align: center;
						line-height: 42rpx;
						margin-top: 10rpx;
					}
				}

				.buc {
					margin-top: 20rpx;
					font-size: 26rpx;
					color: #979797;
				}
			}
		}




		//样式结束
		.title {
			font-weight: 500;
			font-size: 36rpx;
			color: #3D3D3D;
			line-height: 50rpx;
			text-align: left;
			font-style: normal;
			text-transform: none;
		}

		.guangg {
			margin-top: 10rpx;
			margin-bottom: 10rpx;

			image {
				border-radius: 30rpx;
				width: 680rpx;
				height: 218rpx;
			}
		}

		.saoma {
			width: 750rpx;
			height: 166rpx;
			background: #FFFFFF;
			position: relative;
			left: -34rpx;
			padding-top: 22rpx;
			border-radius: 54rpx 54rpx 0 0;
			margin-top: 20rpx;

			view {
				text-align: center;
				width: 676rpx;
				height: 102rpx;
				background: linear-gradient(270deg, #8883F0 0%, #8883F0 100%);
				border-radius: 54rpx 54rpx 54rpx 54rpx;
				font-weight: 500;
				font-size: 40rpx;
				color: #FFFFFF;
				margin: auto;
				line-height: 102rpx;
			}

			image {
				width: 56rpx;
				height: 56rpx;
				vertical-align: middle;
				margin-right: 10rpx;
				margin-bottom: 10rpx;
			}
		}

		.ditu {
			width: 100%;
			height: 980rpx;
			background: #FFFFFF;
			border-radius: 38rpx 38rpx 38rpx 38rpx;
			padding-top: 16rpx;
			position: relative;

			.fujin {
				position: absolute;
				top: 730rpx;
				padding-left: 30rpx;
				width: 100%;

				image {
					width: 210rpx;
					height: 74rpx;
				}
			}

			.dtxs {
				width: 642rpx;
				height: 812rpx;
				margin: auto;
				border-radius: 30rpx;
				overflow: hidden;
			}

			.tubiao {
				display: flex;
				justify-content: space-between;
				padding: 30rpx 50rpx;
				box-sizing: border-box;

				.gr {
					text-align: center;
					width: 100%;
					font-weight: 400;
					font-size: 26rpx;
					color: #3D3D3D;

					image {
						display: block;
						margin: auto;
						margin-bottom: 14rpx;
					}
				}
			}
		}
	}
</style>