import {
	stringToBytes,
	ab2Str,
	getCurrentTime,
	showCustomModal,
	showCustomToast,
	commonStateCodeDeal,
	blueToother,
	storager,
	popuper,
	otherUtils
} from './util.js'

const blueToothMixin = {
	
	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {
		this.leavePageFlag = true
		commonStateCodeDeal(2, 'onHide=>离开页面')
	},
	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {
		commonStateCodeDeal(2, 'onUnload=>离开页面')
	},
	data() {
		return {
			pageLoadText: '',
			// 蓝牙连接相关
			deviceName: '',
			deviceId: '',
			characteristicId: '',
			connectState: false, // false不正常 true正常
			connected: false,
			readyRec: false, // 通知事件是否准备就绪标记。
			leavePageFlag: false,
		};
	},
	methods: {
		// async gobackDeal(){ // 返回上一页的处理逻辑
		// console.log(this.connectState, this.connectState)
		// 	// 添加蓝牙监测 如果手机蓝牙未开启，则直接返回home页面
		// 	try{
		// 		const adapterRes = await blueToother.openBluetoothAdapter()
		// 		if(!this.connectState){ // 没有正确连接的情况，返回直接退出页面到首页
		// 			uni.reLaunch({
		// 				url: '/pages/home/home',
		// 			});
		// 		}else if(this.connectState){
		// 			uni.reLaunch({
		// 				url: '/pages/home/home',
		// 			});
		// 		}else{
		// 			showCustomModal({
		// 				content: '验收仪设备正在连接中，是否要中断连接?',
		// 				showCancel: true,
		// 				success: ()=> {
		// 					this.stopLink({
		// 						showTip: false
		// 					})
		// 					uni.reLaunch({
		// 						url: '/pages/home/home',
		// 					});
		// 				},
		// 			})
		// 		}
				
		// 	}catch(e){
		// 		console.log(e)
		// 		uni.reLaunch({
		// 			url: '/pages/home/home',
		// 		});
		// 	}
		// },
		setConnected(flag){
			this.connected = flag
		},
		setConnectState(flag){ // flag:true  正常  false 不正常
			this.connectState = flag
			this.$store.commit('setLinked', flag) 
			uni.setStorageSync('connected', flag)
		},
		setNavBarTitle(content) {
			// this.navBarTitle = content + ' ' + this.deviceName
			this.pageLoadText = `${this.deviceName} 蓝牙加载中...${content}`
		},
		async initLink() {
			const device = uni.getStorageSync('deviceInfo')
			// console.log('deviceId', device, this)
			if (!device) {
				this.unlinkModalShow({
					redirectUrl: this.redirectUrl
				})
				return
			}

			this.pageLoadText = '正在加载'

			this.deviceId = device.deviceId;
			this.deviceName = device.deviceName;

			this.readyRec = false;
			// this.deviceadd = 'MAC ' + this.deviceId
			commonStateCodeDeal(2, `initLink=>DEVICE_ID:${this.deviceId} DEVICE_NAME:${this.deviceName}`)
		
			try {
				const result = await blueToother.openBluetoothAdapter(this.deviceId)
				if (result) {
					this.startLink()
				}
			} catch (res) {
				commonStateCodeDeal(res.errCode || res, 'initLink=>蓝牙适配器开启失败', this)
			}
		},
		async stopLink(opt) {
			await blueToother.closeBLEConnection(storager.get('deviceInfo').deviceId)
			await blueToother.closeBluetoothAdapter()
			
			this.setNavBarTitle('已断开 ')
			this.setConnectState(false)
			opt.cb && opt.cb()
		},
		async startLink() {
			this.setNavBarTitle('正在连接 ')
			commonStateCodeDeal(2, `startLink=>正在创建连接蓝牙设备`)
			try {
				// const result4close = await blueToother.closeBLEConnection(this.deviceId)

				const result = await blueToother.createBLEConnection(storager.get('deviceInfo').deviceId)
				console.log('result', result)
				if (result) {
					commonStateCodeDeal(2, 'createBLEConnection=>创建连接成功')
					this.setNavBarTitle('已创建连接 ')
					this.getBLEDeviceServices(storager.get('deviceInfo').deviceId);
					uni.onBLEConnectionStateChange((res) => { // 蓝牙连接意外断开等异常情况
						if (!res.connected) {
							this.setNavBarTitle('连接已断开')
							this.setConnectState(false)
							// this.stopLink()
							
						}
						commonStateCodeDeal(2,
							`onBLEConnectionStateChange=>蓝牙设备 ${res.deviceId} 连接状态改变=> ${res.connected}`
							)
					})
					
				}

			} catch (res) {
				this.setConnectState(false)
				commonStateCodeDeal(res.errCode || res, 'startLink=>连接失败', this)
			}

		},
		unlinkModalShow(opt = {}) {
			var option = {}
			option.content = opt.tipContent || '蓝牙未连接或已断开，请重新连接'
			option.success = opt.successCb ||  function(res){
				uni.redirectTo({
					url:  opt.redirectUrl //this.redirectUrl
				})
			} 
			showCustomModal(option)
		},
		setData(obj) {
			for (var key in obj) {
				this[key] = obj[key]
			}
		},

		async getBLEDeviceServices() {
			var that = this;
			this.readyRec = false;
			try {
				const res = await blueToother.getBLEDeviceServices(storager.get('deviceInfo').deviceId)
				console.log('res', res)
				if (res && res.services.length) {
					var isService = false;
					commonStateCodeDeal(2,
						`getBLEDeviceServices获取${res.services.length}条服务`
					)
					for (let i = 0; i < res.services.length; i++) {
						if (blueToother.serviceId == res.services[i].uuid) {
							isService = true;
							this.setNavBarTitle('服务已匹配')
							this.getBLEDeviceCharacteristics(storager.get('deviceInfo').deviceId, blueToother.serviceId);
						}
					}
					if (!isService) {
						this.setConnectState(false)
						this.setNavBarTitle('未发现可匹配的验收仪设备服务，请确认连接的设备是否正确~')
						popuper.hideLoading()
					}
				} else {
					this.setConnectState(false)
					this.setNavBarTitle('未发现服务')
					uni.hideLoading()
					this.unlinkModalShow({
						tipContent: '未发现服务，请重新连接蓝牙设备',
						redirectUrl: this.redirectUrl,
					})
				}
			} catch (res) {
				this.setConnectState(false)
				commonStateCodeDeal(res.errCode || res, 'getBLEDeviceServices=>服务获取失败', that)
			}
		},

		async readBLECharacteristicValue(deviceId, serviceId, characteristicId) {
			try {
				const res = await blueToother.readBLECharacteristicValue(deviceId, serviceId, characteristicId)
			} catch (res) {
				this.setConnectState(false)
				commonStateCodeDeal(res.errCode || res, '读取特征值失败', this)
			}
		},
		async notifyBLECharacteristicValueChange(deviceId, serviceId, characteristicId, state) {
			try {
				const res = await blueToother.notifyBLECharacteristicValueChange(deviceId, serviceId,
					characteristicId, state)
				this.setConnectState(true)
				
				this.setNavBarTitle('【Notify】开启成功')
				this.readyRec = true;
				uni.hideLoading()
				
				// this.gosend('POWER')
				await blueToother.writeBLECharacteristicValue('GETDATA')
				/**
				 * 024-12-27新增逻辑：
				 * 1、蓝牙连接成功后弹窗，点击确认调转页面
				 * 2、发送指令，获取小球id与电量
				 */
				showCustomModal({
					content: '蓝牙已连接，是否跳转首页',
					showCancel: true,
					success: ()=> {
						uni.reLaunch({
							url: '/pages/home/home',
						});
					},
				})
				
				
			} catch (res) {
				this.setConnectState(false)
				commonStateCodeDeal(res.errCode || res,
					`【Notify】监听值失败=> notifyBLECharacteristicValueChange`, this
				)
				this.setNavBarTitle('【Notify】开启失败')
			}
		},
		async getBLEDeviceCharacteristics(deviceId, serviceId) {
			var that = this;

			this.pageLoadText = '开始获取特征值'

			try {
				const res = await blueToother.getBLEDeviceCharacteristics(deviceId, serviceId)
				if (res && res.characteristics.length) {
					var validFlag = true // 特征值校验 读，写，通知
					for (let i = 0; i < res.characteristics.length; i++) {
						let item = res.characteristics[i];
						// console.log('特征值支持的操作类型=> ', item.properties);
						// if (item.properties.read) {
						// 	that.readBLECharacteristicValue(deviceId, serviceId, item.uuid)
						// }
						if (item.properties.write) {
							// console.log('[Write]', item.uuid);
							this._deviceId = deviceId;
							if (blueToother.characteristicId_WRITE == item.uuid) {
								commonStateCodeDeal(2,
									`特征值【WRITE】支持 => txdu:${that.txdu} CHARACTERISTIC_UUID:${item.uuid}`
								)
								// console.warn('find write uuid  ready to ', item.uuid);
								this._characteristicId = item.uuid;
								this._serviceId = serviceId;
							} else {
								this.setConnectState(false)
								that.setNavBarTitle('write特征值uuid不匹配')
							}
						}

						/**
						 * read: 
						 * write：
						 * notify: 设备可以向客户端（如手机或电脑）主动发送更新的数据
						 * indicate: 相比notify多了确认机制。
						 */
						if (item.properties.notify) {
							// console.log('[Notify]', item.uuid);
							if (blueToother.characteristicId_NOTIFY == item.uuid) {
								commonStateCodeDeal(2,
									`特征值【Notify】支持=> rxdu:${blueToother.characteristicId_NOTIFY} CHARACTERISTIC_UUID:${item.uuid}`
								)
								that.setNavBarTitle('正在开启通知')

								that.notifyBLECharacteristicValueChange(storager.get('deviceInfo').deviceId, serviceId, item.uuid, true)
							} else {
								this.setConnectState(false)
								that.setNavBarTitle('notify特征值uuid不匹配')
							}
						}
					}

					// 操作之前先监听，保证第一时间获取数据
					uni.onBLECharacteristicValueChange((characteristic) => {
						console.log('onBLECharacteristicValueChange值改变获取', characteristic)
						if (!this.readyRec) {
							return;
						}
						// var buf = new Uint8Array(characteristic.value);
						var recStr = ab2Str(characteristic.value);
						// console.warn('recstr: ', recStr, characteristic.characteristicId);
						if (blueToother.characteristicId_NOTIFY != characteristic.characteristicId) {
							// console.error('no same : ', blueToother.characteristicId_NOTIFY, characteristic.characteristicId);
							this.setConnectState(false)
							that.setNavBarTitle('特征值UUID值不匹配')
							commonStateCodeDeal(2, '特征值UUID值不匹配onBLECharacteristicValueChange')
							return;
						}					
						console.log('recStr*****', recStr)						
						
						if(recStr === 'HEART'){ // 心跳监测
							blueToother.writeBLECharacteristicValue('HEART')
							return
						}
						if(recStr.indexOf('HEART_OK') > -1){ // 处理掉测量深度对象值粘包后拼接的HEART字符串
							return
						}
						if(recStr.indexOf('HEART') > -1){ // 处理掉测量深度对象值粘包后拼接的HEART字符串
							recStr = recStr.split('HEART')[0]
						}
						// 设置电量值：
						// const recBlueResData = JSON.parse(recStr)
						// 返回值粘包处理
						 const recBlueResData = otherUtils.parseJsonString(recStr)
						 if(!recBlueResData){ // 如果解析后的数据为null 则直接返回不进行下面的业务逻辑
							return 
						 }
						 
						console.log('设备检测值：', JSON.stringify(recBlueResData))
						
						const qiuId = recBlueResData.id
						const power1 = recBlueResData.power1
						const power2 = recBlueResData.power2
						const ks = recBlueResData.ks
						const ss = recBlueResData.ss
						const wd = recBlueResData.temp
						
						if(qiuId){
							this.$store.commit('setMeasureVal', {
								qiuId
							})
							commonStateCodeDeal(2, '监听到设备反馈信息->小球ID'+qiuId)
						}
						
						if(power1){
							this.$store.commit('setMeasureVal', {
								power1
							})
							commonStateCodeDeal(2, '监听到设备反馈信息->仪器电量'+power1)
						}
						if(power2){
							this.$store.commit('setMeasureVal', {
								power2,
							})
							commonStateCodeDeal(2, '监听到设备反馈信息->小球电量'+power2)
						}
						
						if(ks){ // 孔深
							const temp4ks = ks/100
							this.$store.commit('setMeasureVal', {
								actualDepth: parseFloat(temp4ks.toFixed(2)), // 默认回传单位为cm
							})
							commonStateCodeDeal(2, '监听到设备反馈信息->测量孔深'+temp4ks)
						}
						if(ss){ // 水深
							const temp4ss = ss/100
							this.$store.commit('setMeasureVal', {
								actualWaterLevel: parseFloat(temp4ss.toFixed(2)),
							})
							commonStateCodeDeal(2, '监听到设备反馈信息->测量水深'+temp4ss)
						}
						
						// 设置测试值：
						if(wd){ // 温度
							const temp4wd = wd
							this.$store.commit('setMeasureVal', {
								actualHeat: parseFloat(temp4wd.toFixed(2)), // 默认回传单位为摄氏度
							})
							commonStateCodeDeal(2, '监听到设备反馈信息->测量温度~'+temp4wd)
						}
						
						// 接收到监测值，回复主机DATAOK
						if(ks || ss){
							blueToother.writeBLECharacteristicValue('DATAOK')
						}
						// 接收到监测值，回复主机DATAOK
						if(wd){
							blueToother.writeBLECharacteristicValue('DATAOK')
						}
					});
				} else {
					this.setNavBarTitle('未发现特征值')
					this.setConnectState(false)
				}
			} catch (res) {
				commonStateCodeDeal(res.errCode || res, 'getBLEDeviceCharacteristics=>特征值获取失败', that)
				this.setConnectState(false)
			}


		},
	},
}

export {
	blueToothMixin
}