<template>
	<view class="content">
		<view class="loadView" v-if="showLoading">
			<image class="rotateAnim" src="../../static/loading.svg"></image>
			<text style="margin-left: 10rpx;">{{loadingText}}</text>
		</view>
		<view v-for="device in scanDeviceList" v-bind:key='device.mac' @click="gotoConnect(device)">
			<text>设备名称:{{device.name}} \n Mac:{{device.mac}}</text>
		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				isStartScan: false, //是否开始ble扫描
				stopScanTimer: undefined, //超时停止扫描的对象
				scanDeviceList: [], //扫描到的设备列表
				loadingText: '正在扫描设备', //load框的文字提示
				showLoading: false, //是否显示loading
				isOpenSetting:false,//是否跳转小程序设置界面
			}
		},
		onLoad() {
			//this.authorize()
			this.init()
		},
		onShow() {
			if(this.isOpenSetting){//如果为true就是从微信小程序设置返回到该页面，重新获取权限。
				this.isOpenSetting = false
				this.authorize()
			}
		},
		onBackPress() {
			console.log('onBackPress');
			this.stopScan()
		},
		methods: {
			init() {
				let that = this
				//初始化蓝牙模块
				uni.openBluetoothAdapter({
					success(res) {
						console.log(`初始化蓝牙模块成功 ${res}`)
						//开始扫描设备
						that.startBtScan();
					},
					fail(error) {
						if (error.errCode === 10001) { //在用户蓝牙开关未开启或者手机不支持蓝牙功能的情况下
							uni.showModal({
								title: '提示',
								content: '请打开蓝牙！',
								success: function(res) {
									if (res.confirm) {
										console.log('用户点击确定');
										uni.showToast({
											title: '请打开手机蓝牙以便扫描设备',
											icon: 'none',
										})
										that.showLoading = true;
										that.loadingText = '等待开启蓝牙。。。'
										that.lisenBtState()
									} else if (res.cancel) {
										console.log('用户点击取消');
										uni.navigateBack({});
									}
								}
							});
						} else { //其他错误
							uni.showToast({
								title: `查看手机蓝牙是否打开`,
								duration: 1000,
								icon: "none"
							})
							console.log(error)
						}
					},
				})
			},
			lisenBtState() { //监听蓝牙是否打开
				let that = this;
				uni.onBluetoothAdapterStateChange(function(res) {
					console.log('onBluetoothAdapterStateChange')
					console.log(res)
					if (res.available) { //蓝牙已打开
						//开始扫描设备
						that.startBtScan();
					}
				})
			},
			startBtScan() { //开始扫描蓝牙设备
				let that = this
				that.showLoading = true;
				that.loadingText = '正在扫描设备。。。'
				let count = that.scanDeviceList.length
				that.scanDeviceList.splice(0, count);
				//清除停止扫描的定时器
				clearTimeout(that.stopScanTimer)


				//开始扫描
				uni.startBluetoothDevicesDiscovery({
					success(res) {
						that.isStartScan = true
						console.log('开始扫描蓝牙设备');
						console.log(res);
						//30秒之后停止扫描
						that.stopScanTimer = setTimeout(() => {
							//停止扫描
							uni.stopBluetoothDevicesDiscovery({
								complete() {
									that.isStartScan = false
									that.showLoading = false;
									if(that.scanDeviceList.length == 0){
										uni.showModal({
											title: '提示',
											content: '沒有扫描到设备，是否重试！',
											success: function(res) {
												if (res.confirm) {
													console.log('重试！');
													that.startBtScan()
												} else if (res.cancel) {
													uni.navigateBack({});
												}
											}
										});
									}
								}
							})
						}, 30 * 1000);
						uni.onBluetoothDeviceFound(function(res) {
							//console.log('new device list has founded')
							console.log(res)
							console.log(res.devices)

							let devices = res.devices
							for (var i = 0; i < devices.length; i++) {
								console.log(devices[i])
								console.log(`名称：${devices[i].name}, mac : ${devices[i].deviceId}`)
								if (devices[i].name !== undefined && devices[i].name !== null && 
								devices[i].name !== '' && devices[i].name.startsWith('AIrSMArT')) {
									that.scanDeviceList.push({
										name: devices[i].name,
										mac: devices[i].deviceId
									})
								}
							}
						})
					},
					fail(err) {
						console.log(err)
					}
				})
			},
			gotoConnect(device) {
				this.stopScan()
				uni.navigateTo({
					url: `./ConnectBleDevice?name=${device.name}&mac=${device.mac}`
				})
			},
			stopScan() {
				//if(this.isStartScan){
					uni.stopBluetoothDevicesDiscovery({})
					clearTimeout(this.stopScanTimer)
					this.isStartScan = false
				//}
				
			},
			authorize(){
				let that = this
				// #ifdef MP-WEIXIN
				//uni.wx.getSetting()
				//uni.getUserPr
				//微信的定位授权
				uni.getSetting({
					success(res) {
						console.log("获取setting");
						console.log(res);
						if(!res.authSetting['scope.userLocation']){
							uni.authorize({
								  scope: 'scope.userLocation',
								  success() {
								  	console.log("获取到定位权限成功");
									//初始化蓝牙模块
									that.init()
								  },
								  fail(err){
									  console.log("获取到定位权限失败");
									  console.log(err)
									  uni.showModal({
									  	title:'未授权',
										content:'需要打开小程序设置，授权定位权限，来扫描蓝牙设备',
										success() {
											uni.openSetting({
												success() {
													that.isOpenSetting = true
													console.log('openSetting 成功')
												}
											})
										},
										fail() {
											uni.navigateBack({})
										}
									  })
								  }
							})
						}else{
							//初始化蓝牙模块
							that.init()
						}
					}
				})
				
				// #endif
				
			}
		}

	}
</script>

<style>
	.content {
		display: flex;
		width: 100vw;
		height: 100vh;
		flex-direction: column;
		align-items: center;
		/* justify-content: center; */

	}

	.loadView {
		display: flex;
		flex-direction: row;
		align-items: center;
		/* margin-top: 35vh; */
		/* justify-content: center; */
	}

	.rotateAnim {
		width: 60rpx;
		height: 60rpx;
		animation: turn 1200ms linear infinite;
	}

	@keyframes turn {
		0% {
			transform: rotate(0deg);
		}

		50% {
			transform: rotate(180deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}
</style>
