<template>
	<view class="">
		<view class="bluetooth_container">
			<view class="title">
				已配对设备
			</view>
			<view class="matched_list" v-if="matchedList && matchedList.length">
				<view class="flex" v-for="(item, index) in matchedList" :key="item.deviceId" @longpress="showModal2(item.deviceId)">
					<image class="img" src="/static/print.png" mode=""></image>
					<text class="name">{{item.localName ? item.localName : item.name ? item.name : '--'}}</text>
					<text class="link linked" @click="showModal" v-if="linkedDeviceId === item.deviceId">已连接</text>
					<block v-else>
						<image v-if="selectedDeviceId==item.deviceId && isConnectting" class="load_img" src="/static/loadding.gif" mode=""></image>
						<text v-else class="link unlink" @click="connectHandler(item)">未连接</text>
					</block>
				</view>
			</view>
			<view class="empty_box" v-else>
				<u-empty mode="search" text="暂无配对设备,快快添加吧~"></u-empty>
			</view>
			<view class="block"></view>
			<view class="title search_title">
				<text>扫描可用设备</text>
				<view class="stop" v-if="isSearching" @click="stopSearch">
					<text>停止</text>
				</view>
				<view class="img_box" v-else @click="startSearch">
					<image class="img img1" src="/static/refresh.png" mode=""></image>
				</view>
				<view class="load_box" v-if="isSearching">
					<image class="load_img" src="/static/loadding.gif" mode=""></image>
				</view>
			</view>
			<view class="list">
				<view class="flex" v-for="(item, index) in deviceList" :key="index">
					<image class="img img2" src="/static/print.png" mode=""></image>
					<text class="name">{{item.localName ? item.localName : item.name ? item.name : '--'}}</text>
					<image v-if="selectedDeviceId==item.deviceId && isConnectting" class="load_img" src="/static/loadding.gif" mode=""></image>
					<text v-else class="link" @click="connectHandler(item,index)">连接</text>
				</view>
			</view>
		</view>
		
		<u-modal v-model="modalShow" show-cancel-button content="是否断开连接？" @confirm="closeConnect"></u-modal>
		<u-modal v-model="modalShow2" show-cancel-button content="是否忽略此设备？" @confirm="deleteDevice"></u-modal>

	</view>
</template>

<script>
	import B12s from '@/common/b12s.js';
	const b12s = new B12s();
	export default {
		data() {
			return {
				// 蓝牙相关；
				matchedList: [], //已配对的列表；
				deviceList: [], //搜索到的设备列表；
				initCode: 0, //蓝牙初始化结果；0：初始化中，1-成功；2-失败；
				selectedDeviceId: '', //当前操作的蓝牙设备id； 
				isConnectting: false, //蓝牙正在连接中；
				linkedDeviceId: '', //已连接的蓝牙mac地址；
				isSearching: false, //是否正在搜索蓝牙设备；

				b12s: null, //蓝牙工具；
			}
		},
		async onLoad(options) {
			this.initBluetooth();
		},
		async onUnload() {
			this.stopSearch();
			b12s.closeBLE(this.linkedDeviceId);
			b12s.closeAdapter();
		},
		methods: {
			// 初始化蓝牙；
			async initBluetooth() {
				this.getMatchedList();
				await b12s.init(this.onConnectChange);
				this.autoConnect();
			},
			// 如果有配对历史，自动连接最后一个；
			autoConnect() {
				let length = this.matchedList.length
				if (length <= 0) return;
				let item = this.matchedList[length - 1];
				this.connectHandler(item);
			},
			// 开始搜索蓝牙；
			async startSearch() {
				await b12s.startSearch(this.getDeviceList);
				this.isSearching = true;
			},
			// 停止搜索
			async stopSearch() {
				await b12s.stopSearch();
				this.isSearching = false;
			},
			// 获取历史配对列表；
			getMatchedList() {
				let list = uni.getStorageSync('__bluetooth_list_');
				if (list) {
					this.matchedList = list;
				}
				console.log(this.matchedList);
			},
			// 获取可用设备列表；
			getDeviceList(devices) {
				for (let i = 0; i < devices.length; i++) {
					let name = devices[i].name || devices[i].localName;
					if (name) {
						let dLIndex = this.deviceList.findIndex(item => item.deviceId === devices[i].deviceId);
						let mLIndex = this.matchedList.findIndex(item => item.deviceId === devices[i].deviceId);
						if (dLIndex < 0 && mLIndex < 0) {
							this.deviceList.push({
								name: name,
								deviceId: devices[i].deviceId
							})
						}
					}
				}
			},
			// 点击连接；
			async connectHandler(item, index = -1) {
				this.stopSearch();
				await b12s.closeBLE(this.linkedDeviceId)
				this.selectedDeviceId = item.deviceId;
				this.isConnectting = true;
				await b12s.connectBLE(item.deviceId).catch(err => {
					this.isConnectting = false;
				});
				// this.linkedDeviceId = item.deviceId;
				this.isConnectting = false;
				let indexRes = this.matchedList.findIndex(itm => itm.deviceId === item.deviceId);
				if (indexRes < 0) {
					this.matchedList.push(item);
					index !== -1 && this.deviceList.splice(index, 1);
					this.saveStorage()
				}
			},
			// 断开连接
			closeConnect() {
				b12s.closeBLE(this.linkedDeviceId);
				this.modalShow = false;
			},
			// 监听蓝牙连接状态；
			onConnectChange(res) {
				if (res.connected) {
					// this.$u.toast('蓝牙已连接');
					this.linkedDeviceId = res.deviceId;
				} else {
					// this.$u.toast('蓝牙已断开');
					this.linkedDeviceId = '';
				}
			},
			// 删除已缓存设备；
			deleteDevice() {
				this.matchedList = this.matchedList.filter(item => item.deviceId !== this.selectedDeviceId);
				this.saveStorage()
			},
			// 缓存已配对蓝牙；
			saveStorage() {
				uni.setStorageSync('__bluetooth_list_', this.matchedList)
			}
		}
	}
</script>

<style lang="scss" scoped>

	.bluetooth_container {
		padding: 30rpx;

		.load_img {
			width: 40rpx;
			height: 40rpx;
		}

		.title {
			font-size: 34rpx;
			font-weight: bold;

			.img {
				margin-left: 20rpx;
				vertical-align: middle;
				width: 36rpx;
				height: 36rpx;
			}
		}

		.search_title {
			display: flex;
			justify-content: space-between;
			margin-top: 60rpx;

			.img_box {
				flex: 1;
			}

			.load_img {
				width: 40rpx;
				height: 40rpx;
			}

			.stop {
				flex: 1;
				margin-left: 30rpx;

				text {
					font-size: 24rpx;
					font-weight: normal;
					background-color: #fa3534;
					color: #ffffff;
					padding: 10rpx 20rpx;
					border-radius: 30rpx;
				}
			}
		}

		.matched_list {
			// padding: 30rpx 0;

			.flex {
				display: flex;
				margin: 30rpx 0;
				justify-content: space-between;
				align-items: center;

				.img {
					width: 40rpx;
					height: 40rpx;
				}

				.name {
					flex: 1;
					margin-left: 40rpx;
				}

				.link {
					padding: 10rpx 40rpx;
					background-color: #F2F2F2;
					border-radius: 40rpx;
					font-size: 28rpx;
				}

				.unlink {
					color: #606266;
				}

				.linked {
					color: #19be6b;
				}
			}
		}

		.empty_box {
			padding: 90rpx 0;
		}

		.list {
			.flex {
				display: flex;
				margin: 30rpx 0;
				justify-content: space-between;
				align-items: center;

				.img {
					width: 40rpx;
					height: 40rpx;
				}

				.name {
					flex: 1;
					margin-left: 40rpx;
				}

				.link {
					padding: 10rpx 40rpx;
					background-color: #F2F2F2;
					border-radius: 40rpx;
					color: #2979ff;
					font-size: 28rpx;
				}
			}
		}

		.btns {
			display: flex;
			justify-content: space-around;
			margin-top: 200rpx;

			.btn {
				margin: 0;
				width: 40%;
			}
		}
	}

</style>
