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

		<!-- {{ $t('测试指令！！！别删除') }} -->
		<!-- <view class="pair-btn" style="bottom: 240rpx;" @tap="nearCloseUnlockBtn">{{ $t('关闭靠近解锁') }}</view> -->
		<!-- <view class="pair-btn" style="bottom: 240rpx;" @tap="nearTest">{{ $t('跳转解绑配对') }}</view> -->
		<!-- <view class="pair-btn" style="bottom: 240rpx;" @tap="nearUnlockBtn">{{ $t('靠近解锁') }}</view> -->
		<!-- <view class="pair-btn" style="bottom: 140rpx;" @tap="otaUpgrade">OTA{{ $t('升级') }}</view> -->
		<view class="pair-btn" @tap="initiateBluetoothPairing">{{ $t('开始配对') }}</view>
		<CenterDialog :confirmText="$t('配对')" ref="centerDialog" />
	</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');
	import permision from "@/js_sdk/wa-permission/permission.js"
	const DF_CAB_INFO_DONE = 10000; //机柜信息传输完成
	var config = require('../../common/config.js');
	var common = require('../../common/common.js');
	var http = require('../../common/http.js');
	var storage = require('../../common/storage.js');
	// const app = getApp({allowDefault: true})
	export default {
		components: {
			CenterDialog,
			Notice
		},
		data() {
			return {
				QINIU_URL,
				showNotice: false,
				// model_name:'',
				car_sn:'',
				car_info:{},
				isReconnecting: false // 新增标志位
			}
		},
		onLoad(){
			
			this.car_info= uni.getStorageSync('car_info')
			this.car_sn=this.car_info.car_sn
			// this.setData({
			// 	model_name,
			// 	car_sn
			// })
			 // console.log(app,'app');
			 // return
			 // bluetooth.initBluetooth()
			 // this.bluetoothClose()
			const isOpenBluetoothPermission=permision.checkBluetoothPermission()
			if(isOpenBluetoothPermission){
				//初始化 连接蓝牙  -下发配对指令 -会断开连接-直接再次连接 记得不要提示可以蓝牙断开连接
				//点击配对-连接蓝牙-调用配对-确认配对  取消 断开蓝牙 不走逻辑
				bluetooth.initBluetooth()
				this.bluetoothClose()
			}else{
				common.simpleToast(this.$t('蓝牙未启用')+','+this.$t('请先打开蓝牙'))
			}
			
		},
		methods: {
			otaUpgrade(){
				const me=this
				common.loading()
				console.log(this.$t('开始升级'));
				bluetooth.sendOTACommand(this.car_sn, (res) => {
						// uni.hideLoading();
						// console.log(this.$t('结束？？？？？'));
						
						bluetooth.onConnectionStateChange(this.car_sn, 'index', (res) => {
							uni.hideLoading();
							if (!res.connected) {
								// 蓝牙未连接
								console.log('蓝牙连接断开11111');
								if(!res.connected){
									uni.showModal({
										title: this.$t('提示'),
										confirmText: this.$t('重新连接'),
										content: this.$t('蓝牙连接中断，是否重新连接？'),
										success: function(res) {
											if (res.confirm) {
												me.loadBluetooth();
											} else {}
										}
									});
								}
								// common.simpleToast('蓝牙连接断开1111', 2000)
							} else {
								console.log('蓝牙连接成功2222');
								common.simpleToast(this.$t('蓝牙连接成功'), 2000)
							}
						});
						// if (!res.connected) {
						// 	// 蓝牙未连接
						// 	common.simpleToast('蓝牙连接断开1111', 2000)
						// } else {
						// 	common.simpleToast('蓝牙连接成功2222', 2000)
						// }
					});
			},
			 initiateBluetoothPairing() {
				const deviceName = this.$t('电动车蓝牙');
				const pairingCode = '1234567890';
				// this.$refs.centerDialog.open({
				// 	title: this.$t('蓝牙配对请求'),
				// 	content: `<span style="color:#060809;font-weight:bold">${deviceName}</span>
    //             想与您配对，请确保显示的配对密钥为
    //             <span style="color:#060809;font-weight:bold">${pairingCode}</span>`
				// });
				this.loadBluetooth()
				
			},
			bluetoothClose: function() {
				bluetooth.closeBluetoothAdapter();
				bluetooth.closeDevice(
					this.car_sn,
					() => {
						console.log(this.$t('关闭蓝牙连接'));
						// this.setData({
						// 	bt_loading: false
						// });
					},
					() => {}
				);
				bluetooth.offCharacteristicStateChange(this.car_sn, 'index');
				bluetooth.offConnectionStateChange(this.car_sn, 'index');	 
			},
			switchNormal(){
				const me=this
				const app=getApp()
				app.globalData.connectionState={}
				bluetooth.sendSwitchNormalCommand(this.car_sn, (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)
						// }
					});
			},
			nearUnlockBtn(){
				bluetooth.nearUnlock(this.car_sn, (res) => {
						console.log(this.$t('接近解锁下发成功'));
					});
			},
			nearCloseUnlockBtn(){
				bluetooth.nearCloseUnlock(this.car_sn, (res) => {
						console.log(this.$t('接近解锁下发成功'));
					});
			},
			isBluetoothLock(mac_id){
				// if()
				bluetooth.getNearUnlockSet(mac_id, 'index',(res)=>{
					
					//下发打开接近解锁指令
					console.log(this.$t('获取接近解锁下发成功'));
				})
			},
			loadBluetooth() {
				const me = this;
				const third_device_type = this.car_info.third_device_type
				console.log(third_device_type,'third_device_type');
				var device = {
					mac_id: this.car_sn,
					btid: this.car_sn,
					btkey: this.car_sn,
					bt_type: third_device_type,
					device_type: third_device_type,
					// bt_type: 'ZXCAR',
					// device_type: 'ZXCAR'
				};
				const app=getApp()
				app.globalData.connectionState={}
				//bluetooth.acceptDevice(device) 是否是蓝牙类型列表里面的
				if (bluetooth.acceptDevice(device)) {
					// 打开蓝牙连接
					bluetooth.openBluetoothAdapter((res) => {
						common.loading()
						bluetooth.connectDevice(device, () => {
							
							// bluetooth.getNearUnlockSet(device.mac_id,)
							// uni.hideLoading();
							//监听蓝牙设备连接状态变化事件
							bluetooth.onConnectionStateChange(device.mac_id, 'index', (res) => {
								
								if (!res.connected &&!('lockType' in app.globalData.nearLockInfo)) {
									// 蓝牙连接断开
									console.log(this.$t('蓝牙连接断开'));
									if (!me.isReconnecting) { // 检查标志位
										me.isReconnecting = true; // 设置标志位
										setTimeout(() => {
											me.loadBluetooth();
											me.isReconnecting = false; // 重置标志位
										}, 100);
									}
								} else {
									console.log(this.$t('蓝牙连接成功'));
									// uni.hideLoading();
									me.isBluetoothLock(device.mac_id)
									
								}
							});

							},
							(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: this.$t('提示'),
								// 	confirmText: this.$t('重新连接'),
								// 	content: showContent,
								// 	success: function(res) {
								// 		if (res.confirm) {
								// 			setTimeout(()=>{
								// 				me.loadBluetooth();
								// 			},100)
								// 		} else {}
								// 	}
								// });
							}, 
							(res) => {
								// console.log('蓝牙未打开或请在右上角设置授权小程序使用蓝牙66666');
								uni.hideLoading();
								uni.showModal({
									title: this.$t('提示'),
									confirmText: this.$t('我知道了'),
									content: '蓝牙未打开或请在右上角设置授权小程序使用蓝牙66666',
									success: function(res) {
										if (res.confirm) {
											me.loadBluetooth();
										} else {}
									}
								});
							}
						);
					}, );
				} else {
					//蓝牙连接未成功
					console.log(this.$t('当前机柜未找到符合的蓝牙类型'));
					uni.hideLoading();
					// uni.showModal({
					// 	confirmText: this.$t('我知道了'),
					// 	content: this.$t('当前机柜未找到符合的蓝牙类型'),
					// 	showCancel: false,
					// 	title: this.$t('提示'),
					// 	complete: (res) => {}
					// });
				}
			},
			nearTest(){
				uni.navigateTo({
					url:'/pages/bluetoothUnlock/unlockSet'
				})
			}
			
		}
	}
</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>
