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

const blueToothMixin = {
	onBackPress(options) {
		this.gobackDeal()
		return true
		//console.log('from:' + options.from)
	},
	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {
		// console.warn('onHide goto disconnect');
		// if (this.connected) {
			this.leavePageFlag = true
			// this.stopLink({
			// 	showTip: false
			// })
			commonStateCodeDeal(2, 'onHide=>离开页面')
		// }
	},
	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {
		// if (this.connected) {
			this.leavePageFlag = true
			// this.stopLink({
			// 	showTip: false
			// })
			commonStateCodeDeal(2, 'onUnload=>离开页面')
		// }
	},
	data() {
		return {
			startMeasureText: '开始测量',
			pageLoadText: '',
			form: {
				// 回显详情
				'engineeringName': '',
				'middleSectionName': '',
				'segmentName': '',
				'alignmentLineName': '',
				'boreholeNumber': '',
				'throughHole': '',
				'designHoleDepth': '',
				'designInclination': '',
				// 新录入
				realTestHoleDepth: '',
				realTestInclination: '',
				// realTestTime: '',
			},
			// 蓝牙连接相关
			// 目标机器信息
			serviceu: '0000FFE0-0000-1000-8000-00805F9B34FB'.toUpperCase(),
			txdu: '0000FFE1-0000-1000-8000-00805F9B34FB'.toUpperCase(),
			rxdu: '0000FFE1-0000-1000-8000-00805F9B34FB'.toUpperCase(),

			deviceName: '',
			deviceId: '',
			characteristicId: '',
			connectState: false, // false不正常 true正常
			connected: false,
			// reconnect: '连接中...',
			// connectState: '正在连接',
			readyRec: false, // 通知事件是否准备就绪标记。
			canWrite: false,
			// recdata:'',
			leavePageFlag: false,

			// 交互优化
			btnLoading: 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 if(this.btnLoading){
					showCustomModal({
						content: '正在测量中，是否要中断测量?',
						showCancel: true,
						success: ()=> {
							this.gosend('STOP')
							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(this.deviceId)
			await blueToother.closeBluetoothAdapter()
			// uni.closeBLEConnection({
			// 	deviceId: this.deviceId,
			// 	 success:  (res) => {
			// 		commonStateCodeDeal(2, 'stopLink=>断开链接成功', this)
			// 	},
			// 	fail:  (err) => {
			// 	    commonStateCodeDeal(res.errCode || res, 'stopLink=>断开链接失败', this)
			// 	}
			// });
			
			this.setNavBarTitle('已断开 ')
			this.setConnectState(false)
		},
		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}`
							)
						// 如果是非主动离开页面导致断开链接则不显示链接蓝牙弹框
						if (!res.connected && !this.leavePageFlag) {
							showCustomModal({
								content: '当前连接已断开，是否重新连接？',
								showCancel: true,
								success: ()=>{
									uni.hideLoading()
									this.initLink()
								}
							})
						}
					})
					
				}

			} 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 (this.serviceu == res.services[i].uuid) {
							isService = true;
							this.setNavBarTitle('服务已匹配')
							this.getBLEDeviceCharacteristics(storager.get('deviceInfo').deviceId, this.serviceu);
						}
					}
					if (!isService) {
						this.setConnectState(false)
						this.setNavBarTitle('未发现可匹配的验收仪设备服务，请确认连接的设备是否正确~')
					}
				} 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')
				/**
				 * 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) {
							this.setData({
								canWrite: true
							});
							// console.log('[Write]', item.uuid);
							this._deviceId = deviceId;
							if (this.txdu == 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 || item.properties.indicate) {
							// console.log('[Notify]', item.uuid);
							if (this.rxdu == item.uuid) {
								commonStateCodeDeal(2,
									`特征值【Notify】支持=> rxdu:${this.rxdu} CHARACTERISTIC_UUID:${item.uuid}`
								)
								// console.warn('find notity uuid try enablec....', item.uuid);
								// this.showModalTips(this.rxdu + "\r正在开启通知...")
								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 (this.rxdu != characteristic.characteristicId) {
							// console.error('no same : ', this.rxdu, characteristic.characteristicId);
							this.setConnectState(false)
							that.setNavBarTitle('特征值UUID值不匹配')
							commonStateCodeDeal(2, '特征值UUID值不匹配onBLECharacteristicValueChange')
							return;
						}
						console.log('recStr*****', recStr)
						
						if(recStr === 'HEART'){ // 心跳监测
							var temp4heart = new Uint8Array(stringToBytes('HEART'));
							uni.writeBLECharacteristicValue({
								deviceId: storager.get('deviceInfo').deviceId,
								serviceId: '0000FFE0-0000-1000-8000-00805F9B34FB',
								characteristicId: '0000FFE1-0000-1000-8000-00805F9B34FB',
								value: temp4heart.buffer,
								success: (res) => {
									console.log('writeBLECharacteristicValue-successHEART:res=>', res)
								},
								fail: (res) => {
									console.log('writeBLECharacteristicValue-failHEART:res=>', res)
								},
							});
							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)
						// console.log('设备检测值：', recBlueResData.angle)
						if(recBlueResData.power1){
							this.$store.commit('setPower', {
								power1: recBlueResData.power1,
								power2: recBlueResData.power2,
								qiuId: recBlueResData.id
							})
							commonStateCodeDeal(2, '监听到设备反馈信息->电量'+JSON.stringify(recBlueResData))
						}
						if(recBlueResData.ks){
							this.$store.commit('setMeasureVal', {
								actualDepth: recBlueResData.ks,
								actualWaterLevel: recBlueResData.ss,
							})
							commonStateCodeDeal(2, '监听到设备反馈信息->测量深度'+JSON.stringify(recBlueResData))
							
							// 接收到监测深度值，回复主机DATAOK
							var temp4dataok = new Uint8Array(stringToBytes('DATAOK'));
							uni.writeBLECharacteristicValue({
								deviceId: storager.get('deviceInfo').deviceId,
								serviceId: '0000FFE0-0000-1000-8000-00805F9B34FB',
								characteristicId: '0000FFE1-0000-1000-8000-00805F9B34FB',
								value: temp4dataok.buffer,
								success: (res) => {
									console.log('writeBLECharacteristicValue-successHEART:res=>', res)
								},
								fail: (res) => {
									console.log('writeBLECharacteristicValue-failHEART:res=>', res)
								},
							});
						}
					});
				} else {
					this.setNavBarTitle('未发现特征值')
					this.setConnectState(false)
				}
			} catch (res) {
				commonStateCodeDeal(res.errCode || res, 'getBLEDeviceCharacteristics=>特征值获取失败', that)
				this.setConnectState(false)
			}


		},

		async gosend(text) {
			var that = this;
			if (text === 'START') {
				if (this.btnLoading) { // 如果正在测量，不允许操作
					return
				}
				this.btnLoading = true // 设置标志为 true，表示正在加载
			}

			var hex = text; //要发送的数据 有参数则直接发没有则获取输入框的值。
			var buffer1;

			//string发送
			var strbuf = new Uint8Array(stringToBytes(hex));
			// console.log('strtobyte ', strbuf);

			buffer1 = strbuf.buffer;

			if (buffer1 == null) {
				this.pageLoadText = '发送指令内容为空'
				commonStateCodeDeal(2, 'gosend -> 发送指定内容为空')
				this.setNavBarTitle('发送指令内容为空')
				return;
			}
			// const txlen = buffer1.byteLength;
			console.log('this.deviceId', this.deviceId)

			uni.writeBLECharacteristicValue({
				deviceId: that._deviceId,
				serviceId: that._serviceId,
				characteristicId: that._characteristicId,
				value: buffer1,
				success: (res) => {
					if (text === 'STOP') { // 停止测量保存数据
						// showCustomToast({
						// 	title: '已停止测量',
						// })
						this.btnLoading = false
					}
				},
				fail: (res) => {
					commonStateCodeDeal(res.errCode || res, 'gosend -> writeBLECharacteristicValue',
						this)
				},
			});
		},
	},
}

export {
	blueToothMixin
}