<template>
	<view>
		<u-navbar :is-back="true" title='添加设备' title-color="#000" :border-bottom="false" :background="bgc" 
			id="navbar">
		</u-navbar>
        <!-- 有搜索到设备 -->
		<view class="you" v-if="flags">
			<view class="topone">
			    <image src="https://api.ccttiot.com/smartmeter/img/static/ubrPcpGQEXTadkBa1gKh" mode=""></image> 扫描到以下设备，点击添加！        	
			</view>
			<view class="toptwo">
				如未找到想添加的设备，点击重新搜索
			</view>
			<view class="list">
				<view class="list_item" v-for="(item,index) in devicesList" :key="index">
					<image src="https://api.ccttiot.com/smartmeter/img/static/ufPWKlVzDbHNflX0jUIv" mode=""></image>
					<view class="cen">
						<view class="name">
							丁丁浇花器
						</view>
						<view class="devmac">
							MAC：{{item.name}}
						</view>
					</view>
					<view class="add">
						添加
					</view>
				</view>
			</view>
		</view>
		
		
		<!-- 未搜索到设备 -->
		<view class="wei" v-else>
			<image src="https://api.ccttiot.com/smartmeter/img/static/uQ4g6A27FGtF34ebOtea" mode=""></image>
			<view class="sbname">
				搜索附近的设备失败
			</view>
			<view class="sbwz">
				搜索失败点击重新搜索注意打开蓝牙
			</view>
		</view>
		
		<!-- 点击搜索 -->
		<view class="btnss" @click="btnss" v-if="flag">
			重新搜索
		</view>
		<view class="btnss" v-else>
			重新搜索
		</view>
		
	</view>
</template>

<script>
	var xBlufi = require("@/components/blufi/xBlufi.js"); 
	export default {
			data() {
				return {
					bgc: {
						backgroundColor: "#fff",
					},
					active:1,
					flag:true,
					devicesList:[],
					deviceId:'',
				    name:'',
					mac:'2952BB7A4EE0',
					flags:true
				}
			},
			// 分享到好友（会话）
			onShareAppMessage: function() {
				return {
					title: '绿小能',
					path: '/pages/index/index'
				}
			},
			
			// 分享到朋友圈  
			onShareTimeline: function() {
				return {
					title: '绿小能',
					query: '',
					path: '/pages/index/index'
				}
			},
			onLoad() {
				let that = this
				xBlufi.initXBlufi(1);
				xBlufi.listenDeviceMsgEvent(true, that.funListenDeviceMsgEvent)
				xBlufi.notifyStartDiscoverBle({
					'isStart': true
				})
				setTimeout(() => {
					xBlufi.notifyStartDiscoverBle({
						'isStart': false
					})
					if (that.devicesList.length > 0) {
						xBlufi.notifyConnectBle({
							isStart: true,
							deviceId: that.deviceId,
							name: that.name
						})
					}
				}, 2000)
			},
			methods:{
                 btnss(){
					 uni.showLoading({
					 	title: '搜索中...'
					 })
					 this.flag = false
					 let that = this
					 xBlufi.initXBlufi(1);
					 xBlufi.listenDeviceMsgEvent(true, that.funListenDeviceMsgEvent)
					 xBlufi.notifyStartDiscoverBle({
					 	'isStart': true
					 })
					 setTimeout(() => {
					 	xBlufi.notifyStartDiscoverBle({
					 		'isStart': false
					 	})
					 	if (that.devicesList.length > 0) {
							that.flags = true
					 		xBlufi.notifyConnectBle({
					 			isStart: true,
					 			deviceId: that.deviceId,
					 			name: that.name
					 		})
					 	}else{
							that.flags = false
						}
						uni.hideLoading()
						that.flag = true
					 }, 2000)
				 },

				
				// 获取附近蓝牙设备列表
				funListenDeviceMsgEvent: function(options) {
					switch (options.type) {
						case xBlufi.XBLUFI_TYPE.TYPE_STATUS_CONNECTED:
							// that.setData({
							// 	connected: options.result
							// })
							if (!options.result) {
								uni.showModal({
									title: '很抱歉提醒你！',
									content: '小程序与设备异常断开',
									showCancel: false,
									//是否显示取消按钮
									success: function(res) {
										
									}
								})
							}
							break;
						case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS:
							if (options.result) {
								let devicesarr = options.data
								this.devicesList = devicesarr
								console.log(devicesarr,'111');
								// 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
								// 		console.log(device.name,this.mac,'222');
								// 		this.devicesList.push(device);
								// 		let uniqueDevicesList = Array.from(new Set(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
									})
									this.deviceIds = options.data.deviceId
									this.name = this.name
								}
							}else{
								
							}
							break;
						case xBlufi.XBLUFI_TYPE.TYPE_RECIEVE_CUSTON_DATA:
							this.ver_data = this.parseCustomData(options.data)
							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, 5) === "WATER")
								// 将过滤后的数组重新赋值给 this.devicesList
								this.devicesList = filteredDevices
							}
							break;
						case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_START:
							if (!options.result) {
								uni.showToast({
									title: '蓝牙未开启',
									icon: 'none',
									duration: 3000
								})
								this.flags = false
								return
							} else {
								
							}
							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="less">
	/deep/ .u-title{
		margin-bottom: 22rpx;
	}
	/deep/ .uicon-nav-back{
		margin-bottom: 22rpx;
	}
	.wei{
		text-align: center;
		image{
			width: 380rpx;
			height: 394rpx;
		}
		.sbname{
			font-size: 40rpx;
			color: #3D3D3D;
			margin-top: 80rpx;
			width: 100%;
			text-align: center;
		}
		.sbwz{
			font-size: 28rpx;
			color: #737B80;
			margin-top: 24rpx;
			width: 100%;
			text-align: center;
		}
	}
	.btnss{
		width: 512rpx;
		height: 92rpx;
		background: #48893B;
		border-radius: 46rpx 46rpx 46rpx 46rpx;
		border-radius: 50rpx;
		text-align: center;
		line-height: 92rpx;
		font-weight: 600;
		font-size: 40rpx;
		color: #FFFFFF;
		position: fixed;
		left: 50%;
		transform: translateX(-50%);
		bottom: 106rpx;
	}
	.list{
		width: 100%;
		border-radius: 20rpx;
		margin: auto;
		margin-top: 72rpx;
		.list_item{
			margin-top: 18rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			width: 100%;
			height: 152rpx;
			background: #FFFFFF;
			border-radius: 20rpx;
			box-shadow: 0rpx 10rpx 64rpx 0rpx rgba(0,0,0,0.08);
			padding: 18rpx 30rpx;
			box-sizing: border-box;
			image{
				width: 96rpx;
				height: 94rpx;
			}
			.cen{
				.name{
					font-size: 32rpx;
					color: #50565A;
				}
				.devmac{
					font-size: 24rpx;
					color: #BDBCBC;
					margin-top: 6rpx;
				}
			}
			.add{
				width: 108rpx;
				height: 60rpx;
				background: #FFFFFF;
				border: 3rpx solid #48893B;
				filter: blur(0px);
				border-radius: 20rpx;
				text-align: center;
				line-height: 60rpx;
				font-size: 28rpx;
				color: #48893B;
			}
		}
	}
	page{
		width: 100%;
		padding: 20rpx 64rpx;
		box-sizing: border-box;
		background-color: #fff;
	}
    .topone{
		font-size: 36rpx;
		color: #3D3D3D;
		display: flex;
		image{
			width: 48rpx;
			height: 48rpx;
		}
	}
	.toptwo{
		font-size: 28rpx;
		color: #737B7F;
		margin-top: 14rpx;
		width: 100%;
		padding-left: 48rpx;
		box-sizing: border-box;
	}

</style>