<template>
	<ax-body blank="0" hideIndicatorArea>
		<image src="@/static/img/page-bg01.png" class="page-background"></image>
		<view class="body">
			<view v-if="exiting.visible" class="exiting">
				<view class="app-flex c-center column contet">
					<view class="exiting-title">长按停止按钮结束充电</view>
					<view class="countdown-ring" :class="{ active: exiting.lock }" @touchstart="exiting.lock = true"
						@touchend="exiting.lock = false">
						<view class="_half left" @animationend="submitExit()"></view>
						<view class="_half right"></view>
						<view class="_button">
							<view>停止</view>
							<view>充电</view>
						</view>
					</view>
					<view class="close" @click="exiting.visible = false">取消</view>
				</view>
				<view @click="exiting.visible = false" class="mask"></view>
			</view>
			<view v-if="deviceInfo.orderStatus == 1" class="timer">
				<view class="value" style="font-size: 22px;">充电正在启动中......</view>
				<view v-if="isShowBtn" class="name" style="color: red;font-size: 14px;">长时间无法启动可点击“长按结束充电”按钮结束订单。</view>
			</view>
			<!-- 主图 -->
			<view class="app-flex c-center host-graph">
				<image
					src="https://national-motion.oss-cn-beijing.aliyuncs.com/20251230/9ca38a2aa5784e06b9cac31587b188b3.png"
					mode="widthFix" class="image"></image>
			</view>
			<!-- 主参数 -->
			<view class="parameter-info-box">
				<!-- 充电动画 -->
				<view class="charge-loading-box" v-if="deviceInfo.orderStatus == 2">
					<view class="charge-loading">
						<image class="charge-icon" src="../../static/img/charge_loading.svg" mode=""></image>
						<view class="c-loading"></view>
					</view>
				</view>
				<!-- 计时器 -->
				<view class="timer" v-if="deviceInfo.orderStatus == 2">
					<view class="value">{{ timer.text }}</view>
					<view class="name">充电时间</view>
				</view>
				<view class="parameter">
					<view class="param">
						<view class="name">电流A</view>
						<view class="value">{{ deviceInfo.current || '0' }}</view>
					</view>
					<view class="split"></view>
					<view class="param">
						<view class="name">电压V</view>
						<view class="value">{{ deviceInfo.voltage || '0' }}</view>
					</view>
					<view class="split"></view>
					<view class="param">
						<view class="name">功率KW</view>
						<view class="value">{{ deviceInfo.power || '0' }}</view>
					</view>
					<view class="split"></view>
					<view class="param">
						<view class="name">电量/度</view>
						<view class="value">{{ deviceInfo.totalPower || '0' }}</view>
					</view>
					<view class="split"></view>
					<view class="param">
						<view class="name">费用/元</view>
						<view class="value">{{ deviceInfo.totalMoney || '0' }}</view>
					</view>
				</view>
				<view class="end-charge-box">
					<button @click="exiting.visible = true" :disabled="!isShowBtn" class="end-charge">结束充电</button>
				</view>
			</view>
			<!-- 信息 -->
			<view id="info" class="info">
				<view>
					<view class="cell">
						<view class="lable">订单编号</view>
						<view class="contet">{{ deviceInfo.chargeOrderNo }}</view>
					</view>
					<view class="cell">
						<view class="lable">终端编号</view>
						<view class="contet">{{ deviceInfo.connectorCode }}</view>
					</view>
					<view class="cell">
						<view class="lable">充电电站</view>
						<view class="contet">{{ deviceInfo.stationName }}</view>
					</view>
					<view class="cell">
						<view class="lable">充电终端</view>
						<view class="contet">{{ deviceInfo.connectorName }}</view>
					</view>
				</view>
				<view class="tips">账单信息可能会有所延迟，具体以实际结算为准</view>
				<!-- 				<view>
					<button @click="exiting.visible=true" :disabled="!isShowBtn" class="end">结束充电</button>
					<ax-ios-indicator min="10"></ax-ios-indicator>
				</view> -->
			</view>
		</view>
	</ax-body>
</template>

<script>
export default {
	onLoad(opts) {
		console.log("启动充值页面的参数：", opts)
		this.orderInfo.id = opts.orderId;
		this.deviceInfo.id = opts.deviceId;
	},
	onShow() {
		this.getDeviceInfo();
		// this.getOrderInfo();
	},
	data() {
		return {
			exiting: {
				visible: false,
				lock: false
			},
			timer: {
				id: 0,
				start: '2024/08/07 09:00:00',
				text: '00：00：00',
				isSatrt: false,
			},
			pollingTimer: null, //轮询定时器ID
			deviceInfo: {}, //充电桩的信息
			orderInfo: {
				id: 1
			}, //订单信息
			isShowBtn: true, //是否显示长按结束按钮 
		}
	},
	destroyed() {
		console.log("关闭页面了。。。。。。")
		//关闭页面了，要清除定时器
		this.stopPolling();
		clearInterval(this.timer.id);
	},
	methods: {
		//获取设备的详情信息（含轮询）
		getDeviceInfo(showLoading = true) {
			this.$api.base("get", "/applet/v1/station/charging-cost", {}, {
				loading: showLoading
			}).then(res => {
				this.deviceInfo = res.data;
				// 检查订单状态，已完成或已结束则跳转订单详情
				if (res.data.orderStatus == 4 || res.data.orderStatus == 5) {
					uni.hideLoading();
					this.stopPolling();
					clearInterval(this.timer.id);
					this.$app.url.goto('/subPackages/order/order-detail?chargeOrderNo=' + res.data.chargeOrderNo, false);
					return;
				}

				// 充电中状态，启动计时器
				if (res.data.orderStatus == 2 && !this.timer.isSatrt) {
					this.startup();
				}
				// 检查是否显示结束按钮
				this.checkShowEndBtn(res.data.startTime);
				// 启动轮询
				this.startPolling();
			})
		},
		//启动轮询定时器，每5秒查询一次
		startPolling() {
			if (this.pollingTimer) return; // 已启动则不重复
			this.pollingTimer = setInterval(() => {
				this.getDeviceInfo(false);
			}, 5000);
		},
		//停止轮询
		stopPolling() {
			if (this.pollingTimer) {
				clearInterval(this.pollingTimer);
				this.pollingTimer = null;
			}
		},
		//检查是否显示长按结束按钮
		checkShowEndBtn(orderTime) {
			if (!orderTime) return;
			const t1 = new Date(orderTime.replace(/-/g, '/')).getTime();
			const t2 = Date.now();
			const diffSeconds = (t2 - t1) / 1000;
			// 启动时间大于60秒或状态为充电中，显示结束按钮
			if (diffSeconds >= 60 || this.deviceInfo.orderStatus == 2) {
				this.isShowBtn = true;
			}
		},
		// 启动定时器
		startup() {
			// 使用 this.deviceInfo.startTime 替代 this.timer.start
			const start = new Date(this.deviceInfo.startTime);
			const obj = {
				hour: 0,
				minute: 0,
				second: 0
			};
			const handle = () => {
				this.timer.isSatrt = true;
				const diff = Date.now() - start.getTime();
				obj.hour = Math.floor(diff / 1000 / 60 / 60);
				obj.minute = Math.floor(diff / 1000 / 60 % 60);
				obj.second = Math.floor(diff / 1000 % 60);
				this.timer.text =
					`${String(obj.hour).padStart(2, '0')}：${String(obj.minute).padStart(2, '0')}：${String(obj.second).padStart(2, '0')}`;
			}
			clearInterval(this.timer.id);
			this.timer.id = setInterval(handle, 1000);
			handle();
		},
		// 退出充电
		exit() {
			this.$api.base("post", "/applet/v1/charge/stopCharge", {
				"chargeOrderNo": this.deviceInfo.chargeOrderNo
			}, {}).then(res => {
				this.exiting.lock = false;
				this.stopPolling();

				// 显示结算中loading
				this.$app.popup.loading(true, {
					title: "结算中，请稍候",
					timeout: 120 * 1000
				});

				// 2秒后开始轮询查询订单状态
				setTimeout(() => {
					this.getDeviceInfo(false);
				}, 2000);
			}).catch(() => {
				this.exiting.lock = false;
			})
		},
		// 长按动画结束
		submitExit() {
			this.exiting.lock = false;
			this.exiting.visible = false;
			this.exit();
		}
	}
}
</script>

<style lang="less" scoped>
@import url("charging.css");

/* 充电loading动画 */
.charge-loading-box {
	text-align: center;
	margin-top: 20rpx;
}

.charge-loading {
	width: 364rpx;
	height: 36rpx;
	background: #FFFFFF;
	border-radius: 18rpx;
	overflow: hidden;
	position: relative;
	margin: auto;
}

.charge-icon {
	width: 28rpx;
	height: 28rpx;
	z-index: 1000;
	position: absolute;
	left: 20rpx;
	top: 5rpx;
}

.c-loading {
	width: 100%;
	height: 100%;
	background: linear-gradient(66deg,
			rgba(139, 243, 251, 0),
			#60C8FE,
			#53D4FF,
			rgba(139, 243, 251, 0.7), );
	border-radius: 18rpx;
	animation: loading 3s linear infinite;
	background-size: 200% 100%;
}

@keyframes loading {
	0% {
		background-position: 100% 0;
	}

	100% {
		background-position: -100% 0;
	}
}
</style>