<template>
	<view class="page">
		<u-navbar title="协议" :border-bottom="false" :background="bgc" back-icon-color="#fff" title-color='#fff'
			title-size='36' height='50'></u-navbar>
		<view v-if="btnmsk"
			style="width: 100%;height: 100vh;position: fixed;top: 0;left: 0;background-color: #000;opacity: .1;z-index: 999;">
		</view>
		<!-- 新用户弹窗提示 -->
		<view class="xints" >
			<scroll-view scroll-y="true" @scrolltolower="onScrollToLower" class="scrolls">
				<view v-html="contwz"></view>
			</scroll-view>
			<view hover-class="app-tap-hover" class="yiyuess" @click="btnfh" style="background-color: transparent;border: 1px solid #ccc;">
				暂不使用
			</view>
			<view hover-class="app-tap-hover" class="yiyues" v-if="countdown == 0" @click="btnzx">
				同意并使用
			</view>
			<view class="yiyue" v-else>
				同意并使用 {{countdown}}秒
			</view>
		</view>
		<view class="" v-if="xintsflag"
			style="width: 100%;height: 100vh;position: fixed;top: 0;left: 0;background-color: #000;opacity: .5;z-index: 1;">
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				xintsflag: false,
				btnmsk: false,
				qrResult: '',
				bluetoothflag: false,
				shibaiflag: false,
				bgc: {
					backgroundColor: "#4C97E7",
				},
				showloading: false,
				showfz: false,
				show: false,
				showshop: false,
				id: '',
				xgname: '',
				deviceInfo: {},
				groupList: {},
				showpopup: false,
				remake: '',
				price: '',
				showpeice: false,
				showremake: false,
				showmc: false,
				pagenum: 1,
				wateringList: [],
				pagesize: 10,
				isLoading: false,
				noMoreData: false,
				total: 0,
				storeId: '',
				devicesList: [],
				setMode: null,
				mac: '',
				name: '',
				deviceId: '',
				isMch: false,
				taocan: '',
				token: '',
				userImgs: '',
				url: '',
				tclist: [],
				list: [],
				isActive: [],
				countdown: 10, // 初始倒计时时间  
				intervalId: null,
				contwz: '',
				sn: '',
				arrlists: []
			}
		},
		onLoad(option) {
			// let id = option.id
			// this.id = id
			// this.sn = option.sn
		},
		onShow() {
			this.wateringList = []
			this.setMode == null
			this.taocan = ''
			// this.getlistobj(this.id)
			// this.getao()
			// this.getlist()
			this.getxieyi()
		},
		onUnload: function() {
			if (this.intervalId) {
				clearInterval(this.intervalId);
			}
			// xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent);
			wx.closeBLEConnection({
				deviceId: this.deviceId,
			})
		},
		methods: {
			formatTimeLimit(item) {
				if (item.timeLimit === false) {
					return '';
				}
				if (item.timeLimit === true && item.timeStart && item.timeEnd) {
					const result = `${item.timeStart}-${item.timeEnd}`;
					return result
				}
				return ''
			},
			// 格式化星期显示
			formatWeekDisplay(item) {
				if (item.weekLimit === false || !item.weeks || item.weeks.length === 0) {
					return '不限时间使用';
				}
				const weekNames = {
					1: '周一',
					2: '周二', 
					3: '周三',
					4: '周四',
					5: '周五',
					6: '周六',
					7: '周日'
				};
				
				const weekTexts = item.weeks.map(week => weekNames[week]).filter(text => text);
				const result = weekTexts.join(' ');
				// console.log('星期显示结果:', result);
				return '指定时间使用：' + result;
			},
			// 滚动到底部
			onScrollToLower() {
				
			},
			startCountdown() {
				if (this.intervalId) {

				} else {
					this.intervalId = setInterval(() => {
						if (this.countdown > 0) {
							this.countdown--;
						} else {
							clearInterval(this.intervalId); // 清除定时器  
						}
					}, 1000); // 每秒执行一次  
				}
			},
			getxieyi() {
				this.$u.get(`/app/article/first?appId=${this.$store.state.appid}&code=MCH_SERVICE`).then(res => {
					if (res.code == 200) {
						if(res.data){
							this.startCountdown()
							this.contwz = res.data.content
						}else{
							uni.setStorageSync('wzid',11)
							uni.navigateBack()
						}
					}
				})
			},
			btnfh(){
				uni.navigateBack()
			},
			getuser() {
				this.$u.get("/app/user/userInfo").then((res) => {
					if (res.code == 200) {
						if (res.data.readMchLicence == false) {
							this.xintsflag = true
						} else {
							this.xintsflag = false
						}
					}
				})
			},
			btnzx() {
				uni.setStorageSync('wzid',11)
				uni.navigateBack()
				// this.$u.put(`/app/user/readMchLicence`).then((res) => {
				// 	if (res.code == 200) {
						
				// 	}
				// })
			},
			toindex(suitId) {
				const index = this.isActive.indexOf(suitId);
				if (index !== -1) {
					// 如果存在，则删除它  
					this.isActive.splice(index, 1);
					console.log('删除', this.isActive);
				} else {
					// 如果不存在，则添加到数组末尾  
					this.isActive.push(suitId);
					console.log('添加', this.isActive);
				}
			},

			getlist() {
				let data = {
					pageNum: 1,
					pageSize: 99
				}
				this.$u.get(`/app/suit/tempList`, data).then((res) => {
					if (res.code == 200) {
						this.list = res.rows
					}
				})
			},
			getao() {
				this.$u.get(`/app/suit/listByDeviceId/${this.id}`).then(res => {
					if (res.code == 200) {
						this.tclist = res.data
						if (res.data.length <= 1) {
							res.data.forEach(item => {
								this.taocan += item.name
							})
						} else {
							res.data.forEach(item => {
								this.taocan += item.name + ','
							})
						}
					}
				})
			},
			btntc() {
				uni.navigateTo({
					url: '/page_fenbao/statulist/taocanlist/addtaocan/index?id=' + this.id + '&modevalue=' + 4
				})
			},
			btnlyqx() {
				this.shibaiflag = false
				this.bluetoothflag = false
			},
			getlistobj(id) {
				this.$u.get(`/app/device/${id}?withSuit=true`).then((res) => {
					if (res.code == 200) {
						this.listobj = res.data
						this.arrlists.push(res.data)
						uni.setStorageSync('tcidlist', this.arrlists)
						if (res.data.suitList) {
							res.data.suitList.forEach(item => {
								this.isActive.push(item.suitId)
							})
						}
					}
				})
			},
			// 点击进行下一步  
			btnxia() {
				if (this.isActive.length == 0) {
					uni.showToast({
						title: '还未绑定套餐，请先绑定或新建套餐',
						icon: 'none',
						duration: 3000,
					})
				} else {
					this.$u.get("/app/user/userInfo").then((res) => {
						if (res.code == 200) {
							if (res.data.readMchLicence == false) {
								this.xintsflag = true
							} else {
								this.xintsflag = false
								this.$u.delete(`/app/suit/delByDevice/${this.deviceId}`).then(res => {})
								let numArr = this.isActive.map(item => parseInt(item, 10))
								let data = {
									deviceId: this.id,
									suitIds: numArr
								}
								this.$u.put(`/app/device`, data).then((res) => {
									if (res.code == 200) {
										uni.showToast({
											title: res.msg,
											icon: 'success',
											duration: 1000,
										})
										this.getao()
										let data = {
											deviceNo: this.sn
										}
										setTimeout(() => {
											this.btnmsk = false
											uni.reLaunch({
												url: '/pages/index/index'
											})
										}, 1000)
									} else {
										uni.showToast({
											title: res.msg,
											icon: 'none',
											duration: 1000,
										})
										this.btnmsk = false
									}
								})
							}
						}
					})
				}
			},
			// 点击wifi进行配网
			btnwifi() {
				this.shibaiflag = false
				this.bluetoothflag = true
				if (this.setMode == null) {
					xBlufi.initXBlufi(1)
					xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvent);
					xBlufi.notifyStartDiscoverBle({
						'isStart': true
					})

					// 停止蓝牙搜索  
					setTimeout(() => {
						xBlufi.notifyStartDiscoverBle({
							'isStart': false
						})
						xBlufi.notifyConnectBle({
							isStart: true,
							deviceId: this.deviceId,
							name: this.name
						})
						xBlufi.notifyInitBleEsp32({
							deviceId: this.deviceId
						})
						let name = ''
						let index = this.name.indexOf('-');
						if (index !== -1) {
							name = this.name.slice(index + 1);
						}
						let data = {
							storeId: this.storeId,
							mac: this.mac
						}
						this.$u.put('/app/device/bind', data).then((res) => {
							if (res.code == 200) {
								uni.hideLoading();
								this.shibaiflag = false
								this.bluetoothflag = false
								uni.removeStorageSync('mac');
								let systemInfo = uni.getSystemInfoSync();
								if (systemInfo.platform == 'android') {
									// 当前设备是 Android  
									uni.navigateTo({
										url: '/page_components/wifilist/index?deviceId=' + this.deviceId + '&name=' + this.name
									})
								} else if (systemInfo.platform == 'ios') {
									// 当前设备是 iOS  
									uni.navigateTo({
										url: '/page_fenbao/device/wifivideo?deviceId=' + this.deviceId + '&name=' + this.name
									})
								}
							} else if (res.msg == '设备编号和mac不能同时为空') {
								this.shibaiflag = true
								this.bluetoothflag = false
							}
						})
					}, 1000)
				} else {
					let name = ''
					let index = this.name.indexOf('-');
					if (index !== -1) {
						name = this.name.slice(index + 1);
					}
					let data = {
						storeId: this.storeId,
						mac: this.mac
					}
					this.$u.put('/app/device/bind', data).then((res) => {
						if (res.code == 200) {
							this.shibaiflag = false
							this.bluetoothflag = false
							uni.hideLoading();
							uni.removeStorageSync('mac');
							let systemInfo = uni.getSystemInfoSync();
							if (systemInfo.platform == 'android') {
								// 当前设备是 Android  
								uni.navigateTo({
									url: '/page_components/wifilist/index?deviceId=' + this.deviceId + '&name=' + this.name
								})
							} else if (systemInfo.platform == 'ios') {
								// 当前设备是 iOS  
								uni.navigateTo({
									url: '/page_fenbao/device/wifivideo?deviceId=' + this.deviceId + '&name=' + this.name
								})
							}
						} else {
							if (res.msg == '设备编号和mac不能同时为空') {
								this.shibaiflag = true
								this.bluetoothflag = false
								uni.hideLoading()
							} else {
								this.shibaiflag = true
								this.bluetoothflag = false
								uni.hideLoading()
								uni.showToast({
									title: res.msg,
									icon: 'none',
									duration: 2000
								})
							}
						}
					})
				}
			},
			funListenDeviceMsgEvent: function(options) {
				switch (options.type) {
					case xBlufi.XBLUFI_TYPE.TYPE_RECIEVE_MY_DATA:
						let loadPercent = options.data;
						let loadText = '文件读取中'
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_RECIEVE_CUSTON_DATA:
						let ver_data = this.parseCustomData(options.data)
						this.setMode = Math.floor(ver_data.setMode / 60)
						console.log("1收到设备发来的自定义数据结果：", ver_data, this.setMode)
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS:
						if (options.result) {
							let devicesarr = options.data
							devicesarr.forEach(device => {
								if (device.name) {
									if (device.localName.slice(-12) == this.qrResult) {
										this.deviceId = device.deviceId
										this.name = device.name
										this.mac = device.localName.slice(-12)
									}
								}
							})
						}
						break;

					case xBlufi.XBLUFI_TYPE.TYPE_CONNECTED:
						if (options.result) {
							this.bluetoothflag = false
							uni.hideLoading(); {
								console.log("连接回调options.data.deviceId：" + options.data.deviceId,
									"连接回调options.data.name：" + options.data.name);
							}
						} else {
							this.shibaiflag = true
							this.bluetoothflag = false
							uni.hideLoading()
						}

						break;

					case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_START:
						if (!options.result) {
							setTimeout(() => {
								uni.hideLoading()
								this.bluetoothflag = false
							}, 3000)
							console.log("蓝牙未开启", options);
							return
						} else {

						}

						break;

					case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_STOP:
						if (options.result) {
							let uniqueDevicesList = Array.from(new Set(this.devicesList));

							// 将去重后的数组重新赋值给 this.devicesList
							this.devicesList = uniqueDevicesList;
							let list = []
							filteredDevices.forEach(device => {
								// 从设备名称中提取 MAC 地址（假设 MAC 地址是设备名称的后6个字符）
								let macFromName = device.name.substring(device.name.length - 12);
								this.$u.get(`/app/device/${macFromName}/isBind`).then((res) => {
									if (res.data == false) {
										list.push(device)
									} else {

									}
								})

							});
							setTimeout(() => {
								this.devicesList = list
							}, 200)

							console.log('蓝牙停止搜索ok');
						} else {
							//蓝牙停止搜索失败
							console.log('蓝牙停止搜索失败');
						}
						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">
	page {
		background-color: #F7FAFE;
	}
    .card-header {
    	display: flex;
    	align-items: center;
    	margin-bottom: 12rpx;
    }
	.card-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #222;
		flex: 1;
	}
	.card-price {
		color: #ff4848;
		font-size: 36rpx;
		font-weight: bold;
		margin-left: 12rpx;
	}
	.card-desc {
		color: #888;
		font-size: 24rpx;
		margin-bottom: 10rpx;
		line-height: 1.6;
	}
	.card-footer {
		color: #bbb;
		font-size: 22rpx;
		display: flex;
		align-items: center;
	}
	.page {
		width: 750rpx;

		.card {
			margin: 60rpx auto 0;
			width: 654rpx;
			border-radius: 30rpx;

			.toptit {
				font-weight: 700;
				font-size: 44rpx;
				color: #3D3D3D;
				box-sizing: border-box;
			}

			.shebeiname {
				width: 654rpx;
				border-radius: 24rpx 24rpx 24rpx 24rpx;
				margin: auto;
				margin-top: 26rpx;
				box-sizing: border-box;

				.shebeitit {
					font-size: 28rpx;
					color: #606060;
					margin-top: 18rpx;
				}
			}

			.buttit {
				width: 100%;
				height: 1050rpx;
				overflow: scroll;
				background-color: #fff;
				margin-top: 30rpx;
				padding: 28rpx 20rpx;
				box-sizing: border-box;
				border-radius: 20rpx;
			}
		}
	}

	.xztclist {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
		font-size: 36rpx;

		text {
			margin-top: 0 !important;
		}

		image {
			width: 37rpx;
			height: 37rpx;
			padding-left: 10rpx;
			margin-right: 10rpx;
		}
	}

	.taocanlist {
		.tc_list {
			padding: 30rpx;
			box-sizing: border-box;
			background-color: #fff;
			color: #000;
			box-shadow: 0rpx 16rpx 40rpx 0rpx rgba(42, 130, 228, 0.1);
			border-radius: 20rpx;
			margin-top: 20rpx;
			transition: all 0.3s ease;
			
			&.active {
				
				// background-color: #4C97E7;
				// color: #fff;
				
				// .tc_remark {
				// 	color: rgba(255, 255, 255, 0.8);
				// }
				
				// .deposit {
				// 	color: #FFE5E5 !important;
				// }
				
				// .price_info {
				// 	color: #E8F5E8 !important;
				// }
			}
			
			.tc_title {
				font-weight: 600;
				font-size: 29rpx;
				margin-bottom: 15rpx;
				color: inherit;
			}
			
			.tc_content {
				margin-bottom: 15rpx;
				
				.tc_fee_info {
					display: flex;
					flex-wrap: wrap;
					align-items: center;
					gap: 10rpx;
					font-size: 26rpx;
					color: inherit;
					line-height: 1.5;
					
					text {
						display: inline-block;
					}
					
					.fee_mode {
						margin-left: 5rpx;
					}
					
					.deposit {
						margin-left: 10rpx;
						color: #FF6B6B;
					}
					
					.price_info {
						margin-left: 10rpx;
						color: #4C97E7;
					}
				}
			}
			
			.tc_remark {
				font-size: 24rpx;
				color: #333;
				line-height: 1.4;
			}
		}
	}

	.empty_state {
		text-align: center;
		padding: 140rpx 0;

		image {
			width: 276rpx;
			height: 134rpx;
			margin-bottom: 20rpx;
		}

		.empty_text {
			color: #ccc;
			font-size: 28rpx;
		}
	}

	.btnanniu {
		width: 86%;
		align-items: center;
		display: flex;
		justify-content: space-between;
		position: fixed;
		left: 50%;
		transform: translateX(-50%);
		bottom: 50rpx;

		.btn_new {
			width: 36%;
			height: 100rpx;
			line-height: 100rpx;
			border-radius: 10rpx;
			box-sizing: border-box;
			color: #4C97E7;
			border: 1px solid #4C97E7;
			text-align: center;
			font-size: 36rpx;
			background-color: #fff;
		}

		.btnxyb {
			width: 60%;
			height: 100rpx;
			background: #4C97E7;
			box-shadow: 0rpx 16rpx 40rpx 0rpx rgba(42, 130, 228, 0.1);
			filter: blur(0px);
			text-align: center;
			line-height: 100rpx;
			font-size: 36rpx;
			color: #FFFFFF;
			border-radius: 10rpx;
		}
	}

	.xints {
		width: 750rpx;
		overflow: scroll;
		background: #FFFFFF;

		.wxts {
			position: fixed;
			top: 34rpx;
			left: 50%;
			transform: translateX(-50%);
			font-size: 32rpx;
			color: #3D3D3D;
			z-index: 4;
		}

		.huany {
			width: 100%;
			text-align: center;
			font-weight: 600;
			font-size: 32rpx;
			color: #333;
			margin-top: 30rpx;
		}

		.yiyue {
			position: fixed;
			bottom: 46rpx;
			left: 67%;
			transform: translateX(-50%);
			font-size: 24rpx;
			color: #808080;
			z-index: 4;
			width: 430rpx;
			height: 76rpx;
			background: #4C97E7;
			border-radius: 47rpx 47rpx 47rpx 47rpx;
			font-size: 32rpx;
			color: #FFFFFF;
			text-align: center;
			line-height: 76rpx;
		}
.yiyuess {
			position: fixed;
			bottom: 46rpx;
			left: 20%;
			transform: translateX(-50%);
			font-size: 24rpx;
			color: #808080;
			z-index: 4;
			width: 200rpx;
			height: 76rpx;
			background: #4C97E7;
			border-radius: 47rpx 47rpx 47rpx 47rpx;
			font-size: 32rpx;
			color: #333;
			text-align: center;
			line-height: 76rpx;
		}
		.yiyues {
			position: fixed;
			bottom: 46rpx;
			left: 67%;
			transform: translateX(-50%);
			font-size: 24rpx;
			color: #808080;
			z-index: 4;
			width: 430rpx;
			height: 76rpx;
			background: #4C97E7;
			border-radius: 47rpx 47rpx 47rpx 47rpx;
			font-size: 32rpx;
			color: #FFFFFF;
			text-align: center;
			line-height: 76rpx;
		}

		.scrolls {
			width: 100%;
			height: 78vh;
			padding: 0 36rpx;
			box-sizing: border-box;
			font-size: 24rpx;
			color: #3D3D3D;
			margin-top: 20rpx;
		}

		image {
			width: 584rpx;
			height: 798rpx;
			position: fixed;
			top: 0;
			left: 50%;
			transform: translateX(-50%);
			z-index: 2;
		}
	}

	::v-deep .u-flex {
		padding-top: 20rpx !important;
		box-sizing: border-box;
	}

	::v-deep .panel {
		position: fixed;
		width: 100%;
		height: 100%;
		top: 0;
		bottom: 0;
		left: 0;
		z-index: 99 !important;
		overflow: hidden;
	}

	::v-deep .u-title {
		padding-bottom: 22rpx;
	}

	::v-deep .u-icon__icon {
		padding-bottom: 22rpx;
	}
</style>