<template>
	<view class="page">
	<!-- 	<u-navbar  :border-bottom="false" :background="bgc" title-color='#fff' back-icon-color="#fff"
			title-size='36' height='50'></u-navbar> -->
		<view class="title">
		    {{deviceobj.deviceName}}
		</view>
		<view class="box">
			<view class="tit">
				选择服务
			</view>
			<view style="display: flex;justify-content: space-between;flex-wrap: wrap;">
				<view :class="indexactive == item.suitId ? 'active':''"
					style="width: 304rpx;height: 122rpx;background: #fff;box-shadow: 0rpx 16rpx 40rpx 0rpx rgba(42,130,228,0.1);border-radius: 30rpx;display: flex;justify-content: space-between;padding: 20rpx 34rpx;box-sizing: border-box;margin-top: 20rpx;"
					v-for="(item,index) in deviceobj.suitList" :key="index" @click="btnactive(item)">
					<view class="lt">
						<view class="tc">
							{{item.name}}
						</view>
						<view class="date">
							{{item.value}}分钟
						</view>
					</view>
					<view class="rt">
						￥{{item.price}}
					</view>
				</view>
			</view>

			<view class="shuom" v-for="(item,index) in deviceobj.suitList" :key="index"
				v-if="indexactive == item.suitId">
				<view class="tits" style="margin-top: 10rpx;">
					套餐说明
				</view>
				<view class="wz">
					该设备还剩余时长：{{expireTimeStr + 1}}分钟
				</view>
				<view class="">
					{{item.description == null ? '无' : item.description}}
				</view>
				<view class="wz">
					联系客服：2562356565
				</view>
			</view>

			<view class="tongyi">
				<u-checkbox-group>
					<u-checkbox v-model="checked" @change="checkboxChange" active-color="#8883F0 ">我已同意
					</u-checkbox><text>《用户服务协议》</text>
				</u-checkbox-group>
				<view class="zf" @click="btnzhifu">
					立即支付
				</view>
			</view>


		</view>
	</view>
</template>

<script>
	var xBlufi = require("@/page_components/blufi/xBlufi.js");
	export default {
		data() {
			return {
				indexactive: 0,
				checked: false,
				deviceobj: {},
				timer: null,
				expireTimeStr: '',
				zfobj: {},
				orderno: '',
				id: '',
				czflag: false,
				sytime: 0,
				datetime: 0,
				mac: '',
				deviceId: '',
				name: '',
				ver_data: '',
				devicesList: [],
				onlineStatus: ''
			}
		},
		onLoad(option) {
			console.log(option.q)
			if (option.q) {
				function getQueryParam(url, paramName) {
					let regex = new RegExp(`[?&]${paramName}=([^&]*)`);
					let results = regex.exec(url);
					return results ? decodeURIComponent(results[1].replace(/\+/g, ' ')) : null;
				}
				let sceneValue = option.q
				let decodedValue = decodeURIComponent(sceneValue);
				this.id = getQueryParam(decodedValue, 's')
				console.log(this.id)
				this.startTimer()
				this.gettaoc()
				this.getmac()
	            this.gettrue()
			} else {
				this.id = option.id
				this.startTimer()
				this.gettaoc()
				this.getmac()
	            this.gettrue()
			}
			// 一开始搜索设备
			xBlufi.initXBlufi(1)
			xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvent);
			xBlufi.notifyStartDiscoverBle({
				'isStart': true
			})
			setTimeout(() => {
				xBlufi.notifyStartDiscoverBle({
					'isStart': false
				})
				if (this.devicesList.length > 0) {
					xBlufi.notifyConnectBle({
						isStart: true,
						deviceId: this.deviceId,
						name: this.name
					})
				}
			}, 2000)
		},
		computed: {

		},
		onShow() {
			if (this.orderno) {
				this.gethuidaio()
			}
			this.getuserinfo()
		},
		onUnload: function() {
			if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			}
			xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent);
			xBlufi.notifyStartDiscoverBle({
				'isStart': false
			})
		},
		onHide() {
			xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent);
			xBlufi.notifyStartDiscoverBle({
				'isStart': false
			});
		},
		onBeforeUnmount() {
			xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent);
			xBlufi.notifyStartDiscoverBle({
				'isStart': false
			});
		},
		methods: {
			gettrue(){
				this.$u.get("/app/device/isBind?deviceNo=" + this.id).then((res) => {
					if (res.data == false) {
                        uni.navigateTo({
                        	url:'/pages/shouye/index?flag=' + true + '&id=' + this.id
                        })
					} 
				})
			},
			getuserinfo() {
				this.$u.get("/app/user/userInfo").then((res) => {
					if (res.code == 200) {
						
					} else {
						uni.navigateTo({
							url:'/pages/login/login?id=' + 1
						})
					}
				})
			},
			startTimer() {
				this.timer = setInterval(() => {
					this.gettaoc();
				}, 30000);
			},
			getmac() {
				this.$u.get(`/app/device/${this.id}/bySn`).then((res) => {
					if (res.code == 200) {
						this.mac = 'CTKG-' + res.data.mac
						this.onlineStatus = res.data.onlineStatus
					}
				})
			},
			gettaoc() {
				this.$u.get(`/app/device/${this.id}/withSuitList`).then((res) => {
					if (res.code == 200) {
						this.deviceobj = res.data;
						this.indexactive = res.data.suitList[0].suitId;
						this.zfobj = res.data.suitList[0]
						let targetDateStr = this.deviceobj.expireTime
						let targetParts = targetDateStr.split(/[- :]/);
						let targetDate = new Date(targetParts[0], targetParts[1] - 1, targetParts[2], targetParts[
							3], targetParts[4], targetParts[5]);
						let now = new Date();
						let differenceInMs = targetDate - now;
						let differenceInMinutes = Math.floor(differenceInMs / (1000 * 60));
						this.expireTimeStr = parseInt(differenceInMinutes) <= 0 ? '0' : differenceInMinutes
					}
				})
			},
			btnzhifu() {
				if (this.checked == false) {
					uni.showToast({
						title: '请勾选用户服务协议 !',
						icon: 'none',
						duration: 1000
					})
				} else if (this.onlineStatus == 1) {
					let that = this
					let data = {
						deviceNo: that.id,
						suitId: that.zfobj.suitId,
						money: that.zfobj.price,
						suitTime: that.zfobj.value
					}
					that.$u.post('/app/bill/recharge', data).then((res) => {
						if (res.code == 200) {
							that.orderno = res.data
							that.$u.get(`/app/pay/wx/${that.orderno}`).then((res) => {
								if (res.code == 200) {
									uni.requestPayment({
										provider: 'wxpay',
										timeStamp: res.data.timeStamp,
										nonceStr: res.data.nonceStr,
										package: res.data.packageVal,
										signType: res.data.signType,
										paySign: res.data.paySign,
										success: (res) => {
											console.log(res, '支付成功');
											if (that.timer) {
												clearInterval(this
													.timer);
												that.timer = null;
											}
											// 支付成功逻辑
											uni.reLaunch({
												url: '/pages/shouye/index'
											})
											uni.setStorageSync('time',that.expireTimeStr)
										},
										fail(err) {
											// 支付失败逻辑
											uni.showToast({
												title: '支付失败',
												icon: 'none',
												duration: 2000
											});
										}
									});
								}
							})
						} else if (res.code == 401) {
							uni.reLaunch({
								url: '/pages/login/login'
							})
						}
					})
				} else {
					if (this.ver_data == '') {
						let that = this
						uni.showModal({
							title: '提示',
							content: '支付的时候请靠近设备并打开蓝牙',
							success: function(res) {
								if (res.confirm) {
									xBlufi.initXBlufi(1);
									xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvent);
									xBlufi.notifyStartDiscoverBle({
										'isStart': true
									})
									setTimeout(() => {
										xBlufi.notifyStartDiscoverBle({
											'isStart': false
										})
										if (this.devicesList.length > 0) {
											xBlufi.notifyConnectBle({
												isStart: true,
												deviceId: this.deviceId,
												name: this.name
											})
										}
									}, 2000)
								} else if (res.cancel) {
									console.log('用户点击了取消');
								}
							}
						})
					}else{
						let that = this
						let data = {
							deviceNo: that.id,
							suitId: that.zfobj.suitId,
							money: that.zfobj.price,
							suitTime: that.zfobj.value
						}
						that.$u.post('/app/bill/recharge', data).then((res) => {
							if (res.code == 200) {
								that.orderno = res.data
								that.$u.get(`/app/pay/wx/${that.orderno}`).then((res) => {
									if (res.code == 200) {
										uni.requestPayment({
											provider: 'wxpay',
											timeStamp: res.data.timeStamp,
											nonceStr: res.data.nonceStr,
											package: res.data.packageVal,
											signType: res.data.signType,
											paySign: res.data.paySign,
											success: (res) => {
												console.log(res, '支付成功');
												if (that.timer) {
													clearInterval(this
														.timer);
													that.timer = null;
												}
												// 支付成功逻辑
												uni.reLaunch({
													url: '/pages/shouye/index'
												})
												uni.setStorageSync('time',that.expireTimeStr)
											},
											fail(err) {
												// 支付失败逻辑
												uni.showToast({
													title: '支付失败',
													icon: 'none',
													duration: 2000
												});
											}
										});
									}
								})
							} else if (res.code == 401) {
								uni.reLaunch({
									url: '/pages/login/login'
								})
							}
						})
					}

				}
			},

			btnactive(item) {
				this.sytime = item.value
				this.zfobj = item
				this.indexactive = item.suitId;
			},
			checkboxChange(e) {
				this.checked = e.value
			},


			funListenDeviceMsgEvent: function(options) {
				switch (options.type) {
					case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS:
						if (options.result) {
							let devicesarr = options.data
							devicesarr.forEach(device => {
								const mac = device.name.substring(4);
								if (device.name == this.mac) {
									this.deviceId = device.deviceId
									this.name = device.name
									this.devicesList.push(device);
									let uniqueDevicesList = Array.from(new Set(this.devicesList));
									// 将去重后的数组重新赋值给 this.devicesList
									this.devicesList = uniqueDevicesList;
								}
							});
						}
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_CONNECTED:
						console.log("连接回调：" + JSON.stringify(options));
						if (options.result) {
							{
								xBlufi.notifyInitBleEsp32({
									deviceId: this.deviceId
								});
								xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvents);
								this.deviceIds = options.data.deviceId
								this.name = this.name
							}
						}

						break;
					case xBlufi.XBLUFI_TYPE.TYPE_RECIEVE_CUSTON_DATA:

						this.ver_data = this.parseCustomData(options.data)
						uni.hideLoading()
						console.log("1收到设备发来的自定义数据结果：", this.ver_data);
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_STOP:
						if (options.result) {
							let uniqueDevicesList = Array.from(new Set(this.devicesList));
							let filteredDevices = uniqueDevicesList.filter(device => device.name.substring(0, 4) ===
								"CTKG");
							// 将过滤后的数组重新赋值给 this.devicesList
							this.devicesList = filteredDevices;
							filteredDevices.forEach(device => {
								// 从设备名称中提取 MAC 地址（假设 MAC 地址是设备名称的后6个字符）
								let macFromName = device.name.substring(device.name.length - 12);
								console.log(macFromName);
								// 与 this.mac 进行比较
								if (macFromName == this.mac) {
									this.ishave = true;
								}
							})
						}
						this.searching = false
						break;
				}
			},

			parseCustomData(data) {
				// 将字符串按照 "@" 分割成数组
				const dataArray = data.split('@');
				// 根据约定，解析各个字段的值
				const voltage = parseFloat(dataArray[0].substring(1)); // 去除前缀 "V"，并将字符串转换为浮点数
				const switchState = dataArray[1].substring(1); // 去除前缀 "S"
				const current = parseFloat(dataArray[2].substring(1)); // 去除前缀 "A"，并将字符串转换为浮点数
				const power = parseFloat(dataArray[4].substring(1)); // 去除前缀 "P"，并将字符串转换为浮点数
				const remainingPower = parseFloat(dataArray[5].substring(1)); // 去除前缀 "M"，并将字符串转换为浮点数
				const setMode = dataArray[6].substring(1); // 去除前缀 "T"
				// 返回解析后的数据对象
				return {
					voltage,
					switchState,
					current,
					power,
					remainingPower,
					setMode
				};
			},

		}
	}
</script>

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

	/deep/ .u-checkbox__label {
		margin-right: 0 !important;
	}

	// /deep/ .u-icon__icon{
	// 	padding-bottom: 41rpx;
	// }
	page {
		// background: linear-gradient(180deg, #fff 0%, rgba(255, 255, 255, 0) 100%);
	}

	.active {
		background-color: #8883F0 !important;
		color: #fff !important;
	}

	.page {
		width: 750rpx;
		position: fixed;
		top: 0;
		left: 0;

		.tip_box {
			position: fixed;
			left: 72rpx;
			top: 700rpx;
			width: 610rpx;
			// height: 282rpx;
			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;

				}

			}
		}

		.title {
			margin-top: 40rpx;
			padding-left: 32rpx;
			font-weight: 600;
			font-size: 40rpx;
			color: #383838;
			margin-bottom: 30rpx;
			margin-top: 110rpx;
		}

		.box {
			width: 750rpx;
			height: 1440rpx;
			background: #F4F5F7;
			border-radius: 0rpx 0rpx 0rpx 0rpx;
			padding: 36rpx 54rpx;
			box-sizing: border-box;

			.tongyi {
				width: 590rpx;
				position: fixed;
				bottom: 50rpx;
				left: 50%;
				transform: translateX(-50%);

				text {
					color: #638DFF;
					height: 50rpx;
					line-height: 50rpx;
				}

				.zf {
					width: 590rpx;
					height: 84rpx;
					background: #8883F0;
					filter: blur(0px);
					border-radius: 50rpx;
					text-align: center;
					line-height: 84rpx;
					font-size: 36rpx;
					color: #FFFFFF;
					margin-top: 10rpx;
				}
			}

			.shuom {
				width: 648rpx;
				height: 286rpx;
				background: #FFFFFF;
				box-shadow: 0rpx 16rpx 40rpx 0rpx rgba(42, 130, 228, 0.1);
				filter: blur(0px);
				border-radius: 30rpx;
				margin: auto;
				margin-top: 36rpx;
				padding: 20rpx 36rpx;
				box-sizing: border-box;

				.tits {
					font-size: 32rpx;
					font-weight: 600;
					margin-top: 30rpx;
				}

				.wz {
					font-size: 28rpx;
					color: #383838;
					margin-top: 30rpx;
				}
			}

			.list_val {
				.tc {
					font-weight: 500;
					font-size: 34rpx;
					color: #525252;
				}

				.date {
					font-size: 26rpx;
					color: #525252;
					margin-top: 10rpx;
				}

				.rt {
					font-size: 40rpx;
					color: #525252;
					padding-top: 20rpx;
				}
			}

			.tit {
				font-size: 40rpx;
				color: #383838;
				font-weight: 600;
				margin-bottom: 32rpx;
			}
		}
	}
</style>