<template>
	<view class="content">
		<view class="cz-box" @click="toWork">
			<u-image width="100rpx" height="100rpx" src="/static/chengzhong.png"></u-image>
			<view class="tits">投放称重</view>
		</view>
		<view class="bindDev" @click="toFindDev">
			{{statusStr}}
		</view>
		<view class="devList">
			<view @click="connectBlue(item)" v-for="item in deviceList" :key="item.deviceId">
				<view class="names">
					<view>{{item.name}}</view>
					<view class="texts">MAC：{{item.deviceId}}</view>
				</view>
				<view class="btns" v-if="!connectStatus">点击连接</view>
				<view class="btns" @click="closeConnect" v-else>断开连接</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				deviceList:[], // 设备列表
				deviceId: '',
				connectedDeviceId: '',
				services: [],
				readsId:'',
				writeId:'',
				notifyServicweId: '',
				writeDatas: '',
				balanceData: '',
				hexstr: '',
				statusStr: '绑定电子秤',
				connectStatus: false // 设备连接状态
			}
		},
		methods: {
			// 去认证用户并开始称重
			toWork(){
				uni.navigateTo({
					url: '/pages/userAuth/userAuth'
				})
				// 连接成功
				if(this.connectStatus){
					uni.navigateTo({
						url: '/pages/userAuth/userAuth'
					})
				}else{
					uni.showModal({
						title:'提示',
						content:'请先绑定并连接电子秤',
						showCancel: false,
						complete(e) {
							console.log(e)
						}
					})
				}
			},
			toFindDev(){
				if(this.connectStatus){
					return
				}
				let _this = this
				const res = uni.getSystemInfoSync();
				// 初始化蓝牙模块
				uni.openBluetoothAdapter({
				  success(res) {
				    console.log(res)
					_this.statusStr = '初始化蓝牙模块成功'
					/* 获取本机的蓝牙状态 */
					setTimeout(() => {
						_this.init()
					}, 1000)
				  }
				})
				// 监听蓝牙适配器状态变化事件
				uni.onBluetoothAdapterStateChange(function (res) {
				  console.log(res,'适配器变化')
				  _this.statusStr = res.available ? '蓝牙已开启，点击重连' : '蓝牙已关闭，请开启手机蓝牙'
				  if(!res.available){
					  _this.closeConnect()
				  }
				})
				
				if(!res.bluetoothEnabled){
					uni.showModal({
						title:'提示',
						content:'请开启手机蓝牙',
						showCancel: false,
						complete(e) {
							console.log(e)
							_this.statusStr = '请开启手机蓝牙'
						}
					})
				}
			},
			// 初始化蓝牙
			init(){
				let _this = this
				uni.getBluetoothAdapterState({
				  success(res) {
				    console.log(res)
					_this.statusStr = '开始搜寻附近的电子秤'
					// 开始搜寻附近的蓝牙外围设备
					_this.startBluetoothDevicesDiscovery()
				  },
				  fail(res) {
					  console.log(res)
				  }
				})
			},
			startBluetoothDevicesDiscovery(){
				let _this = this
				uni.startBluetoothDevicesDiscovery({
				  services: [],
				  success(res) {
				    console.log(res)
					// 监听寻找到新设备的事件
					uni.onBluetoothDeviceFound(function (res) {
					  let devices = res.devices.filter(item => item.name == 'FAYA')
					  console.log(devices,'devices list')
					  if(devices.length){
						  _this.statusStr = '发现设备'
						  _this.deviceList = res.devices
					  }
					})
				  }
				})
			},
			connectBlue(item){
				this.deviceId = item.deviceId
				this.createBLEConnection()
			},
			// 开始连接指定设备
			createBLEConnection(){
				let _this = this
				uni.createBLEConnection({
				  // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
				  deviceId:this.deviceId,
				  success(res) {
				    console.log(res)
					_this.statusStr = '正在连接设备...'
					_this.connectedDeviceId = _this.deviceId
					// 获取连接设备的service服务
					setTimeout(()=>{
						_this.getBLEDeviceServices()						  
					},1000)
				  }
				})
			},
			// 获取连接设备的service服务
			getBLEDeviceServices(){
				let _this = this
				uni.getBLEDeviceServices({
				  // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
				  deviceId: _this.deviceId,
				  success(res) {
				    console.log('device services:', res.services)
					// _this.statusStr = '获取连接设备的service服务成功'
					_this.services = res.services
					/* 获取连接设备的所有特征值 */
					setTimeout(()=>{
						_this.getBLEDeviceCharacteristics()
					},500)
					// 停止搜索
					uni.stopBluetoothDevicesDiscovery({
						success: function(res) {
							console.log(res, '停止搜索')
						},
						fail(res) {
						}
					})
				  }
				})
			},
			// 获取连接设备的所有特征值
			getBLEDeviceCharacteristics(){
				let _this = this
				this.notifyServicweId = this.services[1].uuid
				uni.getBLEDeviceCharacteristics({
					deviceId: this.connectedDeviceId,
					serviceId: this.notifyServicweId,
					success: function(res) {
						console.log(res)
						// _this.statusStr = '获取连接设备的所有特征值成功'
						for (let i = 0; i < res.characteristics.length; i++) {
							let properties = res.characteristics[i].properties
							// 读id
							if(properties.notify&&!properties.read&&!properties.write){
								_this.readsId = res.characteristics[i].uuid
							}
							// 写id
							if(!properties.notify&&!properties.read&&properties.write){
								_this.writeId = res.characteristics[i].uuid
							}
							console.log(_this.readsId,_this.writeId, '蓝牙特征值 ==========')
							// 启用低功耗蓝牙设备特征值变化时的 notify 功能
							setTimeout(()=>{
								_this.notifyBLECharacteristicValueChange()
							},500)
						}
					},
					fail: function(res) {
						console.log(res)
					}
				})
			},
			// 启用低功耗蓝牙设备特征值变化时的 notify 功能
			 notifyBLECharacteristicValueChange() { 
				let that = this;
				uni.notifyBLECharacteristicValueChange({
					state: true,
					deviceId: that.connectedDeviceId,
					serviceId: that.notifyServicweId,
					characteristicId: that.readsId,
					success(res) {
						console.log(res,'notifyBLECharacteristicValueChange')
						that.statusStr = '连接成功，请点击投放称重'
						that.connectStatus = true
						/*用来监听手机蓝牙设备的数据变化*/
						uni.onBLECharacteristicValueChange(function(res) {
							console.log(res,'read data')
							that.balanceData = that.buf2string(res.value)
						})
						that.sendData()
					},
					fail(res) {
						console.log(res, '启用低功耗蓝牙设备监听失败')
						that.statusStr = '设备连接失败，请点击重试'
						that.closeConnect()
					}
				})
			},
			/*转换成需要的格式*/
		    buf2string(buffer) {
				let arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
				return arr.map((char, i) => {
					return String.fromCharCode(char);
				}).join('');
			},
			receiveData(buf) {
					return this.hexCharCodeToStr(this.ab2hex(buf))
			},
			/*转成二进制*/
			ab2hex (buffer) {
			  let hexArr = Array.prototype.map.call(
				  new Uint8Array(buffer), function (bit) {
					  return ('00' + bit.toString(16)).slice(-2)
				  }
			  )
			  return hexArr.join('')
			},
			/*转成可展会的文字*/
			hexCharCodeToStr(hexCharCodeStr) {
			  let trimedStr = hexCharCodeStr.trim();
			  let rawStr = trimedStr.substr(0, 2).toLowerCase() === '0x' ? trimedStr.substr(2) : trimedStr;
			  let len = rawStr.length;
			  let curCharCode;
			  let resultStr = [];
			  for (let i = 0; i < len; i = i + 2) {
				  curCharCode = parseInt(rawStr.substr(i, 2), 16);
				  resultStr.push(String.fromCharCode(curCharCode));
			  }
			  return resultStr.join('');
			},
			// 发送数据
			sendData(str) {
			    let that = this;
			    let dataBuffer = new ArrayBuffer(3)
			    let dataView = new DataView(dataBuffer)
			     
				dataView.setUint8(0, 0x02)
				dataView.setUint8(1, 0x41)
				dataView.setUint8(2, 0x03)
			    let dataHex = that.ab2hex(dataBuffer);
			    this.writeDatas = that.hexCharCodeToStr(dataHex);
			    uni.writeBLECharacteristicValue({
			        deviceId: that.connectedDeviceId,
			        serviceId: that.notifyServicweId,
			        characteristicId: that.writeId,
			        value: dataBuffer,
			        success: function (res) {
			            console.log('发送数据成功：' + that.writeDatas)
			        },
			        fail: function (res) {
						console.log('发送失败：' + res)
			        },
			        complete: function (res) {
			        }
			    })
			},
			 // 断开设备连接
			closeConnect() {
				let that = this;
			    if (that.connectedDeviceId) {
			        uni.closeBLEConnection({
			            deviceId: that.connectedDeviceId,
			            success: function(res) {
			                that.closeBluetoothAdapter()
			            },
			            fail(res) {
			            }
			        })
			    } else {
			        that.closeBluetoothAdapter()
			    }
			},
			// 关闭蓝牙模块
			closeBluetoothAdapter() {
				let that = this;
			    uni.closeBluetoothAdapter({
			        success: function(res) {
						console.log(res,'closeBluetoothAdapter')
						that.statusStr = '绑定电子秤'
						that.connectStatus = false
						that.balanceData = ''
						that.deviceList = []
			        },
			        fail: function(err) {
			        }
			    })
			},
		},
		onUnload() {
			this.closeConnect()
		}
	}
</script>

<style>
	.content{
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		background-image: linear-gradient(#24c4ff,#1a9ecf);
		height: 100vh;
		width: 100%;
	}
	.cz-box{
		text-align: center;
		background: #fff;
		padding: 50rpx 50rpx 30rpx;
		border:10rpx solid #ef9f2e;
		border-radius: 300rpx;
		box-shadow: 2rpx 2rpx 5rpx #916100;
		width: 250rpx;
		height: 250rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
	}
	.tits{
		padding: 20rpx 0;
		color: #ef9f2e;
	}
	.devList{
		width: 80%;
		padding:10rpx 30rpx;
	}
	.bindDev{
		margin: 30rpx 0;
	}
	.devList > view, .bindDev{
		display: flex;
		align-items: center;
		color: #ffff;
		border-radius: 100rpx;
		background: rgba(255,255,255,0.5);
		padding: 10rpx 40rpx;
		box-shadow: 2rpx 2rpx 5rpx rgba(0,0,0,0.2);
	}
	.devList > view .names{
		flex-grow: 1;
	}
	.devList > view .texts{
		font-size: 24rpx;
	}
	.devList > view .btns{
		text-align: center;
	}
</style>
