<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" class="timer">
				<view class="circleBox">
					<view class="circle"></view>
					<view class="circle1"></view>
					<view class="circle2"></view>
					<view class="circle3"></view>
				</view>
				<view class="timer-box">
					<view class="value" style="font-size: 22px;">充电正在启动中</view>
					<!-- <view v-if="isShowBtn" class="name">长时间无法启动可点击“启动中”按钮结束订单。</view> -->
				</view>
			</view>
			<!-- 主图 -->
			<!-- v-if="deviceInfo.status == '1'" -->
			<view class="host-graph" v-if="deviceInfo.status == '1'">
				<view class="progress-wrapper">
					<CirclePercent :percent="deviceInfo.soc" :size="140" :angle="50" :lineWidth="7"
						backgroundColor="#97DAFF" :color="['#47AEFF']" />
				</view>
				<image
					src="https://national-motion.oss-cn-beijing.aliyuncs.com/20260108/2bf62776bec44e3ab43ac3df02d8deac.gif"
					mode="" class="image"></image>
			</view>
			<!-- 主参数 -->
			<view class="parameter-info-box">
				<!-- 计时器 -->
				<view class="timer-father">
					<view class="item-value">{{ timer.text }}</view>
					<view class="item-name">充电时间</view>
				</view>
				<view class="parameter">
					<view class="param">
						<view class="name">电流A</view>
						<view class="value">
							<text v-if="deviceInfo.current">{{ deviceInfo.current }}</text>
							<image v-else style="width: 40rpx;height: 40rpx;" src="@/static/img/charge-icon.svg"
								mode="" />
						</view>
					</view>
					<view class="split"></view>
					<view class="param">
						<view class="name">电压V</view>
						<view class="value">
							<text v-if="deviceInfo.voltage">{{ deviceInfo.voltage }}</text>
							<image v-else style="width: 40rpx;height: 40rpx;" src="@/static/img/charge-icon.svg"
								mode="" />
						</view>
					</view>
					<view class="split"></view>
					<view class="param">
						<view class="name">功率KW</view>
						<view class="value">
							<text v-if="deviceInfo.power">{{ deviceInfo.power }}</text>
							<image v-else style="width: 40rpx;height: 40rpx;" src="@/static/img/charge-icon.svg"
								mode="" />
						</view>
					</view>
					<view class="split"></view>
					<view class="param">
						<view class="name">电量/度</view>
						<view class="value">
							<text v-if="deviceInfo.totalPower">{{ deviceInfo.totalPower }}</text>
							<image v-else style="width: 40rpx;height: 40rpx;" src="@/static/img/charge-icon.svg"
								mode="" />
						</view>
					</view>
					<view class="split"></view>
					<view class="param">
						<view class="name">费用/元</view>
						<view class="value">
							<text v-if="deviceInfo.totalMoney">{{ deviceInfo.totalMoney }}</text>
							<image v-else style="width: 40rpx;height: 40rpx;" src="@/static/img/charge-icon.svg"
								mode="" />
						</view>
					</view>
				</view>
				<view class="end-charge-box">
					<button @click="exiting.visible = true" :disabled="!isShowBtn" class="end-charge">
						<image v-if="!deviceInfo" class="loading-icon" src="@/static/img/loading.svg" mode="" />
						{{ !deviceInfo ?
							'启动中' : '正在充电' }}
					</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>
import CirclePercent from '@/components/qs-circle-percent/qs-circle-percent.vue'
// 终态状态码：2-结算中, 3-已完成, 5-未成功充电
const TERMINAL_STATUS = ['2', '3', '5'];

export default {
	components: {
		CirclePercent
	},
	onLoad(opts) {
		console.log("启动充值页面的参数：", opts)
		this.orderInfo.id = opts.orderId;
		this.deviceInfo.id = opts.deviceId;
		this.chargeOrderNo = opts.chargeOrderNo || '';
		this.getDeviceInfo(true, opts.chargeOrderNo);
	},
	onShow() {
		// 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
			}, //订单信息
			chargeOrderNo: '',
			isShowBtn: true, //是否显示长按结束按钮
			isStoppingCharge: false, //是否正在停止充电（用户主动停止）
		}
	},
	destroyed() {
		console.log("关闭页面了......")
		// 页面销毁时清除所有定时器
		this.clearAllTimers();
	},
	methods: {
		/**
		 * 清除所有定时器（轮询+计时器）
		 */
		clearAllTimers() {
			this.stopPolling();
			if (this.timer.id) {
				clearInterval(this.timer.id);
				this.timer.id = 0;
			}
		},

		/**
		 * 检查是否为终态状态（需要跳转的状态）
		 * @param {string} status 状态码
		 * @returns {boolean}
		 */
		isTerminalStatus(status) {
			return TERMINAL_STATUS.includes(String(status));
		},

		/**
		 * 处理终态跳转（统一跳转和清理逻辑）
		 */
		handleTerminalRedirect() {
			uni.hideLoading();
			this.clearAllTimers();
			this.isStoppingCharge = false;
			this.$app.url.goto('/subPackages/order/order/order');
		},
		/**
		 * 获取设备的详情信息（含轮询）
		 * @param {boolean} showLoading 是否显示loading
		 * @param {string} orderNo 订单号
		 */
		getDeviceInfo(showLoading = true, orderNo) {
			this.$api.base("get", "/applet/v1/station/charging-cost", {
				orderNo: orderNo || this.chargeOrderNo
			}, {
				loading: showLoading
			}).then(res => {
				this.deviceInfo = res.data;
				// 检查订单状态，终态则跳转订单列表
				// 状态：0-待启动, 1-充电中, 2-结算中, 3-已完成, 5-未成功充电
				if (this.isTerminalStatus(res.data.status)) {
					this.handleTerminalRedirect();
					return;
				}
				// 充电中状态，启动计时器
				// 订单状态：1-启动中, 2-充电中, 3-停止中, 4-已结束, 5-未知
				if (res.data.orderStatus == 2 && !this.timer.isSatrt) {
					this.startup();
				}
				// 检查是否显示结束按钮
				this.checkShowEndBtn(res.data.startTime);
				// 启动轮询（无论是否正在停止充电，都继续轮询等待状态变化）
				this.startPolling();
			}).catch(err => {
				console.error('获取充电信息失败:', err);
				// 请求失败时也要确保轮询继续
				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;
			}
		},

		/**
		 * 检查是否显示长按结束按钮
		 * @param {string} orderTime 订单开始时间
		 */
		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() {
			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.isStoppingCharge = true;
			this.$api.base("post", "/applet/v1/charge/stopCharge", {
				"chargeOrderNo": this.deviceInfo?.chargeOrderNo || this.chargeOrderNo
			}, {}).then(res => {
				if (res.code == '00000') {
					// 显示结算中loading
					this.$app.popup.loading(true, {
						title: "结算中，请稍候",
						timeout: 120 * 1000
					});
					this.exiting.lock = false;
					// 不停止轮询，继续轮询等待状态变为终态（2、3、5）再跳转
					// 轮询会在 getDeviceInfo 中检测到终态后自动跳转并清理
				} else {
					// 停止充电失败，重置状态
					this.isStoppingCharge = false;
					this.exiting.lock = false;
				}
			}).catch(() => {
				this.isStoppingCharge = false;
				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>