<template>
	<view class="pages">
		<u-navbar title="蓝牙充值" :border-bottom="false" :background="bgc" title-color='#fff' back-icon-color="#fff"
			title-size='38' height='50'></u-navbar>
		<view class="card" v-for="(item,index) in devicesList" :key="index">
			<view class="card_left">
				<image src="https://api.ccttiot.com/smartmeter/img/static/uoQO0pUZ1UHcW5uVKkuR" mode=""></image>
			</view>
			<view class="card_cent">
				<view class="info_top">
					创特开关
				</view>
				<view class="info_cont">

				</view>
				<view class="info_cont">
				</view>
				<view class="info_bot">
					MAC号：{{mac}}
				</view>
			</view>
			<view v-if="czflag" class="card_right" @click="czj()">
				充值
			</view>
		</view>
         <view v-if="baiflag" class="bai"></view>
		 <!-- <view class="masks" v-if="maskflag"> -->
		 	
		 <!-- </view> -->
		<!-- 加载状态 -->
		<view class="containers" v-show="statusflag">
			<uni-section>
				<uni-load-more :status="status" />
			</uni-section>
		</view>
		
		<!-- 未打开蓝牙 -->
		<view class="shibai" v-if="lanyaflag">
			<view class="top">
				充值失败
			</view>
			<view class="tishi">
				充值失败请查看手机蓝牙是否打开
			</view>
			<view class="li">
				<view class="wz">
					第一：检查手机蓝牙是否打开
				</view>
				<image style="width: 386rpx;height: 263rpx;" src="https://api.ccttiot.com/smartmeter/img/static/uM4DY4Ee9AgFHLv4bIDR" mode=""></image>
			</view>
			<view class="li">
				<view class="wz">
					第二：设置小程序蓝牙授权
				</view>
				<image style="width: 368rpx;height: 151rpx;" src="https://api.ccttiot.com/smartmeter/img/static/uAj06uo9qysixLrcFHBn" mode=""></image>
				<image style="width: 386rpx;height: 301rpx;" src="https://api.ccttiot.com/smartmeter/img/static/ugFSKFZn4mzJJHQx3K2Z" mode=""></image>
				<image style="width: 386rpx;height: 330rpx;" src="https://api.ccttiot.com/smartmeter/img/static/uZ4XoCI2KNQzcPKbwGLN" mode=""></image>
			</view>
			<view class="jxcz" @click="btnjxcz">
				继续充值
			</view>
		</view>
		
	</view>
</template>

<script>
	const app = getApp();
	var xBlufi = require("@/page_components/blufi/xBlufi.js");
	let _this = null;
	export default {
		data() {
			return {
				baiflag:false,
				titleflag: false, //提示隐藏
				bgc: {
					backgroundColor: "#F7FAFE",
				},
				devicesList: [
					// {name:'110000',
					// mac:'11111'}
				],
				searching: false,
				texts: '正在扫描蓝牙设备...',
				btnflag: true,
				tishiflag: false,
				option: '',
				bluthlist: [], //蓝牙数组
				status: 'loading',
				statusflag: false,
				Bluetoothmac: '',
				mac: '',
				ishave: false,
				ver_data: null,
				deviceInfo: {},
				gps: {},
				isband: false,
				status: false,
				deviceIds: '',
				name: '',
				orderinfo: {},
				dl: 0,
				czmoney: true,
				sn: '',
				jine: 0,
				deviceId: '',
				name: '',
				bgc: {
					background: '#8883F0'
				},
				billNo: '',
				maskflag:true,
				lanyaflag:false,
				czflag:false
			}
		},
		// 分享到好友（会话）
		  onShareAppMessage: function () {  
		    return {  
		      title: '创想物联',  
		      path: '/pages/shouye/index'  
		    }  
		  },  
		  
		  // 分享到朋友圈  
		  onShareTimeline: function () {  
		    return {  
		      title: '创想物联',  
		      query: '',  
		      path: '/pages/shouye/index'  
		    }  
		  },
		onLoad(e) {

			uni.showLoading({
				title: '加载中'
			})

			this.sn = JSON.parse(e.dingobj)
			if (this.sn.length >= 1) {
				this.jine = uni.getStorageSync('time')
				// this.mac = 'CTKG-' + this.sn[0].deviceMac
				this.mac = this.sn[0].deviceMac
				this.billNo = this.sn[0].billNo
				this.jine = this.jine + this.sn[0].suitTime
			} else {
				this.jine = uni.getStorageSync('time')
				this.billNo = this.sn.billNo
				// this.mac = 'CTKG-' + this.sn.deviceMac
				this.mac = this.sn.deviceMac
				this.jine = this.jine + this.sn.suitTime
			}


			xBlufi.initXBlufi(1);
			console.log("xBlufi", xBlufi.XMQTT_SYSTEM);
			xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvent);
			xBlufi.notifyStartDiscoverBle({
				'isStart': true
			});

			// 两秒后停止蓝牙搜索
			setTimeout(() => {
				xBlufi.notifyStartDiscoverBle({
					'isStart': false
				});

				if (this.devicesList.length == 0) {
					uni.showToast({
						title: '暂无发现对应设备,请靠近设备',
						icon: 'none',
						duration:2000
					})
					// uni.hideLoading()
				} else {
					xBlufi.notifyConnectBle({
						isStart: true,
						deviceId: this.deviceId,
						name: this.name
					})
                    // uni.hideLoading()
				}
				this.status = true
			}, 4000)

		},
		onShow: function() {
			// this.openBluetoothAdapter()
		},
		onUnload: function() {
			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
			});
		},
		watch: {

			ishave(newValue) {
				if (newValue === true) {
					// 当 ishave 的值变为 true 时执行相应的操作
					// 这里可以放置你想要执行的代码
					console.log('ishave 的值变为 true');
					this.devicesList.forEach(device => {
						// 从设备名称中提取 MAC 地址（假设 MAC 地址是设备名称的后6个字符）
						// let macFromName = device.name.substring(device.name.length - 12);
						// console.log(macFromName);
						// 与 this.mac 进行比较
						if (device.name.slice(5, 17) == this.mac) {
							// 如果相同，则将 this.ishave 设置为 true
							console.log(device);
							this.deviceInfo = device
							// this.ishave = true;
							this.createBLEConnection(device)

							console.log('对比正确');
						} else {
							console.log('对比失败');
						}
					});

				}
			},
			isband(newValue) {
				if (newValue === true) {
					console.log('isband 的值变为 true，开始监听 ver_data');
					this.$watch('ver_data', this.verDataWatcher);
				} else {
					console.log('isband 的值变为 false，取消监听 ver_data');
					this.$off('ver_data', this.verDataWatcher);
				}
			}
		},
		mounted() {
			this.videoContext = uni.createVideoContext('myVideo', this)
		},
		methods: {
			// 点击继续充值
			btnjxcz(){
				uni.showLoading({
					title: '加载中'
				})

				xBlufi.initXBlufi(1);
				console.log("xBlufi", xBlufi.XMQTT_SYSTEM);
				xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvent);
				xBlufi.notifyStartDiscoverBle({
					'isStart': true
				})
				// 两秒后停止蓝牙搜索
				setTimeout(() => {
					xBlufi.notifyStartDiscoverBle({
						'isStart': false
					});
				
					if (this.devicesList.length == 0) {
						uni.showToast({
							title: '暂无发现对应设备,请靠近设备',
							icon: 'none',
							duration:2000
						})
					} else {
						xBlufi.notifyConnectBle({
							isStart: true,
							deviceId: this.deviceId,
							name: this.name
						})
					}
					this.status = true
				}, 4000)
			},
			
			
			verDataWatcher(newValue, oldValue) {
				console.log('ver_data 变化了，新值：', newValue.remainingPower, '，旧值：', oldValue.remainingPower);
				if (newValue.remainingPower && oldValue.remainingPower) {
					let diff = newValue.remainingPower - oldValue.remainingPower;
					if (diff >= this.dl - 5 && diff <= this.dl + 5) {
						console.log('ver_data 变化符合条件');
						uni.setStorageSync('billNo', this.orderinfo.billNo);
						this.czmoney = false
						this.$u.get(`app/device/bind/${this.billNo}`).then((res) => {
							if (res.code == 200) {
								uni.removeStorageSync('billNo');

							} else {

							}
						})
						setTimeout(() => {
							uni.removeStorageSync('time')
							uni.reLaunch({
								url: '/pages/index/index'
							})
						}, 200)

						// 变化符合条件，执行相应的操作
					} else {
						// console.log('ver_data 变化不符合条件');
					}
				}
			},
			btnyc() {
				this.titleflag = false
			},
			czj() {
				this.baiflag = true
				this.czflag = false
				uni.showLoading({
					title: '充值中...'
				})
				let vm = this; // 将外部的 this 绑定到 vm 上
				uni.getNetworkType({
					success(res) {
						if (res.networkType !== 'none') {
							uni.getConnectedBluetoothDevices({
								success(res) {
									console.log('已连接的蓝牙设备信息：', res);
									xBlufi.notifySendCustomData({
										customData: "time@" + vm.jine * 60
									});
								},
								fail(err) {
									console.error('获取已连接蓝牙设备信息失败：', err);
								}
							})
							vm.$u.get(`/app/bill/recharge/${vm.billNo}/bluetoothSuccess`).then(res => {
								if(res.code == 200){
									setTimeout(()=>{
										uni.hideLoading()
										uni.navigateBack()
									},1000)
								}
							})
						} else {
							console.log('手机未连接网络');
							this.baiflag = false
						}
					}
				})
			},
			bind() {
				if (this.ishave && this.isband) {
					let that = this
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/index/index'
						})
					}, )
				}
			},
			// 解析自定义数据
			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(3); // 去除前缀 "SET"

				// 返回解析后的数据对象
				return {
					voltage,
					switchState,
					current,
					power,
					remainingPower,
					setMode
				};
			},

			funListenDeviceMsgEvent: function(options) {
				switch (options.type) {
					case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS:
						if (options.result) {
							let devicesarr = options.data
							// this.devicesList = options.data
							// console.log(devicesarr,this.mac);
							devicesarr.forEach(device => {
								const mac = device.name.substring(4);
								if (device.name.slice(5, 17) == this.mac) {
									this.deviceId = device.deviceId
									this.name = device.name
									this.devicesList.push(device);
									console.log(this.devicesList, 'devicesarrdevicesarr');
									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) {
							// uni.hideLoading();
							// uni.showToast({
							// 	title: '连接成功',
							// 	icon: 'none'
							// }); 
							{
								xBlufi.notifyInitBleEsp32({
									deviceId: this.deviceId
								});
								xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvents);

								this.deviceIds = options.data.deviceId
								this.name = this.name
								// 连接成功绑定设备
								// let params = {
								// 	mac: this.Bluetoothmac,
								// 	userId: this.$store.state.user.userId
								// }
								let systemInfo = uni.getSystemInfoSync();
								if (systemInfo.platform === 'android') {
									// 当前设备是 Android  

								} else if (systemInfo.platform === 'ios') {
									// 当前设备是 iOS  
									// uni.navigateTo({
									// 	url: '/pages/wifilist/index?deviceId=' + options
									// 		.data.deviceId + '&name=' + options.data.name
									// })
								}
							}
						}else{
							this.maskflag = false
							uni.hideLoading()
							// uni.showToast({
							// 	title: '未连接到设备，请靠近设备尝试',
							// 	icon: 'none'
							// }); 
						}

						break;
					case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_START:
						if (!options.result) {
                            this.lanyaflag = true
							uni.showToast({
								title: '蓝牙未开启',
								icon: 'none',
								duration: 3000
							});
							return
						}else{
							this.lanyaflag = false
						}
						break;
					
					case xBlufi.XBLUFI_TYPE.TYPE_RECIEVE_CUSTON_DATA:

						this.ver_data = this.parseCustomData(options.data)
						this.maskflag = false
						this.czflag = true
						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));

							// 过滤出名称字段的前五个字母为 "CTKG" 的项
							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
									// console.log(device);
									this.ishave = true;
								} else {
									// uni.showToast({
									// 	title: '未搜索到对应设备，请靠近设备重新扫描',
									// 	icon: 'none',
									// 	duration: 2000
									// });
								}
							});
							// console.log('蓝牙停止搜索ok',this.devicesList);
						} else {
							//蓝牙停止搜索失败
							// console.log('蓝牙停止搜索失败');
						}
						this.searching = false
						// _this.setData({
						// 	searching: false
						// });

						break;
				}
			},


			//4、建立连接
			createBLEConnection(e) {
				xBlufi.notifyStartDiscoverBle({
					'isStart': false
				});
				console.log(e, '蓝牙信息')
				const deviceId = e.deviceId
				this.Bluetoothmac = e.localName.substring(4) //从第七位开始截取 只取后面的mac号
				console.log(this.Bluetoothmac, '11111');
				let name = e.name;
				console.log('点击了，蓝牙准备连接的deviceId:' + e.deviceId);
				xBlufi.notifyConnectBle({
					isStart: true,
					deviceId: e.deviceId,
					name
				});
			},
			// 点击重新搜索
			Search() {
				this.bluthlist = []
				this.devicesList = []
				if (this.status) {
					xBlufi.notifyStartDiscoverBle({
						'isStart': true
					});
					// 重新搜索清空蓝牙数组
					// this.startBluetoothDevicesDiscovery()
					this.statusflag = true
					this.texts = '正在扫描蓝牙设备...'
					setTimeout(() => {
						this.statusflag = false
						if (this.searching) {
							xBlufi.notifyStartDiscoverBle({
								'isStart': false
							});
							// 判断是否存在设备
							if (this.devicesList.length == 0) {
								this.tishiflag = true
								this.texts = '扫描完毕，暂无发现设备'
							} else {
								this.texts = '扫描到以下设备，请点击连接！'
							}
						} else {
							xBlufi.notifyStartDiscoverBle({
								'isStart': true
							});
						}
					}, 2000)
				}
			},
			
			// 点击隐藏没有设备提示
			btnhd() {
				this.tishiflag = false
			}
		}

	}
</script>

<style lang="scss">
	.bai{
		width: 100%;
		height: 100vh;
		background-color: #000;
		opacity: .6;
		z-index: 99;
		position: fixed;
		top: 0;
		left: 0;
	}
	.shibai{
		margin-top: 50rpx;
		text-align: center;
		padding-bottom: 300rpx;
		.jxcz{
			width: 563rpx;
			height: 100rpx;
			background: #8883F0;
			border-radius: 60rpx 60rpx 60rpx 60rpx;
			text-align: center;
			line-height: 100rpx;
			font-size: 45rpx;
			color: #FFFFFF;
			position: fixed;
			bottom: 62rpx;
			left: 50%;
			transform: translateX(-50%);
		}
		.top{
			font-size: 40rpx;
			color: #3D3D3D;
		}
		.tishi{
			font-size: 31rpx;
			color: #3D3D3D;
			margin-top: 50rpx;
		}
		.li{
			margin-top: 50rpx;
			font-size: 31rpx;
			color: #3D3D3D;
			image{
				margin-top: 30rpx;
			}
		}
	}
	/deep/ .u-title {
		padding-bottom: 22rpx;
	}

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

	page {
		background-color: #F7FAFE !important;
	}
    
	.masks{
		width: 100%;
		height: 100vh;
		position: fixed;
		top: 0;
		left: 50%;
		transform: translateX(-50%);
		background-color: #ccc;
		opacity: .6;
	}   
	
	.card {
		margin-top: 50rpx;
		display: flex;
		flex-wrap: nowrap;
		align-items: center;
		// justify-content: space-between;
		width: 658rpx;
		// height: 282rpx;
		padding: 54rpx 48rpx;
		background: #fff;
		box-shadow: 0rpx 16rpx 40rpx 0rpx rgba(255, 255, 255, 0);
		border-radius: 24rpx 24rpx 24rpx 24rpx;

		.card_left {
			image {
				width: 63rpx;
				height: 169rpx;
			}
		}

		.card_cent {
			margin-left: 56rpx;
			width: 304rpx;
			display: flex;
			flex-wrap: wrap;

			.info_top {

				font-weight: 500;
				font-size: 42rpx;
				color: #8883F0;
			}

			.info_cont {
				display: flex;
				flex-wrap: nowrap;
				margin-top: 24rpx;

				.text {
					font-weight: 400;
					font-size: 26rpx;
					color: #95989D;
				}
			}

			.info_bot {
				margin-top: 24rpx;
				font-weight: 400;
				font-size: 26rpx;
				color: #95989D;
			}
		}

		.card_right {
			margin-left: 38rpx;
			width: 108rpx;
			height: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border: 2rpx solid #8883F0;
			border-radius: 20rpx;
			font-weight: 400;
			font-size: 28rpx;
			color: #8883F0;

		}

		.act1 {
			color: #8883F0;
			border: 2rpx solid #8883F0;
		}
	}

	.containers {
		width: 100%;
		height: 100vh;
		position: fixed;
		top: 0;
		padding-top: 130rpx;
		box-sizing: border-box;
		left: 0;
		z-index: 999 !important;
		/* background-color: #fff; */
		z-index: 99;
	}

	.pages {
		// padding-top: 136rpx !important;
		padding: 0 66rpx;
		box-sizing: border-box;
	}

	// text{
	// 	display: block;
	// }

	.sm {
		color: #77808D;
		border-radius: 0rpx 0rpx 0rpx 0rpx;
		// margin-top: 48rpx;
		display: inline-block;
	}

	.title {
		margin-bottom: 84rpx;

		image {
			display: inline-block;
			width: 48rpx;
			height: 48rpx;
			vertical-align: bottom;
			margin-right: 10rpx;
		}

		text:nth-child(1) {
			font-weight: 400;
			font-size: 96rpx;
			color: #262B37;
			line-height: 88rpx;
			text-align: left;
			font-style: normal;
			text-transform: none;
			display: block;
			margin-bottom: 48rpx;
		}
	}

	.dblist {
		display: flex;
		width: 100%;
		margin-top: 34rpx;
		background: #FFFFFF;
		box-shadow: 0rpx 10rpx 64rpx 0rpx rgba(0, 0, 0, 0.08);
		padding: 20rpx 0 24rpx 18rpx;
		box-sizing: border-box;
		text-align: center;
		border-radius: 10rpx;

		.lt {
			padding-left: 10rpx;
			box-sizing: border-box;
			margin-right: 38rpx;

			image {
				width: 42rpx;
				// height: 112rpx;
			}
		}

		.cen {
			width: 370rpx;
			padding-left: 10rpx;
			box-sizing: border-box;

			.name {
				font-family: AlibabaPuHuiTi, AlibabaPuHuiTi;
				font-weight: 400;
				font-size: 32rpx;
				color: #262B37;
				line-height: 40rpx;
				text-align: left;
				font-style: normal;
				text-transform: none;
				margin-top: 10rpx;
			}

			.mac {
				font-family: AlibabaPuHuiTi, AlibabaPuHuiTi;
				font-weight: 400;
				font-size: 26rpx;
				color: #262B37;
				line-height: 32rpx;
				text-align: left;
				font-style: normal;
				text-transform: none;
				margin-top: 16rpx;
			}
		}

		.rt {
			margin-top: 22rpx;

			text {
				display: inline-block;
				width: 108rpx;
				height: 60rpx;
				background: rgba(255, 255, 255, 0);
				border: 2rpx solid #8883F0;
				filter: blur(0px);
				border-radius: 20rpx;
				text-align: center;
				line-height: 60rpx;
				color: #8883F0;
			}
		}
	}

	.anniu {
		margin-top: 50rpx;
		padding: 0 90rpx;
		width: 100%;
		box-sizing: border-box;
		// position: fixed;
		// left: 0;
		// bottom: 112rpx;

		button {
			background: #8883F0;
			border-radius: 52rpx 52rpx 52rpx 52rpx;
			color: #fff;
		}
	}

	.mask {
		width: 622rpx;
		height: 710rpx;
		background: #FFFFFF;
		filter: blur(0px);
		border-radius: 20rpx;
		position: fixed;
		top: 475rpx;
		left: 50%;
		transform: translateX(-50%);
		padding-top: 38rpx;
		padding-left: 60rpx;
		padding-right: 60rpx;
		box-sizing: border-box;

		.titles {
			font-size: 48rpx;
			color: #262B37;
			line-height: 70rpx;
			text-align: center;
			margin-bottom: 24rpx;
		}

		text {
			display: block;
			font-size: 32rpx;
			color: #262B37;
			line-height: 56rpx;
			text-align: left;
		}

		button {
			margin-top: 46rpx;
			width: 266rpx;
			height: 96rpx;
			background: #8883F0;
			border-radius: 52rpx 52rpx 52rpx 52rpx;
			color: #fff;
			text-align: center;
			line-height: 96rpx;
		}
	}
</style>