<template>
	<view class="content">
		<!-- 个人信息 -->
		<view class="blur-bg-2"></view>
		<view class="top-btn">
			<view class="back x-c" @click="$navBack()">
				<image src='/static/image/new/icon_back.svg'></image>
				返回
			</view>
			<view class="title x-c">
				<image src='/static/image/new/img_title1.svg'></image>
				<text>脉诊</text>
				<image src='/static/image/new/img_title2.svg'></image>
			</view>
			<view class="index x-c" @click="goIndex">
				<image src='/static/image/new/icon_home.svg'></image>
				首页
			</view>
		</view>
		<view class="userBox y-bc">
			<view class="tranBox">
				<view>引导动画</view>
			</view>
			<view class="btnBox">
				<view class="timer x-c" v-if="status == 'init'|| status == 'disinfecting'">
					<image src='/static/image/new/icon_safe.svg'></image>
					一键消毒，安心检测~
				</view>
				<view class="timer2 y-c" v-if="status == 'fail'">
					<image src='/static/image/new/icon_sad.svg'></image>
					采集失败，调整下姿势，再试一试呢
				</view>
				<view class="timer3 y-c" v-if="status == 'collecting'">
					<view class="progress">
						<u-line-progress :percentage="30" :showText="false" height="18" inactiveColor="#fff" activeColor="#3CD3AD"></u-line-progress>
					</view>
					正在精准采集中...
				</view>
				<view class="timer4 y-c" v-if="status == 'guide'">
					<view class="item x-c">
						<image src='/static/image/new/icon_item.svg'></image>
						请将手放在脉诊垫上
					</view>
					<view class="item x-c">
						<image src='/static/image/new/icon_item.svg'></image>
						手腕放松，掌心向上
					</view>
				</view>
				<view class="timer5 y-c" v-if="status == 'sensing'">
					<view class="progress">
						<u-loading-icon mode="circle" color="#3CD3AD" size="62"></u-loading-icon>
					</view>
					正在感知您的脉象 请保持放松
				</view>
				<view class="btn" @click="toConnect" v-if="status == 'init'">去脉诊</view>
				<!-- <view class="btn" @click="start" v-if="status == 'init'">一键消毒</view>
				<view class="btn loading-btn" v-if="status == 'disinfecting'">
					<u-loading-icon color="#fff" size="48"></u-loading-icon>消毒中
				</view>
				<view class="btn" @click="restartDetect" v-if="status == 'fail'">重新检测</view> -->
			</view>
		</view>
		<view v-if="isShow" class="mask">
			<view class="popup-container">
				<image class="bg" src='/static/image/new/bg_popup.svg'></image>
				<view class="title-t x-c">
					<image src='/static/image/new/img_title1.svg'></image>
					<text>提示</text>
					<image src='/static/image/new/img_title2.svg'></image>
					</view>
				<view class="title-r">点击确认查看检测报告</view>
				<!-- <image style="width: 200px;height: 200px;margin-bottom: 20px;" :src="qUrl"></image> -->
				<view class="x-c">
					<!-- <view class="btn-l" @click="close">取消</view> -->
					<view class="btn-r" @click="closeP">确认</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getUserInfoByUserId,
		getUserInfo
	} from '@/api/user.js';
	import {
		addPulse
	} from '@/api/healthTongue.js'
	export default {
		data() {
			return {
				// 状态：init(初始)/disinfecting(消毒中)/collecting(采集ing)/fail(失败)/guide(引导)
				status: 'init',
				progressPercent: 0, // 进度条百分比
				progressTimer: null ,// 定时器
				showProgress: false, // 是否显示进度条
				info: null,
				// 插件实例
				tyPulse: null,
				// 状态
				initStatus: false,
				deviceConnected: false,
				measuring: false,
				// 设备信息
				deviceInfo: null,
				// 测量相关
				measureProgress: 0,
				currentStage: '待机',
				lastResult: null,
				appId: "nehijR6y",
				appSecret: "f740435d1b84b9944a52f064dd1ecf6e8a76f546",
				uid: "userid000067",
				qUrl: '',
				isShow:false,
				initData:{},
				user:{}
			}
		},
		onLoad(option) {
			//this.startCountDown();
			this.initPlugin()
		},
		onShow() {
			this.user=JSON.parse(uni.getStorageSync('userInfo'));
	// 清除所有定时器，防止内存泄漏
			clearInterval(this.progressTimer);
			this.progressTimer = null;
		},
		methods: {
			//开始消毒
			start() {
				this.status = 'disinfecting';
				//this.status = 'sensing';
								this.showProgress = true;
								// 模拟消毒进度
								this.progressPercent = 0;
								this.progressTimer = setInterval(() => {
									if (this.progressPercent >= 100) {
										clearInterval(this.progressTimer);
										this.progressTimer = null;
										// 消毒完成后进入引导状态
										this.status = 'guide';
										this.showProgress = false;
										// 3秒后自动进入脉象感知状态
										setTimeout(() => {
											this.startSensePulse();
										}, 3000);
										return;
									}
									this.progressPercent += 2;
								}, 100);
			},
				/**
						 * 开始感知脉象
						 */
						startSensePulse() {
							this.status = 'sensing';
							this.showProgress = false;
							
							// 模拟脉象感知过程（5秒）
							setTimeout(() => {
								// 感知完成后进入精准采集状态
								this.startCollect();
							}, 5000);
						},
						
						/**
						 * 开始精准采集
						 */
						startCollect() {
							this.status = 'collecting';
							this.showProgress = true;
							this.progressPercent = 0;
							// 模拟采集进度（随机失败/成功）
							this.progressTimer = setInterval(() => {
								if (this.progressPercent >= 100) {
									clearInterval(this.progressTimer);
									this.progressTimer = null;
									// 随机模拟采集结果（70%成功，30%失败）
									const isSuccess = Math.random() > 0.3;
									if (isSuccess) {
										// 采集成功，跳转到分析页面
										//this.goAnalysis();
									} else {
										// 采集失败
										this.status = 'fail';
										this.showProgress = false;
									}
									return;
								}
								this.progressPercent += 1;
							}, 150);
						},
			//重新检测
			restartDetect() {
				this.status = 'init';
			},
			//跳转分析
			goAnalysis() {
				uni.redirectTo({
					url: '/pages/index/loading', // 替换为实际分析页面路径
					fail: (err) => {
						console.error('跳转失败：', err);
						uni.showToast({
							title: '跳转失败',
							icon: 'none'
						});
					}
				});
			},
			// 初始化插件
			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;
					console.log('插件初始化成功');
					// uni.showToast({
					// 	title: '初始化成功',
					// 	icon: 'success'
					// });
			
				} catch (error) {
					console.log(`初始化失败: ${error.message}`);
					uni.showToast({
						title: '初始化失败',
						icon: 'error'
					});
				}
			},
			toMeasure() {
				try {
					// 设置自动屏幕方向
					this.tyPulse.toMeasure((result) => {
						if (result.success) {
							if (result.cmdType == "pulseResult") {
								this.info = result;
								console.log('脉诊回调结果:', result);
								this.addPulse()
							}
							if (result.cmdType == "deviceConnect") {
								//获取设备信息
								this.getDeviceInfo();
							}
						}
					});
				} catch (error) {
					console.log(`测脉失败: ${error.message}`);
				}
			},
			// 获取设备信息
			getDeviceInfo() {
				try {
					this.tyPulse.getDeviceInfo((result) => {
						if (result.success && result.data) {
							this.deviceInfo = result.data;
							this.deviceConnected = result.data.isConnected;
							//console.log('设备信息获取成功:' + JSON.stringify(result.data));
						}
					});
				} catch (error) {
					console.log(`获取设备信息失败: ${error.message}`);
				}
			},
			toConnect() {
				// if (this.$isEmpty(this.selectUser)) {
				// 	uni.showToast({
				// 		title: '请先选择就诊人',
				// 		icon: 'none'
				// 	});
				// 	return;
				// }
				this.isConnect = true
				this.toMeasure()
			},
			addPulse() {
				if (this.$isEmpty(this.info)) {
					uni.showToast({
						title: '测量失败,请重试',
						icon: 'none'
					});
					return;
				}
				const data = {
					userId: this.user.fsUserId,
					sex: this.user.sex,
					name: this.user.username,
					pulseEquipmentResult: {
						reportData: JSON.parse(this.info.reportData),
						success: this.info.success,
						measureId: this.info.measureId,
						pulseUrl: JSON.parse(this.info.pr)
					}
				}
				console.log("qxj addPulse data",data);
				uni.showLoading({
					title: "处理中...",
					mask: true
				})
				addPulse(data).then(res => {
						console.log('zaizz', data, res)
						if (res.code == 200) {
							uni.hideLoading();
							//this.qUrl = res.codeImage
							this.isConnect = false
							this.isResult = true
						} else {
							uni.hideLoading();
							this.isConnect = false
							this.errMsg = res.msg;
							uni.showToast({
								icon: 'none',
								title: res.msg,
							});
						}
					},
					rej => {}
				);
			},
			closeP() {
				this.isResult = false
				uni.navigateTo({
					url: "/pages/user/healthReportOld?userId="+this.user.fsUserId
				})
			
			},
			//首页
			goIndex() {
				uni.reLaunch({
					url: '/pages/index/index',
					animationType: 'none',
					animationDuration: 2000
				})
			},

		}
	}
</script>


<style scoped lang="scss">
	page {
		background: #fff;
		font-size: 16px
	}
/* 遮罩层样式 */
	.mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 999;
		animation: fadeIn 0.3s ease;
	}

	/* 弹窗容器样式 */
	.popup-container {
		//width: 50%;
		width: 620px;
		height: 352px;
		background: #FFFFFF;
		border-radius: 39px 39px 39px 39px;
		animation: scaleIn 0.3s ease;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-between;
		padding:43px;
		position: relative;
		.bg{
			width: 100%;
			height: 244px;
			position: absolute;
			top:0
		}
		.title-t {
			image{
				width: 153px;
				height: 25px;
			}
			text{
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 32px;
				color: #333333;
				margin: 0 10px;
			}
		}

		.title-r {
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			font-size: 28px;
			color: #333333;
		}
       .btn-l{
		   display: flex;
		   align-items: center;
		   justify-content: center;
		   font-family: PingFang SC, PingFang SC;
		   font-weight: 600;
		   font-size: 28px;
		   color: #37C3A0;
		   width: 220px;
		   height: 64px;
		   border-radius: 121px 121px 121px 121px;
		   border: 2px solid #37C3A0;
		   margin-right: 40px;
	   }
		.btn-r {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 220px;
			height: 64px;
			background: #37C3A0;
			border-radius: 121px 121px 121px 121px;
			font-family: PingFang SC, PingFang SC;
			font-weight: 600;
			font-size: 28px;
			color: #FFFFFF;
		}
	}
	.content {
		width: 100%;
		height: 100vh;
		background: #D8F6EF;
		padding: 28px;
		display: flex;
		flex-direction: column;

		.blur-bg-2 {
			width: 350px;
			height: 350px;
			background: #FFFDCC;
			// opacity: 0.47;
			filter: blur(200px);
			position: absolute;
			z-index: 1;
			top: 60px;
			right: calc(0px - 107px);
			pointer-events: none
		}
	}

	.top-btn {
		display: flex;
		align-items: center;
		justify-content: space-between;
		z-index: 2;

		.back {
			width: 140px;
			height: 48px;
			background: rgba(255, 255, 255, 0.64);
			border-radius: 45px 45px 45px 45px;
			border: 2px solid #FFFFFF;
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 22px;
			color: #327E6F;

			image {
				margin-right: 4px;
				width: 24px;
				height: 24px;
			}
		}

		.title {
			font-family: PingFang SC, PingFang SC;
			font-weight: 600;
			font-size: 36px;
			color: #327E6F;
			line-height: 54px;

			text {
				margin: 0 14px;
			}

			image {

				width: 153px;
				height: 25px;
			}
		}

		.index {
			width: 140px;
			height: 48px;
			background: rgba(255, 255, 255, 0.64);
			border-radius: 55px 55px 55px 55px;
			border: 2px solid #FFFFFF;
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 22px;
			color: #327E6F;

			image {
				margin-right: 4px;
				width: 24px;
				height: 24px;
			}
		}
	}

	.userBox {
		flex: 1;
		margin-top: 28px;
		background: rgba(255, 255, 255, 0.7);
		border-radius: 24px 24px 24px 24px;
		padding: 27px 40px;
		z-index: 9;

		.tranBox {
			display: flex;
			align-items: center;
			flex-direction: column;
			justify-content: center;
			margin-top: 85px;
			width: 727px;
			height: 442px;
			background: #FFFFFF;
			border-radius: 36px 36px 36px 36px;

			view {
				font-family: PingFang SC, PingFang SC;
				font-weight: 600;
				font-size: 40px;
				color: #7FD7C5;
			}

			image {
				width: 99px;
				height: 99px;
			}

			.title {
				margin-top: 42px;
				width: 468px;
				height: 57px;
				line-height: 57px;
				text-align: center;
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 35px;
				color: #333333;
				background-image: url(/static/image/new/img_cloud.svg);
				background-repeat: no-repeat;
				position: relative;
				background-size: 100% 100%;
			}

			.text {
				margin-top: 11px;
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				font-size: 28px;
				color: #333333;
			}
		}

		.btnBox {
			display: flex;
			align-items: center;
			flex-direction: column;

			.timer {
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				font-size: 32px;
				color: #333333;
				line-height: 72px;

				image {
					width: 32px;
					height: 32px;
					margin-right: 20px;
				}
			}

			.timer2 {
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				font-size: 28px;
				color: #333333;
				line-height: 38px;

				image {
					width: 84px;
					height: 84px;
				}
			}

.timer3 {
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				font-size: 28px;
				color: #333333;
				line-height: 72px;
				margin-bottom: 56px;
				.progress{
					width: 420px;
					margin-bottom: 33px;
				}
			}
.timer4 {
	margin-bottom: 60px;
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				font-size: 32px;
				color: #333333;
				line-height: 48px;
               .item{
				   margin-top: 28px;
			   }
				image {
					width: 32px;
					height: 32px;
					margin-right: 30px;
				}
			}
			.timer5 {
				margin-bottom: 56px;
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				font-size: 28px;
				color: #333333;
				line-height: 45px;
				.progress{
					margin-bottom: 32px;
				}
						}
			.btn {
				margin-top: 28px;
				margin-bottom: 29px;
				display: flex;
				align-items: center;
				justify-content: center;
				width: 360px;
				height: 68px;
				background: #37C3A0;
				border-radius: 121px 121px 121px 121px;
				font-family: PingFang SC, PingFang SC;
				font-weight: 600;
				font-size: 28px;
				color: #FFFFFF;
				transition: all 0.3s;

				// 消毒中按钮样式
				&.loading-btn {
					display: flex;
					align-items: center;
					justify-content: center;
					background: #37C3A0;
					opacity: 0.6;
					pointer-events: none; // 禁用点击
				}
			}
		}

	}
</style>