<template>
	<view class="bluetoothPair-page">
		<view class="car-wrap">
			<view class="name">智能电动摩托车智驾 M7</view>
			<image :src="QINIU_URL + 'Fi6CPKj4-raA86oizhL3PiXD4DkH'" class="car-img" />
			<view>
				<viwe class="pair-title">是否配对改设备</viwe>
				<view class="pair-options">
					<view class="btn cancle">取消</view>
					<view class="btn confirm">配对</view>
				</view>
			</view>
		</view>
		<view class="pair-desc">
			点击下方 “ <text class="t">开始配对</text>”，请在系统弹窗中选择 “<text class="t">配对</text>”，以完成功能开启。
		</view>
		<view class="pair-tips">
			<view class="title">提示信息</view>
			<view class="text">使用感应解锁功能时，请务必保证手机蓝牙功能开启，在蓝牙列表中忽略此设备会导致感应解锁失败</view>
		</view>

		<!-- <view class="pair-btn" style="bottom: 240rpx;" @tap="switchNormal">切换正常 升级模式</view> -->
		<view class="pair-btn" style="bottom: 140rpx;" @tap="otaUpgrade">OTA升级</view>
		<view class="pair-btn" @tap="initiateBluetoothPairing">开始配对</view>
		<CenterDialog confirmText="配对" ref="centerDialog" />
		<Notice v-model="showNotice" title="感应解锁已开启" btnText="关闭" text='注意：请勿在手机蓝牙中忽略“电动车蓝牙02"设备，否则感应解锁功能将无法使用' />
	</view>
</template>

<script>
	import {
		QINIU_URL
	} from '@/common/constant'
	import CenterDialog from '@/component/comPopup/CenterDialog.vue';
	import Notice from '@/component/comPopup/Notice.vue';
	var bluetooth = require('@/common/bluetooth.js');
	const DF_CAB_INFO_DONE = 10000; //机柜信息传输完成
	var app = getApp();
	var config = require('../../common/config.js');
	var common = require('../../common/common.js');
	var http = require('../../common/http.js');
	var storage = require('../../common/storage.js');
	export default {
		components: {
			CenterDialog,
			Notice
		},
		data() {
			return {
				QINIU_URL,
				showNotice: false
			}
		},
		created(){
			bluetooth.initBluetooth()
			this.bluetoothClose()
		},
		methods: {
			otaUpgrade(){
				const me=this
				common.loading()
				console.log('开始升级');
				bluetooth.sendOTACommand('900000997', (res) => {
						// uni.hideLoading();
						// console.log('结束？？？？？');
						
						bluetooth.onConnectionStateChange('900000997', 'index', (res) => {
							uni.hideLoading();
							if (!res.connected) {
								// 蓝牙未连接
								console.log('蓝牙连接断开11111');
								if(!res.connected){
									uni.showModal({
										title: '提示',
										confirmText: '重新连接',
										content: '蓝牙连接中断，是否重新连接？',
										success: function(res) {
											if (res.confirm) {
												me.loadBluetooth();
											} else {}
										}
									});
								}
								// common.simpleToast('蓝牙连接断开1111', 2000)
							} else {
								console.log('蓝牙连接成功2222');
								common.simpleToast('蓝牙连接成功', 2000)
							}
						});
						// if (!res.connected) {
						// 	// 蓝牙未连接
						// 	common.simpleToast('蓝牙连接断开1111', 2000)
						// } else {
						// 	common.simpleToast('蓝牙连接成功2222', 2000)
						// }
					});
			},
			 initiateBluetoothPairing() {
				const deviceName = '电动车蓝牙';
				const pairingCode = '1234567890';
				// this.$refs.centerDialog.open({
				// 	title: '蓝牙配对请求',
				// 	content: `<span style="color:#060809;font-weight:bold">${deviceName}</span>
    //             想与您配对，请确保显示的配对密钥为
    //             <span style="color:#060809;font-weight:bold">${pairingCode}</span>`
				// });
				this.loadBluetooth()
				
			},
			bluetoothClose: function() {
			console.log(11112222);
				bluetooth.closeBluetoothAdapter();
				bluetooth.closeDevice(
					"900000997",
					() => {
						// this.setData({
						// 	bt_loading: false
						// });
					},
					() => {}
				);
				bluetooth.offCharacteristicStateChange("900000997", 'home');
				bluetooth.offConnectionStateChange("900000997", 'home');	 
			},
			switchNormal(){
				const me=this
				app.globalData.connectionState={}
				bluetooth.sendSwitchNormalCommand('900000997', (res) => {
						// uni.hideLoading();
						console.log(res,'sendSwitchNormalCommand 切换正常工厂模式');
						//切换工厂模式以后蓝牙断开 重新连接蓝牙
						console.log(app.globalData,'app.globalData');
						
						me.loadBluetooth()
						// if (!res.connected) {
						// 	// 蓝牙未连接
						// 	common.simpleToast('蓝牙连接断开1111', 2000)
						// } else {
						// 	common.simpleToast('蓝牙连接成功2222', 2000)
						// }
					});
			},
			loadBluetooth() {
				const me = this;
				var device = {
					mac_id: "900000997",
					btid: "900000997",
					btkey: "900000997",
					bt_type: "ZXCAR",
					device_type: "ZXCAR"
				};
				//bluetooth.acceptDevice(device) 是否是蓝牙类型列表里面的
				if (bluetooth.acceptDevice(device)) {
					// 打开蓝牙连接
					bluetooth.openBluetoothAdapter((res) => {
						common.loading()
						bluetooth.connectDevice(device, () => {
							uni.hideLoading();
							//监听蓝牙设备连接状态变化事件
							bluetooth.onConnectionStateChange(device.mac_id, 'index', (res) => {
								uni.hideLoading();
								if (!res.connected) {
									// 蓝牙未连接
									common.simpleToast('蓝牙连接断开')
								} else {
									common.simpleToast('蓝牙连接成功')
								}
							});
							// uni.hideLoading()
							// await bluetooth.sendOTACommand(device.mac_id, 'index', (res) => {
							// 		uni.hideLoading();
							// 		if (!res.connected) {
							// 			// 蓝牙未连接
							// 			common.simpleToast('蓝牙连接断开1111', 2000)
							// 		} else {
							// 			common.simpleToast('蓝牙连接成功2222', 2000)
							// 		}
							// 	});
							console.log('test');
							console.log(app.globalData.connectionStateChangeFunc,'app.globalData.connectionStateChangeFunc');
							//监听蓝牙特征值状态变化事件
							// 	bluetooth.onCharacteristicStateChange(device.mac_id, 'index', (data) => {
							// 		console.log(data,'datatest');
							// 		if (JSON.stringify(data) != '{}') {
							// 			if (data.state === DF_CAB_INFO_DONE) {
							// 				me.reportCabintInfo(device.mac_id, data.commandList);
							// 				uni.hideLoading();
							// 				common.simpleToast('蓝牙连接成功0000')
							// 				// 进行机柜蓝牙换电 API_DAYHIRE_CABINRT_BLUETOOTH_CHANGE_BATTERY
							// 			}
							// 		}
							// 	});
								
							// 	bluetooth.sendGetCabinetInfoCommand(
							// 		device.mac_id,
							// 		device,
							// 		(res) => {
							// 			common.loading();
							// 		},
							// 		(res) => {
							// 			uni.showModal({
							// 				title: '提示',
							// 				confirmText: '重新连接',
							// 				content: '连接失败，请尝试重新连接3333',
							// 				success: function(res) {
							// 					if (res.confirm) {
							// 						me.loadBluetooth();
							// 					} else {}
							// 				}
							// 			});
							// 		}
							// 	);
							
							},
							(res) => {
								console.log('观察周围是否有其他骑手连接，请等待对方完成 或 微信是否开启了蓝牙权限',res,res.errCode);
								uni.hideLoading();
								// var showContent = ""
								// if (res && ("errCode" in res)) {
								// 	if (res.errCode == 9000001) {
								// 		var showContent = "观察周围是否有其他骑手连接，请等待对方完成 或 微信是否开启了蓝牙权限！！"
								// 	} else {
								// 		var showContent = "连接失败，请尝试重新连接44444"+res.errCode
								// 	}
								// } else {
								// 	var showContent = "连接失败，请尝试重新连接55555"
								// }
								// uni.showModal({
								// 	title: '提示',
								// 	confirmText: '重新连接',
								// 	content: showContent,
								// 	success: function(res) {
								// 		if (res.confirm) {
								// 			me.loadBluetooth();
								// 		} else {}
								// 	}
								// });
							}, 
							(res) => {
								// console.log('蓝牙未打开或请在右上角设置授权小程序使用蓝牙66666');
								uni.hideLoading();
								uni.showModal({
									title: '提示',
									confirmText: '我知道了',
									content: '蓝牙未打开或请在右上角设置授权小程序使用蓝牙66666',
									success: function(res) {
										if (res.confirm) {
											me.loadBluetooth();
										} else {}
									}
								});
							}
						);
					}, );
				} else {
					//蓝牙连接未成功
					console.log('当前机柜未找到符合的蓝牙类型');
					uni.hideLoading();
					// uni.showModal({
					// 	confirmText: '我知道了',
					// 	content: '当前机柜未找到符合的蓝牙类型',
					// 	showCancel: false,
					// 	title: '提示',
					// 	complete: (res) => {}
					// });
				}
			},
			reportCabintInfo(dev_id, list){
				 var pushList = []
					for (var i = 0; list.length > i; i++) {
					  var sublist = []
					  for (var j = 0; list[i].length > j; j++) {
						sublist.push(parseInt(list[i][j]))
					  }
					  pushList.push(sublist)
					}
					const pData = {
					  dev_id: dev_id,
					  data: JSON.stringify(pushList)
					}
					const me = this
					http.postApi(config.API_CABINET_BLUETOOTH_INFO, pData, function (response) {
					  if (response.data.code === 200) {
						// me.setData({
						//   cabinetInfo: response.data.data.cabinetInfo
						// })
					  } else {
						simpleToast(response.data.msg)
					  }
					})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.bluetoothPair-page {
		padding: 56rpx 32rpx 48rpx;

		.car-wrap {
			width: 100%;
			background: #F1F3F4;
			border-radius: 32rpx;
			padding: 48rpx 32rpx 32rpx;
			text-align: center;

			.name {
				color: #060809;
				font-size: 32rpx;
				font-weight: bold;
			}

			.car-img {
				width: 480rpx;
				height: 324rpx;
				margin: 48rpx auto;
				display: block;
			}

			.pair-title {
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 24rpx;
				color: #060809;
			}

			.pair-options {
				margin-top: 30rpx;
				display: flex;
				justify-content: space-between;

				.btn {
					width: 302rpx;
					height: 80rpx;
					border-radius: 40rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 32rpx;

					&.cancle {
						color: #060809;
						background: #E4E8E9;
					}

					&.confirm {
						color: #FFFFFF;
						background: #060809;
					}
				}
			}
		}

		.pair-desc {
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			font-size: 24rpx;
			color: #828DA2;
			text-align: left;
			margin: 24rpx 0 48rpx;

			.t {
				color: #060809;
			}
		}

		.pair-tips {
			.title {
				font-weight: 500;
				font-size: 32rpx;
				color: #060809;
				margin-bottom: 20rpx;
			}

			.text {
				font-weight: 400;
				font-size: 24rpx;
				color: #828DA2;
			}
		}

		.pair-btn {
			position: absolute;
			width: 91%;
			bottom: 48rpx;
			height: 80rpx;
			background: #060809;
			border-radius: 40rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 32rpx;
			color: #FFFFFF;

			&:active {
				opacity: .7;
			}
		}
	}
</style>
