<template>
	<view class="container">
		<!-- 标题 -->
		<view class="header" :style="{height:(44+statusBarHeight)+'px',paddingTop: statusBarHeight+ 'px'}">
			<text class="title">TyPulse 简单示例</text>
		</view>

		<!-- 状态显示 -->
		<view class="status-section">
			<view class="status-item">
				<text class="status-label">插件状态:</text>
				<text
					:class="['status-value', initStatus ? 'success' : 'error']">{{ initStatus ? '已初始化' : '未初始化' }}</text>
			</view>
			<view class="status-item">
				<text class="status-label">设备状态:</text>
				<text
					:class="['status-value', deviceConnected ? 'success' : 'error']">{{ deviceConnected ? '已连接' : '未连接' }}</text>
			</view>
			<view class="status-item">
				<text class="status-label">测量状态:</text>
				<text :class="['status-value', measuring ? 'warning' : 'normal']">{{ measuring ? '测量中' : '待机' }}</text>
			</view>
		</view>

		<!-- 连接状态指示器 -->
		<view class="connection-status" v-if="deviceInfo">
			<view class="status-indicator connected"></view>
			<text class="status-text">设备已连接</text>
		</view>
		
		<!-- 设备信息 -->
		<view v-if="deviceInfo" class="device-section">
			<text class="section-title">设备信息</text>
			<text class="device-battery">设备id: {{ deviceInfo.deviceId }}</text>
			<text class="device-name">设备名称:{{ deviceInfo.deviceName }}</text>
			<text class="device-battery">电量: {{ deviceInfo.battery }}%</text>
		</view>

		</view>

		<!-- 操作按钮 -->
		<view class="action-section">
			<view @click="toMeasure" class="btn btn-primary">
				{{ deviceInfo ? '继续测脉' : '去测脉' }}
			</view>
			<view v-if="deviceInfo" @click="disconnectDevice" class="btn btn-secondary">断开设备</view>
			<view @click="toMeasurePortrait" class="btn btn-secondary">去测脉(强制竖屏)</view>
			<view @click="toMeasureLandscape" class="btn btn-secondary">去测脉(强制横屏)</view>
			<view @click="toMeasureAuto" class="btn btn-secondary">去测脉(自动方向)</view>
			<view @click="toTongue" class="btn btn-primary">舌诊示例</view>
			<view @click="toCamera" class="btn btn-primary">摄像头调试</view>
			<view @click="toSmdtDevice" class="btn btn-primary">平板设备</view>

			<!-- <view @click="toCamera1" class="btn btn-primary">摄像头自动变焦</view> -->
			<!-- <view @click="startMeasure" :disabled="!deviceConnected || measuring" class="btn btn-success">开始测量</view>
      <view @click="stopMeasure" :disabled="!measuring" class="btn btn-danger">停止测量</view> -->
		</view>

		<!-- 测量进度 -->
		<view v-if="measuring" class="progress-section">
			<text class="progress-text">测量进度: {{ measureProgress }}%</text>
			<view class="progress-bar">
				<view class="progress-fill" :style="{ width: measureProgress + '%' }"></view>
			</view>
			<text class="stage-text">{{ currentStage }}</text>
		</view>

		<!-- 测量结果 -->
		<view v-if="lastResult" class="result-section">
			<text class="section-title">最新测量结果</text>
			<view class="result-item">
				<text class="result-label">心率:</text>
				<text class="result-value">{{ lastResult.heartRate }} bpm</text>
			</view>
			<view class="result-item">
				<text class="result-label">血压:</text>
				<text class="result-value">{{ lastResult.bloodPressure.systolic }}/{{ lastResult.bloodPressure.diastolic }}
					mmHg</text>
			</view>
			<view class="result-item">
				<text class="result-label">测量时间:</text>
				<text class="result-value">{{ lastResult.measureTime }}</text>
			</view>
		</view>

		<!-- 简单日志 -->
		<view class="log-section">
			<text class="section-title">操作日志</text>
			<scroll-view class="log-list" scroll-y="true">
				<view v-for="(log, index) in logs" :key="index" class="log-item">
					<text class="log-text">{{ log }}</text>
				</view>
			</scroll-view>
		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 插件实例
				tyPulse: null,
				// 状态
				initStatus: false,
				deviceConnected: false,
				isConnecting: false, // 防止重复连接的标志
				measuring: false,
				// 设备信息
				deviceInfo: null,
				// 测量相关
				measureProgress: 0,
				currentStage: '待机',
				lastResult: null,
				appId: "nehijR6y",
				appSecret: "f740435d1b84b9944a52f064dd1ecf6e8a76f546",
				uid: "userid000067",
				// 日志
				logs: [],
				devices: [],
				statusBarHeight: uni.getSystemInfoSync().statusBarHeight,
				// 重连相关
				reconnectAttempts: 0,
				// 连接状态检查标志（防止重复执行和白屏）
				isCheckingConnection: false,
			}
		},
		onLoad() {
			this.addLog('页面加载完成');
			this.initPlugin();
		},
		onShow() {
			this.addLog('页面显示');
			// 页面显示时检查连接状态
			if (this.tyPulse && this.initStatus) {
				this.checkAndRestoreConnection();
			}
		},
		onHide() {
			this.addLog('页面隐藏，保持连接状态');
			// 页面隐藏时不主动断开连接，只记录状态
			// 这样可以在页面重新显示时恢复连接
		},
		onUnload() {
			this.addLog('页面卸载，清理连接状态');
			// 页面卸载时清理连接状态
			if (this.tyPulse) {
				// 不再主动断开连接，保持蓝牙连接状态
				this.addLog('页面卸载，保持蓝牙连接');
			}
		},
		methods: {
					// 添加日志
					addLog(message) {
						const time = new Date().toLocaleTimeString();
						this.logs.unshift(`[${time}] ${message}`);
						if (this.logs.length > 20) {
							this.logs.pop();
						}
					},

					// 检查并恢复连接状态（合并后的优化版本）
					checkAndRestoreConnection() {
						// 添加状态检查，防止重复执行
						if (this.isCheckingConnection) {
							this.addLog('连接状态检查正在进行中，跳过重复检查');
							return;
						}
						
						this.isCheckingConnection = true;
						this.addLog('开始检查连接状态...');
						
						// 延迟执行，避免页面切换时的竞争条件
						setTimeout(() => {
							this.performConnectionCheck();
						}, 500);
					},
					
					// 执行连接检查的核心逻辑
					async performConnectionCheck() {
						try {
							if (!this.tyPulse || !this.initStatus) {
								this.addLog('插件未初始化，跳过连接检查');
								return;
							}
							
							// 设置超时保护，防止长时间阻塞
							const timeoutPromise = new Promise((resolve) => {
								setTimeout(() => {
									resolve({ success: false, error: '连接状态检查超时' });
								}, 5000); // 5秒超时
							});
							
							// 优先使用智能连接
							if (this.tyPulse.smartConnect) {
								const smartPromise = new Promise((resolve) => {
									this.tyPulse.smartConnect(resolve);
								});
								
								const result = await Promise.race([smartPromise, timeoutPromise]);
								
								this.addLog('智能连接结果: ' + JSON.stringify(result));
								
								if (result.success) {
									if (result.isAlreadyConnected) {
										this.addLog('设备已连接');
										this.deviceConnected = true;
										// 异步获取设备信息
										setTimeout(() => {
											this.getDeviceInfo();
										}, 50);
										return;
									} else if (result.isAutoReconnected) {
										this.addLog('自动重连成功');
										this.deviceConnected = true;
										uni.showToast({
											title: '自动重连成功',
											icon: 'success'
										});
										return;
									}
								} else {
									if (result.needScan) {
										this.addLog('需要重新扫描连接，请手动点击连接按钮');
									} else {
										this.addLog('智能连接失败: ' + (result.error || '未知错误'));
									}
								}
							}
							
							// 如果没有智能连接方法，使用原有的检查方法
							if (this.tyPulse.checkConnectionStatus) {
								const statusPromise = new Promise((resolve) => {
									this.tyPulse.checkConnectionStatus(resolve);
								});
								
								const result = await Promise.race([statusPromise, timeoutPromise]);
								
								this.addLog('连接状态检查结果: ' + JSON.stringify(result));
								
								if (result.success && result.data) {
									if (result.data.isConnected) {
										// 当前已连接
										this.deviceConnected = true;
										this.addLog('检测到已有蓝牙连接，状态已恢复');
										// 异步获取设备信息，不阻塞UI
										setTimeout(() => {
											this.getDeviceInfo();
										}, 50);
									} else {
										this.addLog('当前没有蓝牙连接');
									}
								} else {
									this.addLog('连接状态检查失败: ' + (result.error || '未知错误'));
								}
							} else {
								// 如果没有专门的连接状态检查方法，尝试获取设备信息
								this.addLog('使用设备信息检查连接状态...');
								this.getDeviceInfo();
							}
						} catch (error) {
							this.addLog('连接状态检查异常: ' + error.message);
						} finally {
							this.isCheckingConnection = false;
							this.addLog('连接状态检查完成');
						}
					},

					// 初始化插件
					async initPlugin() {
							try {
								this.addLog('开始初始化插件...');
								// 获取插件实例
								this.tyPulse = uni.requireNativePlugin('TyPulseManager');
								if (!this.tyPulse) {
									throw new Error('无法获取插件实例');
								}


								// 初始化
								await new Promise((resolve, reject) => {
									this.tyPulse.initSDK(this.appId, this.appSecret, this.uid, (
										result) => {
										if (result.success) {
											resolve();
										} else {
											reject(new Error(result.error));
										}
									});
								});

								this.initStatus = true;
								this.addLog('插件初始化成功');
								uni.showToast({
									title: '插件初始化成功',
									icon: 'success'
								});

								// 延迟检查连接状态，确保插件完全初始化
								setTimeout(() => {
									this.checkAndRestoreConnection();
								}, 500);
							} catch (error) {
								this.addLog(`初始化失败: ${error.message}`);
								uni.showToast({
									title: '初始化失败',
									icon: 'error'
								});
							}
					},

					toMeasure() {
						if (!this.initStatus || !this.tyPulse) {
							this.addLog('插件未初始化，无法进行测量');
							uni.showToast({
								title: '插件未初始化',
								icon: 'error'
							});
							return;
						}
						this.addLog('调用原生 toMeasure...');
						this.tyPulse.toMeasure(result => {
							this.addLog('toMeasure 回调: ' + JSON.stringify(result));
							if (result.success) {
								if (result.cmdType == "pulseResult") {
									this.addLog('测量结果:' + JSON.stringify(result));
								}
								if (result.cmdType == "deviceConnect") {
									//获取设备信息
									this.getDeviceInfo();
									this.addLog('回调结果:' + JSON.stringify(result));
								}
							} else {
								this.addLog('测脉操作失败: ' + (result.error || '未知错误'));
							}
						});
					},

					// 设置回调
					setupCallbacks() {
						this.tyPulse.setDeviceCallback((result) => {
							this.addLog('设备状态变更: ' + JSON.stringify(result));
							
							switch (result.status) {
								case 'connected':
									this.deviceConnected = true;
									this.deviceInfo = result.deviceInfo || {};
									this.reconnectAttempts = 0; // 重置重连次数
									uni.showToast({
										title: '设备已连接',
										icon: 'success'
									});
									break;
								case 'disconnected':
									this.deviceConnected = false;
									this.deviceInfo = {};
									uni.showToast({
										title: '设备已断开',
										icon: 'none'
									});
									// 如果是意外断开，可以尝试自动重连
									if (result.isUnexpected) {
										this.addLog('设备意外断开，尝试自动重连...');
										setTimeout(() => {
											this.checkAndRestoreConnection();
										}, 1000);
									}
									break;
								case 'connection_failed':
									this.deviceConnected = false;
									this.deviceInfo = {};
									uni.showToast({
										title: '连接失败',
										icon: 'error'
									});
									break;
							}
						});

						// 测量进度回调
						this.tyPulse.setProgressCallback((progress) => {
							this.measureProgress = progress.percentage;
							this.currentStage = this.getStageText(progress.stage);
						});

						// 测量结果回调
						this.tyPulse.setMeasureCallback((result) => {
							this.measuring = false;
							this.measureProgress = 0;
							this.currentStage = '待机';

							if (result.success) {
								this.lastResult = result.data;
								this.addLog(`测量完成 - 心率: ${result.data.heartRate} bpm`);
								uni.showToast({
									title: '测量完成',
									icon: 'success'
								});
							} else {
								this.addLog(`测量失败: ${result.error}`);
								uni.showToast({
									title: '测量失败',
									icon: 'error'
								});
							}
						});
					},

					// 获取阶段文本
					getStageText(stage) {
							const stageMap = {
								'preparing': '准备中',
								'calibrating': '校准中',
								'measuring': '测量中',
								'analyzing': '分析中',
								'completed': '完成'
							};
							return stageMap[stage] || '未知阶段';
					},

					// 获取设备信息
					getDeviceInfo() {
						if (!this.tyPulse || !this.initStatus) {
							this.addLog('插件未初始化，无法获取设备信息');
							return;
						}
						
						try {
							this.tyPulse.getDeviceInfo((result) => {
								if (result.success) {
									this.deviceInfo = result.data;
									this.deviceConnected = true; // 更新设备连接状态
									this.addLog(`设备信息: ${JSON.stringify(result.data)}`);
									uni.showToast({
										title: '设备已连接',
										icon: 'success'
									});
								} else {
									this.addLog(`获取设备信息失败: ${result.error}`);
									this.deviceInfo = null;
									this.deviceConnected = false; // 更新设备连接状态
								}
							});
						} catch (error) {
							this.addLog(`获取设备信息异常: ${error.message}`);
							this.deviceInfo = null;
						}
					},

					// 断开设备连接
					disconnectDevice() {
						if (!this.tyPulse || !this.initStatus) {
							this.addLog('插件未初始化，无法断开设备');
							return;
						}
						
						try {
							this.tyPulse.disconnectDevice((result) => {
								if (result.success) {
									this.deviceInfo = null;
									this.deviceConnected = false; // 更新设备连接状态
									this.addLog('设备已断开连接');
									uni.showToast({
										title: '设备已断开',
										icon: 'success'
									});
								} else {
									this.addLog(`断开设备失败: ${result.error}`);
								}
							});
						} catch (error) {
							this.addLog(`断开设备异常: ${error.message}`);
						}
					},

					// 安全的连接状态检查方法（防止白屏）
					async checkAndRestoreConnectionSafely() {
						try {
							// 添加状态检查，防止重复执行
							if (this.isCheckingConnection) {
								this.addLog('连接状态检查正在进行中，跳过重复检查');
								return;
							}
							
							this.isCheckingConnection = true;
							this.addLog('安全检查蓝牙连接状态...');
							
							// 设置超时保护，防止长时间阻塞
							const timeoutPromise = new Promise((resolve) => {
								setTimeout(() => {
									resolve({ success: false, error: '连接状态检查超时' });
								}, 5000); // 5秒超时
							});
							
							// 使用新的智能连接方法
							if (this.tyPulse.smartConnect) {
								const smartPromise = new Promise((resolve) => {
									this.tyPulse.smartConnect(resolve);
								});
								
								const result = await Promise.race([smartPromise, timeoutPromise]);
								
								this.addLog('智能连接结果: ' + JSON.stringify(result));
								
								if (result.success) {
									if (result.isAlreadyConnected) {
										this.addLog('设备已连接');
										this.deviceConnected = true;
										// 异步获取设备信息
										setTimeout(() => {
											this.getDeviceInfo();
										}, 50);
									} else if (result.isAutoReconnected) {
										this.addLog('自动重连成功');
										this.deviceConnected = true;
										uni.showToast({
											title: '自动重连成功',
											icon: 'success'
										});
									}
								} else {
									if (result.needScan) {
										this.addLog('需要重新扫描连接，请手动点击连接按钮');
										// 不自动触发任何连接操作，完全由用户手动控制
									} else {
										this.addLog('智能连接失败: ' + (result.error || '未知错误'));
									}
								}
							} else {
								// 如果没有智能连接方法，使用原有的检查方法
								if (this.tyPulse.checkConnectionStatus) {
									const statusPromise = new Promise((resolve) => {
										this.tyPulse.checkConnectionStatus(resolve);
									});
									
									const result = await Promise.race([statusPromise, timeoutPromise]);
									
									this.addLog('连接状态检查结果: ' + JSON.stringify(result));
									
									if (result.success && result.data) {
										if (result.data.isConnected) {
											// 当前已连接
											this.deviceConnected = true;
											this.addLog('检测到已有蓝牙连接，状态已恢复');
											// 异步获取设备信息，不阻塞UI
											setTimeout(() => {
												this.getDeviceInfo();
											}, 50);
										} else {
											// 没有连接，不做任何自动操作
											this.addLog('当前没有蓝牙连接，请手动点击连接按钮');
										}
									} else {
										this.addLog('连接状态检查失败: ' + (result.error || '未知错误'));
									}
								} else {
									this.addLog('没有可用的连接状态检查方法');
								}
							}
						} catch (error) {
							this.addLog('连接状态检查异常: ' + error.message);
						} finally {
							this.isCheckingConnection = false;
						}
					},



					// 自动重连
					async autoReconnect() {
						try {
							this.addLog('开始自动重连...');
							
							// 优先使用智能连接
							if (this.tyPulse.smartConnect) {
								const result = await new Promise((resolve) => {
									this.tyPulse.smartConnect(resolve);
								});
								
								this.addLog('智能连接结果: ' + JSON.stringify(result));
								
								if (result.success) {
									if (result.isAlreadyConnected) {
										this.deviceConnected = true;
										this.addLog('设备已连接');
										this.getDeviceInfo();
									} else if (result.isAutoReconnected) {
										this.deviceConnected = true;
										this.addLog('自动重连成功');
										uni.showToast({
											title: '自动重连成功',
											icon: 'success'
										});
										this.getDeviceInfo();
									}
									return;
								}
							}
							
							// 如果智能连接失败，尝试连接已保存的设备
							if (this.tyPulse.connectToSavedDevice) {
								const savedResult = await new Promise((resolve) => {
									this.tyPulse.connectToSavedDevice(resolve);
								});
								
								this.addLog('连接已保存设备结果: ' + JSON.stringify(savedResult));
								
								if (savedResult.success) {
									this.deviceConnected = true;
									this.addLog('连接已保存设备成功');
									uni.showToast({
										title: '连接已保存设备成功',
										icon: 'success'
									});
									this.getDeviceInfo();
								} else {
									this.addLog('连接已保存设备失败: ' + (savedResult.error || '未知错误'));
								}
							}
						} catch (error) {
							this.addLog(`自动重连失败: ${error.message}`);
						}
					},

						// 连接设备
					async connectDevice() {
						try {
							// 防止重复连接
							if (this.isConnecting) {
								this.addLog('连接正在进行中，请稍候...');
								return;
							}
							
							// 先尝试智能连接
							if (this.tyPulse.smartConnect) {
								this.isConnecting = true;
								this.addLog('尝试智能连接...');
								
								uni.showLoading({
									title: '连接中...'
								});
								
								const smartResult = await new Promise((resolve) => {
									this.tyPulse.smartConnect(resolve);
								});
								
								uni.hideLoading();
								
								if (smartResult.success) {
									if (smartResult.isAlreadyConnected) {
										this.deviceConnected = true;
										this.addLog('设备已连接');
										uni.showToast({
											title: '设备已连接',
											icon: 'success'
										});
										this.getDeviceInfo();
										return;
									} else if (smartResult.isAutoReconnected) {
										this.deviceConnected = true;
										this.addLog('自动重连成功');
										uni.showToast({
											title: '自动重连成功',
											icon: 'success'
										});
										this.getDeviceInfo();
										return;
									}
								}
							}
							
							// 如果智能连接失败或不可用，使用普通连接
							this.isConnecting = true;
							this.addLog('开始连接设备...');
							
							uni.showLoading({
								title: '连接中...'
							});

							// 直接弹出设备选择窗口，让用户选择设备
							this.addLog('弹出设备选择窗口...');
							const scanResult = await new Promise((resolve) => {
								this.tyPulse.scanAndConnect(resolve);
							});

							uni.hideLoading();

							if (scanResult.success) {
								this.addLog('设备选择窗口已启动，等待用户选择设备...');
								// 注意：实际的连接成功会通过setDeviceCallback中的'connected'事件通知
								// 这里不需要设置deviceConnected = true，等待回调处理
							} else {
								this.addLog(`连接失败: ${scanResult.error}`);
								uni.showToast({
									title: '连接失败',
									icon: 'error'
								});
							}
						} catch (error) {
							uni.hideLoading();
							this.addLog(`连接异常: ${error.message}`);
							uni.showToast({
								title: '连接异常',
								icon: 'error'
							});
						} finally {
							this.isConnecting = false;
						}
					},

					// 开始测量
					async startMeasure() {
							try {
								this.measuring = true;
								this.measureProgress = 0;
								this.currentStage = '开始测量';
								this.addLog('开始测量...');
								this.tyPulse.startMeasure((result) => {
									if (result.success) {
										this.addLog('测量启动成功');
									} else {
										this.measuring = false;
										this.addLog(`测量失败: ${result.error}`);
									}
								});

							} catch (error) {
								this.measuring = false;
								this.addLog(`开始测量失败: ${error.message}`);
							}
					},

					// 停止测量
					async stopMeasure() {
							try {
								this.addLog('停止测量...');
								this.tyPulse.stopMeasure((result) => {
									this.measuring = false;
									this.measureProgress = 0;
									this.currentStage = '待机';
									if (result.success) {
										this.addLog('测量已停止');
									} else {
										this.addLog(`停止测量失败: ${result.error}`);
									}
								});
							} catch (error) {
								this.measuring = false;
								this.addLog(`停止测量失败: ${error.message}`);
							}
					},
					toSmdtDevice(){
						uni.navigateTo({
							url:"/pages/index/smdtManager/smdtManager"
						})
					},
					toCamera(){
						uni.navigateTo({
							url:"/pages/device/tongue/test"
						})
					},
					toCamera1(){
						console.log("qxj toCamera1");
						uni.navigateTo({
							url:"/pages/device/tongue/testCameraAuto"
						})
					},
					toTongue(){
						uni.navigateTo({
							url:"/pages/device/tongue/indexOld"
						})
					},
					
					// 强制竖屏测脉
					toMeasurePortrait() {
						try {
							// 设置强制竖屏
							this.tyPulse.setOrientationConfig({
								autoOrientationEnabled: false,
								forcedOrientation: 1 // ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
							});
							this.addLog('设置强制竖屏模式');
							
							this.tyPulse.toMeasure((result) => {
								setTimeout(() => {
									uni.showToast({
										title: '竖屏模式: ' + JSON.stringify(result),
										icon: 'none'
									});
								}, 2000);
								if (result.success) {
									if (result.cmdType == "pulseResult") {
										this.addLog('测量结果(竖屏):' + JSON.stringify(result));
									}
									if (result.cmdType == "deviceConnect") {
										this.getDeviceInfo();
										this.addLog('回调结果(竖屏):' + JSON.stringify(result));
									}
								}
							});
						} catch (error) {
							this.addLog(`竖屏测脉失败: ${error.message}`);
						}
					},
					
					// 强制横屏测脉
					toMeasureLandscape() {
						try {
							// 设置强制横屏
							this.tyPulse.setOrientationConfig({
								autoOrientationEnabled: false,
								forcedOrientation: 0 // ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
							});
							this.addLog('设置强制横屏模式');
							
							this.tyPulse.toMeasure((result) => {
								setTimeout(() => {
									uni.showToast({
										title: '横屏模式: ' + JSON.stringify(result),
										icon: 'none'
									});
								}, 2000);
								if (result.success) {
									if (result.cmdType == "pulseResult") {
										this.addLog('测量结果(横屏):' + JSON.stringify(result));
									}
									if (result.cmdType == "deviceConnect") {
										this.getDeviceInfo();
										this.addLog('回调结果(横屏):' + JSON.stringify(result));
									}
								}
							});
						} catch (error) {
							this.addLog(`横屏测脉失败: ${error.message}`);
						}
					},
					
					// 自动屏幕方向测脉
					toMeasureAuto() {
						try {
							// 设置自动屏幕方向
							this.tyPulse.setOrientationConfig({
								autoOrientationEnabled: true,
								forcedOrientation: -1 // ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
							});
							this.addLog('设置自动屏幕方向模式');
							
							this.tyPulse.toMeasure((result) => {
								setTimeout(() => {
									uni.showToast({
										title: '自动方向: ' + JSON.stringify(result),
										icon: 'none'
									});
								}, 2000);
								if (result.success) {
									if (result.cmdType == "pulseResult") {
										this.addLog('测量结果(自动):' + JSON.stringify(result));
									}
									if (result.cmdType == "deviceConnect") {
										this.getDeviceInfo();
										this.addLog('回调结果(自动):' + JSON.stringify(result));
									}
								}
							});
						} catch (error) {
							this.addLog(`自动方向测脉失败: ${error.message}`);
						}
				},

				// 尝试自动连接（不显示设备选择弹框）
					async tryAutoConnect() {
						try {
							this.addLog('开始尝试自动连接...');
							
							// 优先使用智能连接
							if (this.tyPulse.smartConnect) {
								const smartResult = await new Promise((resolve) => {
									this.tyPulse.smartConnect(resolve);
								});
								
								this.addLog('智能连接结果: ' + JSON.stringify(smartResult));
								
								if (smartResult.success) {
									if (smartResult.isAlreadyConnected) {
										this.deviceConnected = true;
										this.addLog('设备已连接');
										this.getDeviceInfo();
										return true;
									} else if (smartResult.isAutoReconnected) {
										this.deviceConnected = true;
										this.addLog('自动重连成功');
										this.getDeviceInfo();
										return true;
									}
								}
							}
							
							// 如果智能连接失败，尝试连接已保存的设备
							if (this.tyPulse.connectToSavedDevice) {
								const savedResult = await new Promise((resolve) => {
									this.tyPulse.connectToSavedDevice(resolve);
								});
								
								this.addLog('连接已保存设备结果: ' + JSON.stringify(savedResult));
								
								if (savedResult.success) {
									this.deviceConnected = true;
									this.addLog('连接已保存设备成功');
									this.getDeviceInfo();
									return true;
								}
							}
							
							this.addLog('自动连接失败，无法连接到设备');
							return false;
							
						} catch (error) {
							this.addLog(`自动连接异常: ${error.message}`);
							return false;
						}
					},

					// 断开蓝牙连接
					disconnectDevice() {
						if (this.tyPulse) {
							this.tyPulse.disconnectDevice((result) => {
								console.log('断开连接结果:', result);
								if (result.success) {
									this.addLog('蓝牙连接已断开');
									this.deviceConnected = false;
									this.reconnectAttempts = 0; // 重置重连次数
								} else {
									this.addLog('断开连接失败: ' + (result.error || '未知错误'));
								}
							});
						} else {
							this.addLog('插件未初始化，无法断开连接');
						}
					}
			}
		}
</script>

<style scoped lang="scss">
	.container {
		padding: 20rpx;
		background-color: #f8f9fa;
		min-height: 100vh;
	}

	.header {
		text-align: center;
		padding: 30rpx;
		background-color: #007AFF;
		border-radius: 10rpx;
		margin-bottom: 20rpx;
	}

	.title {
		color: white;

		font-weight: bold;
	}

	.status-section {
		background-color: white;
		border-radius: 10rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;

	}

	.status-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.status-item:last-child {
		border-bottom: none;
	}

	.status-label {

		color: #666;
	}

	.status-value {
		font-weight: bold;
	}

	.status-value.success {
		color: #52c41a;
	}

	.status-value.error {
		color: #ff4d4f;
	}

	.status-value.warning {
		color: #faad14;
	}

	.status-value.normal {
		color: #666;
	}

	/* 连接状态指示器样式 */
	.connection-status {
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: white;
		border-radius: 10rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
	}

	.status-indicator {
		width: 20rpx;
		height: 20rpx;
		border-radius: 50%;
		margin-right: 15rpx;
		animation: pulse 2s infinite;
	}

	.status-indicator.connected {
		background-color: #52c41a;
	}

	.status-text {
		color: #52c41a;
		font-weight: bold;
	}

	@keyframes pulse {
		0% {
			opacity: 1;
			transform: scale(1);
		}
		50% {
			opacity: 0.7;
			transform: scale(1.1);
		}
		100% {
			opacity: 1;
			transform: scale(1);
		}
	}

	.device-section,
	.result-section,
	.log-section {
		background-color: white;
		border-radius: 10rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
	}

	.section-title {
		font-weight: bold;
		color: #333;
		margin-bottom: 15rpx;
		display: block;
	}

	.device-name {

		color: #333;
		margin-bottom: 10rpx;
		display: block;
	}

	.device-battery {

		color: #666;
		display: block;
	}

	.action-section {
		background-color: white;
		border-radius: 10rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
		display: flex;
		flex-direction: column;
		gap: 15rpx;
	}

	.btn {
		padding: 5px;
		border-radius: 8rpx;
		border: none;
		text-align: center;
		width: 100%;
		margin: 6rpx;
		//font-size: 14px;
	}

	.btn-primary {
		background-color: #007AFF;
		color: white;
	}

	.btn-secondary {
		background-color: #6c757d;
		color: white;
	}

	.btn-success {
		background-color: #28a745;
		color: white;
	}

	.btn-danger {
		background-color: #dc3545;
		color: white;
	}

	.btn:disabled {
		opacity: 0.5;
		background-color: #ccc;
	}

	.progress-section {
		background-color: white;
		border-radius: 10rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
	}

	.progress-text {

		color: #333;
		margin-bottom: 15rpx;
		display: block;
	}

	.progress-bar {
		width: 100%;
		height: 20rpx;
		background-color: #f0f0f0;
		border-radius: 10rpx;
		overflow: hidden;
		margin-bottom: 15rpx;
	}

	.progress-fill {
		height: 100%;
		background-color: #007AFF;
		transition: width 0.3s ease;
	}

	.stage-text {

		color: #666;
		text-align: center;
		display: block;
	}

	.result-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 12rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.result-item:last-child {
		border-bottom: none;
	}

	.result-label {

		color: #666;
	}

	.result-value {

		color: #333;
		font-weight: bold;
	}

	.log-list {
		height: 700rpx;
		border: 1rpx solid #e8e8e8;
		border-radius: 8rpx;
		padding: 10rpx;
	}

	.log-item {
		padding: 8rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.log-item:last-child {
		border-bottom: none;
	}

	.log-text {

		color: #666;
		line-height: 1.4;
	}
</style>