<template>
	<view class="bt">
		<view class="bt-t1">工牌开机后，须开启手机蓝牙和位置定位搜索</view>
		<view class="bt-c1">
			<text>蓝牙</text>
			<view @click="openBlue()" :class="['bt-sw',connectState?'bt-sw-ac':'']"></view>
		</view>
		<view class="bt-t2">
			智能工牌开机后2分钟内会发送蓝牙信号，请先开机后并2分钟内搜索设备；如超时请重新开机搜索！或者请重新进入小程序并开启定位功能！
		</view>
		<!-- <view class="bt-t3">
			输入或搜索需要查询的SN
		</view>
		<view class="bt-input1">
			<view class="bt-input1-c">
				<image src="/static/images/bluetooth-search.png" />
				<input v-model="keyword" @confirm="getBluetoothDevices" placeholder="请输入设备SN" />
			</view>
			<image class="scan" @click="ermScan" src="/static/images/bluetooth-scan.png" />
		</view> -->
		<view class="bt-c2">
			<view class="bt-c2-l">我的工牌</view>
			<image @click="startBluetoothDevicesDiscovery" src="/static/images/bluetooth-sx.png"
				:class="['bt-c2-r',isSearch?'bt-c2-r-ani':'']" />
		</view>

		<view v-for="(item,index) in blist" :key="index" @click="goDetail(item)" class="bt-c3">
			<view class="bt-c3-l">{{item.name}}</view>
			<image src="/static/images/jiantop.png" />
		</view>

		<view class="bt-c2">
			<view class="bt-c2-l">已绑定的工牌</view>
		</view>

		<view v-for="(item,index) in savelist" :key="index" @click="goDetail(item)" @longpress="delOld(index)" class="bt-c3">
			<view class="bt-c3-l">
				{{item.name}}
				<image mode="heightFix" v-if="item.isConnect && item.isConnect == 1" src="/static/images/bluetooth-con.png" />
			</view>
			<image src="/static/images/jiantop.png" />
		</view>
		<view v-if="savelist.length > 0" class="bt-c2" style="margin-top: 20rpx;">
			<view class="bt-c2-l">长按删除</view>
		</view>

	</view>
</template>

<script>
	import {
		serviceId,
		closeBlueAdapter,
		readCharacteristicId,
		writeCharacteristicId
	} from "@/utils/blue.js";
	import {
		mapState,
	} from 'vuex';

	export default {
		data() {
			return {
				privacyVisible: false,
				open: false,
				serviceId,
				readCharacteristicId,
				writeCharacteristicId,
				blist: [],
				keyword: "",
				savelist: [],
				isSearch: false
			}
		},
		computed: {
			...mapState(['connectDev', 'connectState']),
		},
		watch: {
			connectDev(newVal) {
				this.savelist = this.savelist.filter(v => {
					v.isConnect = '0';
					if (newVal && v.deviceId == newVal.deviceId) v.isConnect = '1';
					if (v.name && v.deviceId) return v;
				})
			}
		},
		onShow() {
			this.keyword = uni.getStorageSync("imeiCode");
			if (this.connectState == true) {
				this.getBluetoothDevices();
			} else {
				this.savelist = this.savelist.filter(v => {
					v.isConnect = '0';
					if (that.connectDev && v.deviceId == that.connectDev.deviceId) v.isConnect = '1';
					if (v.name && v.deviceId) return v;
				})
			}
		},
		methods: {
			//搜索
			ermScan() {
				var that = this
				uni.scanCode({
					success: (res) => {
						that.keyword = res.result
						that.getBluetoothDevices();
					},
					fail: (err) => {
						console.error('扫码失败：' + err);
					}
				});
			},
			//打开蓝牙
			openBlue() {
				
				var that = this
				if (!that.connectState) {
					
					uni.showLoading({
						title: "链接中...",
						icon: "none"
					})
					uni.authorize({
						scope: 'scope.bluetooth',
						success: () => {
							uni.openBluetoothAdapter({
								success: (res) => {
									uni.hideLoading();
									that.$store.commit('setConnectState', true);
									that.getBluetoothAdapterState();
								},
								fail: (res) => {
									uni.hideLoading();
									uni.showToast({
										title: "蓝牙适配器打开失败",
										icon: "none"
									})
								}
							});
						},
						fail: () => {
							uni.hideLoading();
							uni.showModal({
								title: '提示',
								content: '需要使用蓝牙功能，请授权使用',
								showCancel: false,
								success: () => {
									uni.openSetting();
								}
							})
						}
					})
				} else {
					that.blist = [];
					that.savelist = [];
					closeBlueAdapter();
				}
			},
			//搜索蓝牙
			getBluetoothAdapterState() {
				var that = this;
				that.blist = [];
				uni.getBluetoothAdapterState({
					success: function(res) {
						if (!res.discovering) {
							that.startBluetoothDevicesDiscovery();
						}
						if (!res.available) {
							uni.showModal({
								title: '提示',
								content: '当前蓝牙适配器不可用',
								confirmColor: '#00b6b5',
								showCancel: false,
								success(res) {}
							})
						}
					},
					fail: function(res) {
						uni.showModal({
							title: '提示',
							content: '适配蓝牙失败',
							confirmColor: '#00b6b5',
							showCancel: false,
							success(res) {}
						})
					}
				});
			},
			//搜索蓝牙
			startBluetoothDevicesDiscovery() {
				var that = this;
				that.isSearch = true
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: false,
					success: function(res) {
						setTimeout(() => {
							that.isSearch = false
							that.lanya5()
						}, 5000)
						that.onBluetoothDeviceFound();
					},
					fail: function(res) {
						that.isSearch = false
						uni.showModal({
							title: '提示',
							content: '搜索蓝牙设备失败'
						})
					}
				})
			},
			//获取所有已发现的设备
			getBluetoothDevices() {
			    var that = this;
				that.savelist = [];

				let islist = uni.getStorageSync("connectDevList")?uni.getStorageSync("connectDevList"):[]
				that.savelist = islist.filter(v => {
					v.isConnect = '0';
					if (that.connectDev && v.deviceId == that.connectDev.deviceId) v.isConnect = '1';
					if (v.name && v.deviceId) return v;
				})
				
			    uni.getBluetoothDevices({
			        success(res){
						res.devices.filter(v => {
							if (!that.blist.find(v2 => v2.deviceId == v.deviceId)) {
								if (v.name.toLowerCase() == that.keyword.toLowerCase()) that.blist.push(v);
							}
						})
			        }
			    })
			},
			// 获取所有已发现的设备
			onBluetoothDeviceFound() {
				var that = this;
				that.savelist = [];
				
				let islist = uni.getStorageSync("connectDevList")?uni.getStorageSync("connectDevList"):[]
				that.savelist = islist.filter(v => {
					v.isConnect = '0';
					if (that.connectDev && v.deviceId == that.connectDev.deviceId) v.isConnect = '1';
					if (v.name && v.deviceId) return v;
				})
				
				uni.onBluetoothDeviceFound((res) => {
					res.devices.filter(v => {
						//判断blist中如果没有就添加
						if (!that.blist.find(v2 => v2.deviceId == v.deviceId)) {
							if (v.name.toLowerCase() == that.keyword.toLowerCase()) that.blist.push(v);
						}
						
					})
				})
			},

			//停止搜索周边设备
			lanya5() {
				uni.getBluetoothAdapterState({
					success: function(res) {
						if (res.discovering) {
							uni.stopBluetoothDevicesDiscovery({
								success: function(res) {
									console.log("蓝牙停止搜索")
								}
							})
						}
					}
				})
			},
			//关闭蓝牙
			closeBluetoothAdapter() {
				var that = this
				uni.closeBluetoothAdapter({
					complete() {}
				})
			},
			delOld(index){
				
				var that = this;
				uni.showModal({
					title: '提示',
					content: '确定要删除该工牌吗?',
					success(res) {
						if (res.confirm) {
							let item = that.savelist[index];
							if (item.isConnect == 1) {
								uni.setStorageSync("lyDetail", item)
								uni.showToast({
									title: '该工牌蓝牙已连接,请先进入"蓝牙详情"页面断开蓝牙',
									duration: 3000,
									icon: "none",
								})
								setTimeout(() => {
									uni.navigateTo({
										url: '/pages/bluetooth/detail'
									})
								}, 3000)
								return
							}
							
							that.savelist.splice(index,1);
							uni.setStorageSync("connectDevList",that.savelist);
						}
					}
				})
			},
			//去详情页
			goDetail(item) {
				uni.setStorageSync("lyDetail", item)
				uni.navigateTo({
					url: "/pages/bluetooth/detail"
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.bt {
		background-color: #F1F2F4;
		min-height: 100vh;
		width: 100%;
		box-sizing: border-box;
		padding: 40rpx 28rpx;

		.bt-t1 {
			font-weight: 400;
			font-size: 26rpx;
			color: #666666;
			margin-bottom: 20rpx;
		}

		.bt-c1 {
			height: 88rpx;
			background: #FFFFFF;
			border-radius: 12rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 28rpx;
			color: #333333;
			box-sizing: border-box;
			padding: 0 28rpx;
		}

		.bt-sw {
			width: 60rpx;
			height: 36rpx;
			background: #D8D8D8;
			box-shadow: 0rpx 2rpx 4rpx 0rpx rgba(9, 23, 44, 0.3);
			border-radius: 18rpx;
			display: flex;
			align-items: center;
			transition: all 0.3s linear;
			position: relative;
		}

		.bt-sw::after {
			content: " ";
			position: absolute;
			left: 8rpx;
			width: 20rpx;
			height: 20rpx;
			background: #FFFFFF;
			border-radius: 16rpx;
			transition: all 0.3s linear;
		}

		.bt-sw-ac {
			background: #2671E2;
		}

		.bt-sw-ac::after {
			left: 32rpx;
		}

		.bt-t2 {
			font-size: 30rpx;
			color: #999999;
			margin-top: 20rpx;
			line-height: 1.6;
		}

		.bt-t3 {
			margin-top: 60rpx;
			font-size: 26rpx;
			color: #666666;
		}

		.bt-input1 {
			width: 100%;
			background: #FFFFFF;
			border-radius: 12rpx;
			box-sizing: border-box;
			padding: 20rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-top: 20rpx;

			&-c {
				width: 100%;
				height: 66rpx;
				background: #F1F2F4;
				border-radius: 8rpx;
				display: flex;
				align-items: center;
				box-sizing: border-box;
				padding: 0 20rpx;

				image {
					width: 36rpx;
					height: 36rpx;
					margin-right: 10rpx;
					flex-shrink: 0;
				}

				input {
					width: 100%;
					font-weight: 400;
					font-size: 26rpx;
					color: #333;
				}
			}

			.scan {
				width: 30rpx;
				height: 30rpx;
				margin-left: 28rpx;
				flex-shrink: 0;
			}
		}

		.bt-c2 {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-top: 60rpx;

			.bt-c2-l {
				font-weight: 400;
				font-size: 26rpx;
				color: #666666;
				transform: translateY(-2rpx);
			}

			.bt-c2-r {
				width: 32rpx;
				height: 32rpx;
			}

			.bt-c2-r-ani {
				animation: spin 2.5s linear infinite;
			}

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

				100% {
					transform: rotate(360deg);
				}
			}
		}

		.bt-c3 {
			box-sizing: border-box;
			padding: 32rpx;
			background: #FFFFFF;
			border-radius: 12rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-top: 20rpx;

			.bt-c3-l {
				display: flex;
				align-items: center;
				font-weight: 400;
				font-size: 28rpx;
				color: #333333;

				image {
					height: 36rpx;
					margin-left: 12rpx;
					flex-shrink: 0;
				}
			}

			image {
				width: 12rpx;
				height: 28rpx;
				margin-left: 20rpx;
				flex-shrink: 0;
			}
		}

	}
</style>