<template>
	<view class="qualitySpringback">
		<headers :showBack="true">
			<view class="headerName">
				回弹仪
			</view>
		</headers>
		<view class="content">
			<view class="chart_wrap">
				<view class="title" style="color: #488DEC;">·测量情况·</view>
				<view class="flex">
					<view class="chart">
						<image class="chart_img" src="/static/measure1.png"></image>
						<view class="chart_text">
							<view class="value">{{totalSurveyNum}}</view>
							<view class="name">全部测量<br />构件</view>
						</view>
					</view>
					<view class="chart">
						<image class="chart_img" src="/static/measure2.png" style="height: 257rpx;"></image>
						<view class="chart_text">
							<view class="value">{{abnormalSurveyNum}}</view>
							<view class="name">不合格<br />构件</view>
						</view>
					</view>
				</view>
			</view>
			<view class="title">
				<text style="color: #2A2B5B; opacity: 0.4;">·设备列表·</text>
				<button type="primary" plain @click="getList()" size="mini" class="searchBluetooth">
					<icon v-show="!isSearching" class="searchIcon" color="#007aff" type="search" size="15" />
					<loadingGig v-show="isSearching"></loadingGig>
					<!-- <image src="/static/loading.png" class="loadingIcon"></image> -->
					{{isSearching?'搜索蓝牙中':'搜索蓝牙'}}
				</button>
			</view>

			<!-- <input type="text" v-model="sendData" placeholder="" style="border:1px solid red;padding: 5px 10px;margin-bottom: 10px;" />
			<button type="default" @click="send()">发送数据</button> -->

			<view class="listItem"
				:class="(bleDeviceId==item.deviceId&&isLinkFinished=='连接成功')?'linkFinishedItem':'value'"
				v-for="(item,index) in bluetooth" @click="conn(item)" :key="index">
				<view class="item_name">蓝牙编码：<text class="value">{{item.name?item.name:item.deviceId}}</text></view>
				<view class="item_name">信号强度：<text class="value">{{item.RSSI}}</text></view>
				<!-- <view class="item_name">边接状态：<text class="value">{{isLink[index]==0?'未连接':isLink[index]==1?'连接中...':isLink[index]==2?'连接成功':
				isLink[index]==3?'连接失败':isLink[index]==4?'已断开':''
				}}</text></view> -->
				<view class="item_name">连接状态：<text
						:class="bleDeviceId==item.deviceId?'primaryText':'value'">{{bleDeviceId==item.deviceId?isLinkFinished:'未连接'}}</text>
				</view>
				<view class="animateBox" v-show="bleDeviceId==item.deviceId&&isLinkFinished=='连接中...'">

				</view>
			</view>
			<view class="placeholderBox" v-if="bluetooth.length==0">
				<image class="noDataImg" src="/static/noData.png"></image>
				<view class="text">暂未搜到蓝牙设备</view>
			</view>
			<view class="start_wrap">
				<view class="start_btn" @click="measureBtn">开始测量</view>
				<view class="start_btn" style="margin-top: 10px" @click="measureBtn(1)">开始测试</view>
			</view>
		</view>

		<view class="tabBarBox">
			<view class="item active">
				<image src="/static/personManage/index.png" class="img"></image>
				<view class="txt">
					首页
				</view>
			</view>
			<view class="item" @click="goHasMeasure">
				<image src="/static/personManage/location.png" class="img"></image>
				<view class="txt">
					已测量
				</view>
			</view>
			<view class="item" @click="queryStaff">
				<image src="/static/personManage/search.png" class="img"></image>
				<view class="txt">
					浇筑令
				</view>
			</view>

		</view>
	</view>
	</view>
</template>

<script>
	var times = 0
	import {
		getBlooth,
		createBLE,
		DeviceFound
	} from '@/static/js/BLEConn.js';
	import loadingGig from "@/components/loadingGig.vue"
	export default {
		components: {
			loadingGig
		},
		data() {
			return {
				projectDetail: '',
				bluetooth: [],
				isLink: [],
				totalSurveyNum: 0,
				abnormalSurveyNum: 0,
				sendData: '24535253F8230D0A',
				bleDeviceId: '',
				bleName: '',
				isLinkFinished: '未连接', // 未连接    连接中...    连接成功   连接失败
				isSearching: false,
				platform:'',
				
			}
		},
		onLoad() {
			//24535253F8230D0A   正在回弹采集命令
			//2445525396230D0A   停止回弹采集命令
			//24524449DF230D0A   获取设备信息命令
			this.projectDetail = JSON.parse(uni.getStorageSync('projectDetail'));
			if(uni.getStorageSync('measureDevType')){
				uni.removeStorageSync('measureDevType');
			}
			
			this.getDevTotal();

			// this.bluetooth=[
			// 	{
			// 		name:'aaaa',deviceId:'11111111',RSSI:'12'
			// 	}
			// ]
			this.platform=uni.getStorageSync('systemInfo').platform
			let that = this
			uni.getNetworkType({
			    success: function (res) {
			        console.log(res.networkType);
					if(res.networkType != 'none'){
						let outLineData = []
						if(uni.getStorageSync('outLineData')){
							outLineData = JSON.parse(uni.getStorageSync('outLineData'))
							that.uploadData(outLineData)
						}
						console.log(outLineData)
					}
			    }
			});
			
		},
		onshow(){
			if(uni.getStorageSync('oldObj')){
				console.log(uni.getStorageSync('oldObj'))
			}
		},

		methods: {
			uploadData(data){
				console.log(data)
				this.sendRequest({
					url: 'xmgl/massReboundSurveyArea/saveBatch',
					method: 'post',
					data: data,
					success: (res) => {
						if (res.code == 200) {
							console.log('res.result', res.result)
							uni.showToast({
								title: '离线数据上传成功！'
							})
							uni.removeStorageSync('outLineData');
						}
					}
				})
				
			},
			// 搜索蓝牙列表
			async getList() {
				// uni.showLoading({
				// 	title: '蓝牙搜索中...',
				// 	icon: 'none'
				// })
				this.isSearching = true
				var flag = false // 标记是否进入了getBLooth
				this.closeDevConnect()
				await getBlooth().then(res => {
					// console.log(res)
					flag = true
					this.isSearching = false
					uni.showToast({
						title: '蓝牙搜索完成',
						icon: 'none'
					})
					// console.log('第' + times + '次')
					// if (res.devices.length == 0 && times <= 3) {
					// 	times++
					// 	this.getList()
					// } else {
					this.bluetooth = res.devices
					if(res.devices.length==0){
						// uni.showToast({
						// 	title: '请先开启手机定位',
						// 	icon: 'none',
						// 	mask: true
						// })
						this.checkOpenGPSServiceByAndroid()
					}
					console.log('蓝牙设备列表')
					console.log(this.bluetooth)
					// uni.hideLoading()
					// times = 1
					// // 打开弹框
					// this.$refs.popup.open()
					// this.scanBLE = true
					// }
				}).catch(err => {
					flag = false
					// times = 1
				})
				// console.log(flag)
				if (!flag) {
					this.isSearching = false
					// uni.hideLoading()
					let txt = ''
					if(this.platform=='android'){
						txt='和定位'
					}
					uni.showToast({
						title: '请先开启手机蓝牙'+txt,
						icon: 'none',
						mask: true
					})
					console.log('没有进入getBlooth')
				}
			},
			checkOpenGPSServiceByAndroid() {
				let system = uni.getSystemInfoSync(); // 获取系统信息
				// console.log(system);
				if (system.platform === 'android') {
					// 判断平台
					var context = plus.android.importClass('android.content.Context');
					var locationManager = plus.android.importClass('android.location.LocationManager');
					var main = plus.android.runtimeMainActivity();
					var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
					if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
						uni.showModal({
							title: '提示',
							content: '请打开定位服务功能',
							showCancel: false, // 不显示取消按钮
							success() {
								if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
									var Intent = plus.android.importClass('android.content.Intent');
									var Settings = plus.android.importClass('android.provider.Settings');
									var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
									main.startActivity(intent); // 打开系统设置GPS服务页面
								} else {
									console.log('GPS功能已开启');
								}
							}
						});
					}
				}
			},
			addDevice(devName, devNo) {
				console.log(devName, devNo)
				
				this.sendRequest({
					url: 'xmgl/massReboundMeasureDev/add',
					method: 'post',
					hideLoading: 'true',
					data: {
						projectSn: this.projectDetail.projectSn,
						devName: devName,
						devNo: devNo
					},
					success: (res) => {

					}
				})
			},
			async closeDevConnect(id) {
				if (this.bleDeviceId) {
					let that = this
						uni.closeBLEConnection({
							deviceId: this.bleDeviceId,
							success(res) {
								console.log('断开上一个连接的蓝牙')
								that.bleDeviceId = ''
								that.bleName = ''
								that.isLinkFinished = '未连接'
								
							}
						})
				}
			},
			// 2. 选中蓝牙并连接
			async conn(item) {
				// console.log(item)
				// uni.showLoading({
				// 	title: "正在连接...",
				// 	icon: "loading",
				// 	mask: true
				// })
				// await this.closeDevConnect(item.deviceId)
				if (this.bleDeviceId) {
					let that = this
					// that.closeBle().then(res => {
					// 	// this.closeDiv = false
					// 	// this.clear()
					// 	// uni.hideLoading()
					// 	console.log('断开蓝牙成功')
					// }).catch(err => {
					// 	// uni.hideLoading()
					// 	console.log('断开蓝牙失败')
					// })
					
					// return new Promise((resolve, reject) => {
						uni.closeBLEConnection({
							deviceId: this.bleDeviceId,
							success(res) {
								console.log('断开上一个连接的蓝牙')
								if (that.bleDeviceId == item.deviceId && (that.isLinkFinished == '连接成功')) {
									that.bleDeviceId = ''
									that.bleName = ''
									that.isLinkFinished = '未连接'
									uni.showToast({
										title: '已断开连接'
									})
								}
							}
						})
					// })
					if (this.bleDeviceId == item.deviceId && (that.isLinkFinished != '连接失败')) {
						console.log('停止接下来的操作')
						return false
					}
				}
				// console.log('执行完closeDevConnect')
				this.bleDeviceId = item.deviceId
				this.bleName = item.name
				this.isLinkFinished = '连接中...'
				// connBLESuc++
				let create = true // 判断有没有进入createBLE
				// '49535343-FE7D-4AE5-8FA9-9FAFD205E455'
				await createBLE(item, '0000FFE0-0000-1000-8000-00805F9B34FB').then(res => {
					console.log('createBLE ' + res)
					create = false
					this.isLinkFinished = '连接成功'
					this.addDevice(item.name, item.deviceId)
				}).catch(err => {
					console.log('createBLE error')
					// this.isLinkFinished = '连接失败'
					create = false
				
				})
				// setTimeout(() => {
				// 	if (create) {
				// 		console.log('没有进入回调')
				// 		this.isLinkFinished = '连接失败'
				// 		uni.hideLoading()
				// 		setTimeout(() => {
				// 			uni.showToast({
				// 				// title: this.other.fail,
				// 				title: "连接失败",
				// 				icon: "none"
				// 			})
				// 		}, 500)
				// 	}

				// }, 3000)
			},



			getDevTotal() {
				let that = this;
				this.sendRequest({
					url: 'xmgl/massReboundSurveyArea/selectProjectCount',
					method: 'post',
					data: {
						projectSn: that.projectDetail.projectSn
					},
					success: res => {
						that.totalSurveyNum = res.result.totalSurveyNum;
						that.abnormalSurveyNum = res.result.abnormalSurveyNum;
						setTimeout(() => {
							this.getList()
						}, 200)

					}
				})
			},
			measureBtn(val) {
				if (this.isLinkFinished != '连接成功') {
					uni.showToast({
						title: '请先连接蓝牙'
					})
				} else {
					
					if(val == 1){
						uni.navigateTo({
							url: './selectPage?isAdd=true&isTest=true'
						});
					} else {
						uni.navigateTo({
							url: './selectPage?isAdd=true'
						});
					}
				}

			},
			goHasMeasure() {
				uni.navigateTo({
					url: './selectPage?isAdd=false'
				});
			},
			queryStaff() {
				uni.navigateTo({
					url: './pouringOrderManage'
				});
			}
		}
	}
</script>

<style scoped lang="scss">
	.flex {
		display: flex;
		align-items: center;
		justify-content: space-around;
	}

	.flex2 {
		display: flex;
		align-items: center;
	}

	.flex3 {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.title {
		text-align: center;
		font-size: 30rpx;
		letter-spacing: 1.4px;
		line-height: 21px;
		margin-bottom: 8px;
		position: relative;
	}

	.content {
		padding: 10px 30rpx 62px;
		box-sizing: border-box;
		width: 100%;

	}

	.chart_wrap {
		width: 100%;
		box-shadow: 0 2px 10px 0 rgba(212, 220, 236, 0.65);
		border-radius: 8px;
		background-color: rgba(251, 251, 255, 1);
		box-sizing: border-box;
		padding: 10px 0 20px;
		margin-top: 10px;
		margin-bottom: 20px;
	}

	.chart {
		position: relative;
		width: 266rpx;
		height: 269rpx;
	}


	.chart_img {
		width: 266rpx;
		height: 269rpx;
		position: absolute;
		top: 0;
		right: 0;
		left: 0;
		bottom: 0;
		z-index: 2;
	}

	.chart_text {
		z-index: 999;
		text-align: center;
		position: relative;
		top: 50%;
		/*偏移*/
		margin-top: -38px;
	}

	.chart_text .value {
		font-size: 60rpx;
		font-weight: 700;
	}

	.chart_text .name {
		color: #54547C;
		font-size: 30rpx;
		line-height: 18px;
	}

	.listItem {
		line-height: 26px;
		margin-top: 15px;
		box-shadow: 0 2px 10px 0 rgba(212, 220, 236, 0.65);
		border-radius: 5px;
		padding: 10px 30rpx;
		font-size: 28rpx;
		position: relative;
	}

	.linkFinishedItem {
		background-color: rgba(219, 231, 243, 0.2);
	}

	.animateBox {
		position: absolute;
		left: 0;
		top: 5%;
		width: 80px;
		height: 90%;
		background: linear-gradient(to right, rgba(219, 231, 243, 0.2), rgba(219, 231, 243, 0.8), #dbe7f3);
		filter: blur(4px);
		animation: mymove 1s infinite;
	}

	@keyframes mymove {
		from {
			left: 0px;
		}

		to {
			left: 80%;
		}
	}

	@-webkit-keyframes mymove

	/*Safari and Chrome*/
		{
		from {
			left: 0px;
		}

		to {
			left: 80%;
		}
	}

	.item_name {
		color: rgba(42, 43, 91, 0.6);
	}

	.item .value {
		color: #2A2B5B;
	}

	.item .active {
		color: $uni-color-primary;
	}

	.start_wrap {
		margin-top: 40px;
		margin-bottom: 40px;
	}

	.start_btn {
		text-align: center;
		pos-bottom: 20px;
		line-height: 45px;
		width: 60%;
		margin: 0 auto;
		background-color: rgba(72, 141, 236, 1);
		color: #fff;
		border-radius: 35px;
		box-shadow: 0 2px 4px 0 rgba(43, 141, 243, 0.42);

	}

	.start_btn:active {
		background-color: rgba(65, 129, 254, 0.8);
	}

	.searchBluetooth {
		position: absolute;
		right: 0px;
		top: -5px;
		padding: 0 8px;
	}

	.tabBarBox {
		display: flex;
		align-items: center;
		font-size: 12px;
		border-top: 1px solid rgba(151, 151, 151, 0.2);
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 62px;
		background-color: white;
		z-index: 22;

		.item {
			flex: 1;
			// display: inline-flex;
			text-align: center;
			color: rgba(148, 149, 173, 1);

			.img {
				width: 35px;
				height: 35px;
			}

			&.active {
				color: rgba(72, 141, 236, 1);
			}
		}
	}

	.placeholderBox {
		margin: 50px auto;
	}

	.searchIcon {
		vertical-align: middle;
		margin-right: 3px;
	}

	.loadingIcon {
		width: 16px;
		height: 16px;
		vertical-align: middle;
		margin-right: 3px;

		animation: mymove2 0.5s infinite;
	}


	@keyframes mymove2 {
		from {
			transform: rotate(0deg);
		}

		to {
			transform: rotate(180deg);
		}
	}

	@-webkit-keyframes mymove2

	/*Safari and Chrome*/
		{
		from {
			transform: rotate(0deg);
		}

		to {
			transform: rotate(180deg);
		}
	}
</style>
