<template>
	<view>
		<HomePage v-if="selectIndex === 'homePage'" tarbar-type="index" />
		<PersonCenter v-else-if="selectIndex === 'personCenter'" />
		<WorkBranch v-else-if="selectIndex === 'workbranch'" />
		<view class="tab_bar" :style="[isPad?'height: 100px;':'height: 3.5rem;']">
			<view class="tabbarBox">
				<view v-for="(item,index) in tabBarList" :key="index" class="handleBox"
					@click="goPages(item.pageIndex)">
					<view class="menuBox">
						<view class="menuIcon" :style="[isPad?'margin-top: 8px;':'']">
							<image v-if="item.pageIndex!=selectIndex" class="img" :src="item.iconPath" />
							<image v-else class="img" :src="item.selectIconPath" />
						</view>
						<view class="menuName" :style="[isPad?'margin-top: 8px;':'']">
							<text class="Text"
								:style="{ color: item.pageIndex!=selectIndex? 'gray': 'black' }">{{ item.tabbarName }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import HomePage from './homePage.vue'
	import PersonCenter from './personCenter.vue'
	import WorkBranch from './workbranch.vue'
	import {
		getFileStorage
	} from '@/unit/fileStorage.js'
	import Bluetooth from '@/unit/print/bluetooth.js'
	import {
		hideBoard
	} from '@/unit/default'

	const bluetooth = new Bluetooth()
	export default {
		components: {
			HomePage,
			PersonCenter,
			WorkBranch
		},
		data() {
			return {
				selectIndex: 'homePage',
				tabBarList: [{
						'flag': 'icon',
						'pageIndex': 'homePage',
						'iconPath': '/static/menu_imgs/home-default.png',
						'selectIconPath': '/static/menu_imgs/home.png',
						'tabbarName': '首页'
					},
					{
						'flag': 'icon',
						'pageIndex': 'workbranch',
						'iconPath': '/static/menu_imgs/workbranch-default.png',
						'selectIconPath': '/static/menu_imgs/workbranch.png',
						'tabbarName': '工作台'
					},
					{
						'flag': 'icon',
						'pageIndex': 'personCenter',
						'iconPath': '/static/menu_imgs/person-default.png',
						'selectIconPath': '/static/menu_imgs/person.png',
						'tabbarName': '个人中心'
					}
				]
			}
		},
		onShow() {
		},
		async beforeCreate() {
			// #ifdef APP-PLUS
			await bluetooth.openBluetoothAdapter()
			// #endif
		},
		// uniapp子组件不支持应用生命周期，所以只能用vue生命周期
		mounted() {
			const _this = this
			// 隐藏原生tarbar (这里因为用自定义tarbar跳转时闪白屏，所以这里用一种特殊的方式)
			uni.hideTabBar()
			// 蓝牙自连
			// #ifdef APP-PLUS
			getFileStorage('bluetoothConfig.txt')
				.then(async data => {
					if (data != null) {
						const blueConfig = JSON.parse(data)
						const isConfigNull = Object.keys(blueConfig).every(ret => ![null, ''].includes(blueConfig[
							ret]))
						if (isConfigNull) {
							bluetooth.serviceName = blueConfig.serviceName
							bluetooth.deviceId = blueConfig.deviceId
							bluetooth.serviceId = blueConfig.serviceId
							bluetooth.writeId = blueConfig.writeId
							bluetooth.notifyId = blueConfig.notifyId
							bluetooth.isOpenBle = blueConfig.isOpenBle
							uni.setStorageSync('bluetoothConfig', JSON.stringify(bluetooth))

							try {
								await _this.createBLEConnection()
								setTimeout(async () => {
									await _this.getBLEDeviceCharacteristics()
								}, 4500)
							} catch (e) {
								// TODO handle the exception
							}
						}
					}
				})
				.catch((e) => {
					uni.showToast({
						title: '获取蓝牙配置文件失败, 请检查本地文件是否丢失',
						duration: 2000,
						icon: 'none'
					})
				})
			// #endif
		},
		methods: {
			// 进入tabble页
			goPages(pageIndex) {
				this.selectIndex = pageIndex
			},
			createBLEConnection() {
				plus.bluetooth.createBLEConnection({
					deviceId: bluetooth.deviceId,
					success: (res) => {
						// console.log("res:createBLEConnection " + JSON.stringify(res));
						// resolve(res)
					},
					fail: err => {
						uni.hideLoading()
						if (err?.code === -1) {
							// {"code":-1,"message":"already connect"}
							uni.showToast({
								title: `此设备已连接，请勿重复操作` + JSON.stringify(err),
								duration: 2000,
								icon: 'none'
							})
						} else {
							uni.showToast({
								title: `连接蓝牙设备失败` + JSON.stringify(err),
								duration: 2000,
								icon: 'none'
							})
						}
					}
				})
			},
			getBLEDeviceCharacteristics() {
				plus.bluetooth.getBLEDeviceCharacteristics({
					deviceId: bluetooth.deviceId,
					serviceId: bluetooth.serviceId,
					success: res => {
						// 解决安卓低功耗蓝牙写入code 10007问题
						uni.setBLEMTU({
							deviceId: bluetooth.deviceId,
							mtu: 180,
							success(res) {
								console.log('设置最大值成功')
							}

						})

						// const result = {
						//   'notifyId': bluetooth.notifyId,
						//   'writeId': bluetooth.writeId
						// }
						const notifyifIsItEmpty = ['', null, undefined, NaN].includes(bluetooth.notifyId)
						const writeIdIsItEmpty = ['', null, undefined, NaN].includes(bluetooth.writeId)

						if (notifyifIsItEmpty || writeIdIsItEmpty) {
							uni.showToast({
								title: `此服务不可用，请选择其它服务`,
								duration: 2000,
								icon: 'none'
							})
						} else {
							// this.showToast(`获取服务中所有特征值OK,${JSON.stringify(result)}`);
							// uni.showToast({
							// 	title: `蓝牙打印自动重连成功`,
							// 	duration: 2000,
							// 	icon: "none"
							// });
						}
					},
					fail: err => {
						uni.showToast({
							title: `getBLEDeviceCharacteristics` + JSON.stringify(err),
							duration: 2000,
							icon: 'none'
						})
					}
				})
			}
		}
	}
</script>
<style lang="scss">
	.tab_bar {
		width: 100vw;
		position: fixed;
		bottom: 0rpx;
		box-shadow: 0px 10px 15px 3px gray;
		border-radius: 15px 15px 0 0;
		background: #ffffff;
		z-index: 99999;

		.tabbarBox {
			display: flex;
			justify-content: space-evenly;

			.handleBox {
				width: 20vw;
				height: 100%;

				.menuBox {
					padding: 0rpx 20rpx;
					width: 120rpx;
					height: 100%;
					text-align: center;

					.menuIcon {
						height: 30px;
						display: flex;
						align-items: center;
						justify-content: center;

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

	.Text {
		font-size: 25rpx;
	}
</style>