<template>
	<view class="detail-container">
		<!-- 轮播图区域 -->
		<swiper class="swiper-box" :indicator-dots="true" :circular="true" :autoplay="true" :interval="3000" :duration="500">
			<swiper-item v-for="(img, index) in sliderImages" :key="index">
				<image :src="img" class="slide-image" mode="aspectFill"></image>
			</swiper-item>
		</swiper>
		
		<!-- 价格与倒计时区域 -->
		<view class="price-section" :class="activityType">
			<view class="price-info">
				<view class="activity-price">
					<text class="unit">￥</text>
					<text class="num">{{ currentPrice }}</text>
				</view>
				<view class="original-price">
					<text>￥{{ detailData.originalPrice || detailData.otPrice }}</text>
				</view>
			</view>
			
			<view class="countdown-info" v-if="detailData.activityStatus !== 'ended' && detailData.activityStatus !== 'sold_out'">
				<text class="countdown-title">{{ detailData.activityStatus === 'not_started' ? '距开始' : '距结束' }}</text>
				<view class="countdown-time">
					<text class="time-block">{{ formatTime(detailData.countdown).h }}</text>
					<text class="colon">:</text>
					<text class="time-block">{{ formatTime(detailData.countdown).m }}</text>
					<text class="colon">:</text>
					<text class="time-block">{{ formatTime(detailData.countdown).s }}</text>
				</view>
			</view>
		</view>
		
		<!-- 商品基础信息 -->
		<view class="base-info">
			<view class="title">{{ detailData.productName }}</view>
			<view class="sub-info">
				<text class="sales">销量: {{ detailData.sales || 0 }}</text>
				<text class="stock">剩余库存: {{ detailData.remainStock || 0 }}</text>
			</view>
		</view>
		
		<!-- 商品详情 -->
		<view class="product-detail">
			<view class="detail-title">商品详情</view>
			<view class="detail-content">
				<rich-text :nodes="detailData.productInfo || '暂无详情'"></rich-text>
			</view>
		</view>
		
		<!-- 底部操作栏 -->
		<view class="bottom-action">
			<view class="btn-group">
				<button 
					class="action-btn" 
					:class="[
						activityType,
						detailData.activityStatus === 'not_started' ? 'disabled' : '',
						detailData.activityStatus === 'sold_out' ? 'disabled' : '',
						detailData.activityStatus === 'ended' ? 'disabled' : ''
					]"
					@tap="handleBuy"
				>
					{{ btnText }}
				</button>
			</view>
		</view>

		<!-- 规格选择弹窗 -->
		<popupBottom ref="popup" :visible.sync="specVisible" title=" " radius="32" maxHeight="1024">
			<view class="product-spec" v-if="detailData">
				<!-- 商品信息 -->
				<view class="pro-info">
					<view class="img-box">
						<image :src="currentSpec.image || detailData.productImage" mode="aspectFill"></image>
					</view>
					<view class="info-text">
						<view class="price">
							<text class="unit">¥</text>
							<text class="num">{{ currentSpec.price || currentPrice }}</text>
						</view>
						<view class="desc-box">
							<text class="text">已选：{{ currentSpec.specName || '默认规格' }}</text>
							<text class="text">库存：{{ currentSpec.remainStock !== undefined ? currentSpec.remainStock : detailData.remainStock }}</text>
						</view>
					</view>
				</view>
				
				<!-- 规格列表 -->
				<view class="spec-box" v-if="detailData.specs && detailData.specs.length > 0">
					<view class="title">规格</view>
					<view class="spec-list">
						<view 
							v-for="(item, index) in detailData.specs" 
							:key="index" 
							:class="['item', specIndex === index ? 'active' : '']" 
							@click="choseSpec(index)">
							{{ item.specName }}
						</view>
					</view>
				</view>
				
				<!-- 数量 (秒杀折扣限制数量为1，不可修改) -->
				<!-- <view class="price-num">
					<view class="label">数量</view>
					<view class="num-box">
						<view class="img-box" style="background:#f5f5f5;">
							<image src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/purpleShop/jian.png" mode=""></image>
						</view>
						<input type="number" value="1" disabled style="background:#f5f5f5;" />
						<view class="img-box" style="background:#f5f5f5;">
							<image src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/purpleShop/add.png" mode=""></image>
						</view>
					</view>
				</view> -->
				<view class="sub-btn" @click="submitSpec">确定</view>
			</view>
		</popupBottom>
	</view>
</template>

<script>
import { getFlashSaleDetail, getFlashSaleServerTime } from '@/api/flashSale.js';
import { getDiscountDetail, getDiscountServerTime } from '@/api/discount.js';
import { addCart } from '@/api/product.js';
import popupBottom from '@/components/px-popup-bottom/px-popup-bottom.vue';

export default {
	components: {
		popupBottom
	},
	data() {
		return {
			activityType: 'flash', // 'flash' 或 'discount'
			activityId: '',
			detailData: {},
			timer: null,
			stockTimer: null,
			serverTimestamp: 0,
			specVisible: false,
			specIndex: 0
		};
	},
	computed: {
		currentPrice() {
			if (this.activityType === 'flash') {
				return this.detailData.flashPrice || 0;
			} else {
				return this.detailData.discountPrice || 0;
			}
		},
		btnText() {
			const status = this.detailData.activityStatus;
			switch (status) {
				case 'not_started': 
					let time = this.formatTime(this.detailData.countdown);
					return `即将开抢 ${time.h}:${time.m}:${time.s}`;
				case 'ongoing': return '立即抢购';
				case 'sold_out': return '已售罄';
				case 'ended': return '已结束';
				default: return '抢购';
			}
		},
		sliderImages() {
			// 解析接口中的 sliderImage
			if (this.detailData.sliderImage) {
				if (typeof this.detailData.sliderImage === 'string') {
					return this.detailData.sliderImage.split(',').filter(item => item.trim() !== '');
				} else if (Array.isArray(this.detailData.sliderImage)) {
					return this.detailData.sliderImage;
				}
			}
			// 如果没有 sliderImage，兜底使用 productImage
			return this.detailData.productImage ? [this.detailData.productImage] : [];
		},
		currentSpec() {
			if (this.detailData.specs && this.detailData.specs.length > 0) {
				let spec = this.detailData.specs[this.specIndex];
				if (spec) {
					spec.price = this.activityType === 'flash' ? spec.flashPrice : spec.discountPrice;
					return spec;
				}
			}
			return {};
		}
	},
	onLoad(options) {
		if (options.type) {
			this.activityType = options.type;
			uni.setNavigationBarTitle({
				title: this.activityType === 'flash' ? '秒杀商品详情' : '折扣商品详情'
			});
		}
		if (options.id) {
			this.activityId = options.id;
			this.fetchDetailData();
		}
	},
	onUnload() {
		this.clearTimer();
		this.clearStockPolling();
	},
	onHide() {
		this.clearTimer();
		this.clearStockPolling();
	},
	onShow() {
		// 如果页面重新显示且数据已存在，则重新启动定时器（可选，取决于具体业务需不需要继续跑倒计时）
		if (this.detailData && this.detailData.id) {
			if (!this.timer) this.startTimer();
			if (!this.stockTimer && this.detailData.activityStatus !== 'sold_out' && this.detailData.activityStatus !== 'ended') {
				this.startStockPolling();
			}
		}
	},
	beforeDestroy() {
		this.clearTimer();
		this.clearStockPolling();
	},
	methods: {
		async fetchDetailData() {
			try {
				let detailRes, timeRes;
				
				if (this.activityType === 'flash') {
					[detailRes, timeRes] = await Promise.all([
						getFlashSaleDetail(this.activityId),
						getFlashSaleServerTime()
					]);
				} else {
					[detailRes, timeRes] = await Promise.all([
						getDiscountDetail(this.activityId),
						getDiscountServerTime()
					]);
				}
				
				if (detailRes.code === 0 || detailRes.code === 200) {
					this.detailData = detailRes.data || {};
					
					let currentServerTime = Date.now();
					if (timeRes.code === 0 || timeRes.code === 200) {
						currentServerTime = timeRes.serverTimestamp || timeRes.data?.serverTimestamp || Date.now();
					} else if (detailRes.serverTimestamp) {
						currentServerTime = detailRes.serverTimestamp;
					}
					
					const serverTimeSec = Math.floor(currentServerTime / 1000);
					
					// 重新校准倒计时
					let targetTime = 0;
					if (this.detailData.activityStatus === 'not_started') {
						targetTime = Math.floor(new Date(this.detailData.startTime.replace(/-/g, '/')).getTime() / 1000);
					} else if (this.detailData.activityStatus === 'ongoing') {
						targetTime = Math.floor(new Date(this.detailData.endTime.replace(/-/g, '/')).getTime() / 1000);
					}
					
					if (targetTime > 0) {
						let diff = targetTime - serverTimeSec;
						this.detailData.countdown = diff > 0 ? diff : 0;
					}
					
					this.startTimer();
					this.startStockPolling();
				} else {
					uni.showToast({
						title: detailRes.msg || '获取详情失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('获取详情数据失败', error);
			}
		},
		startTimer() {
			this.clearTimer();
			this.timer = setInterval(() => {
				if (this.detailData.countdown > 0) {
					this.detailData.countdown--;
				} else if (this.detailData.countdown === 0 && this.detailData.activityStatus === 'not_started') {
					this.detailData.activityStatus = 'ongoing';
					let endTimeSec = Math.floor(new Date(this.detailData.endTime.replace(/-/g, '/')).getTime() / 1000);
					let nowSec = Math.floor(Date.now() / 1000);
					let diff = endTimeSec - nowSec;
					this.detailData.countdown = diff > 0 ? diff : 0;
				} else if (this.detailData.countdown === 0 && this.detailData.activityStatus === 'ongoing') {
					this.detailData.activityStatus = 'ended';
					this.clearTimer();
				}
			}, 1000);
		},
		clearTimer() {
			if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			}
		},
		startStockPolling() {
			this.clearStockPolling();
			this.stockTimer = setInterval(async () => {
				try {
					let res;
					if (this.activityType === 'flash') {
						res = await getFlashSaleDetail(this.activityId);
					} else {
						res = await getDiscountDetail(this.activityId);
					}
					
					if (res.code === 0 || res.code === 200) {
						let remainStock = res.data?.remainStock || 0;
						this.detailData.remainStock = remainStock;
						if (remainStock <= 0) {
							this.detailData.activityStatus = 'sold_out';
							this.clearStockPolling();
						}
					}
				} catch (e) {
					console.error('获取实时库存失败', e);
				}
			}, 3000);
		},
		clearStockPolling() {
			if (this.stockTimer) {
				clearInterval(this.stockTimer);
				this.stockTimer = null;
			}
		},
		formatTime(seconds) {
			if (!seconds || seconds <= 0) return { h: '00', m: '00', s: '00' };
			let h = Math.floor(seconds / 3600);
			let m = Math.floor((seconds % 3600) / 60);
			let s = seconds % 60;
			return {
				h: h.toString().padStart(2, '0'),
				m: m.toString().padStart(2, '0'),
				s: s.toString().padStart(2, '0')
			};
		},
		handleBuy() {
			const status = this.detailData.activityStatus;
			
			if (status === 'not_started') {
				uni.showToast({ title: '活动尚未开始，请耐心等待', icon: 'none' });
				return;
			}
			if (status === 'ended') {
				uni.showToast({ title: '抱歉，活动已结束', icon: 'none' });
				return;
			}
			if (status === 'sold_out' || this.detailData.remainStock <= 0) {
				uni.showToast({ title: '活动商品已售罄', icon: 'none' });
				return;
			}
			if (this.detailData.status === 0) {
				uni.showToast({ title: '商品已下架', icon: 'none' });
				return;
			}
			
			// 打开规格选择弹窗
			this.specVisible = true;
		},
		choseSpec(index) {
			this.specIndex = index;
		},
		submitSpec() {
			let stock = this.currentSpec.remainStock !== undefined ? this.currentSpec.remainStock : this.detailData.remainStock;
			if (stock <= 0) {
				uni.showToast({ title: '该规格库存不足', icon: 'none' });
				return;
			}
			
			// 调用加入购物车接口（立即购买模式 isBuy: 1）
			let attrValueId = 0;
			if (this.detailData.specs && this.detailData.specs.length > 0) {
				attrValueId = this.detailData.specs[this.specIndex].specId || this.detailData.specs[this.specIndex].id || 0;
			}

			let data = {
				isBuy: 1,
				cartNum: 1, // 秒杀/折扣强制为1件
				productId: this.detailData.productId,
				attrValueId: attrValueId
			};
			
			uni.showLoading({ title: '加载中' });
			addCart(data).then(res => {
				uni.hideLoading();
				if (res.code === 200) {
					this.specVisible = false; // 关闭弹窗
					let cartIds = res.id;
					let orderType = this.activityType === 'flash' ? 6 : 7;
					// associatedId 为中间表 ID，即 specs 数组里的 id
					let associatedId = this.detailData.specs && this.detailData.specs.length > 0 ? (this.detailData.specs[this.specIndex].id || this.activityId) : this.activityId;
					
					uni.navigateTo({
						url: `/pages/shopping/confirmOrder?type=buy&cartIds=${cartIds}&orderType=${orderType}&activityType=${this.activityType}&productId=${this.detailData.productId}&associatedId=${associatedId}`
					});
				} else {
					uni.showToast({
						icon: 'none',
						title: res.msg || '操作失败'
					});
				}
			}).catch(err => {
				uni.hideLoading();
				console.error(err);
			});
		}
	}
};
</script>

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

.swiper-box {
	width: 100%;
	height: 750rpx;
	
	.slide-image {
		width: 100%;
		height: 100%;
		background-color: #fff;
	}
}

.price-section {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 30rpx;
	color: #fff;
	
	&.flash {
		background: linear-gradient(90deg, #ff6000, #ff4a00);
	}
	
	&.discount {
		background: linear-gradient(90deg, #b835c9, #9c26b0);
	}
	
	.price-info {
		display: flex;
		align-items: baseline;
		
		.activity-price {
			font-size: 48rpx;
			font-weight: bold;
			margin-right: 20rpx;
			
			.unit {
				font-size: 32rpx;
			}
		}
		
		.original-price {
			font-size: 26rpx;
			text-decoration: line-through;
			opacity: 0.8;
		}
	}
	
	.countdown-info {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		
		.countdown-title {
			font-size: 24rpx;
			margin-bottom: 8rpx;
		}
		
		.countdown-time {
			display: flex;
			align-items: center;
			
			.time-block {
				background-color: rgba(255, 255, 255, 0.2);
				color: #fff;
				font-size: 24rpx;
				padding: 4rpx 8rpx;
				border-radius: 6rpx;
			}
			
			.colon {
				margin: 0 6rpx;
				font-weight: bold;
			}
		}
	}
}

.base-info {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
	
	.title {
		font-size: 32rpx;
		color: #333;
		font-weight: bold;
		line-height: 44rpx;
		margin-bottom: 20rpx;
	}
	
	.sub-info {
		display: flex;
		justify-content: space-between;
		font-size: 24rpx;
		color: #999;
	}
}

.product-detail {
	background-color: #fff;
	padding: 30rpx;
	
	.detail-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
		border-left: 6rpx solid #ff4a00;
		padding-left: 16rpx;
	}
	
	.detail-content {
		font-size: 28rpx;
		color: #666;
		line-height: 1.6;
		
		img {
			max-width: 100%;
		}
	}
}

.bottom-action {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 100rpx;
	background-color: #fff;
	display: flex;
	align-items: center;
	padding: 0 30rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	z-index: 99;
	
	.btn-group {
		flex: 1;
		
		.action-btn {
			width: 100%;
			height: 80rpx;
			line-height: 80rpx;
			border-radius: 40rpx;
			font-size: 30rpx;
			color: #fff;
			border: none;
			
			&::after {
				display: none;
			}
			
			&.flash {
				background: linear-gradient(90deg, #ff6000, #ff4a00);
			}
			
			&.discount {
				background: linear-gradient(90deg, #b835c9, #9c26b0);
			}
			
			&.disabled {
				background: #cccccc;
			}
		}
	}
}

.product-spec {
	padding: 30rpx;
	background: #fff;
	border-radius: 32rpx 32rpx 0 0;
	
	.pro-info {
		display: flex;
		align-items: center;
		padding-bottom: 30rpx;
		border-bottom: 1rpx solid #f5f5f5;
		
		.img-box {
			width: 160rpx;
			height: 160rpx;
			background: #f8f8f8;
			border-radius: 12rpx;
			margin-right: 20rpx;
			overflow: hidden;
			
			image {
				width: 100%;
				height: 100%;
			}
		}
		
		.info-text {
			display: flex;
			flex-direction: column;
			justify-content: space-around;
			height: 140rpx;
			
			.price {
				display: flex;
				align-items: baseline;
				color: #ff4a00;
				
				.unit {
					font-size: 24rpx;
				}
				.num {
					font-size: 40rpx;
					font-weight: bold;
				}
			}
			
			.desc-box {
				display: flex;
				flex-direction: column;
				
				.text {
					font-size: 24rpx;
					color: #999;
					margin-top: 8rpx;
				}
			}
		}
	}
	
	.spec-box {
		padding: 30rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
		
		.title {
			font-size: 28rpx;
			color: #333;
			font-weight: bold;
			margin-bottom: 20rpx;
		}
		
		.spec-list {
			display: flex;
			flex-wrap: wrap;
			
			.item {
				padding: 10rpx 30rpx;
				background: #f5f5f5;
				color: #333;
				font-size: 26rpx;
				border-radius: 30rpx;
				margin-right: 20rpx;
				margin-bottom: 20rpx;
				border: 1rpx solid transparent;
				
				&.active {
					background: rgba(255, 74, 0, 0.1);
					color: #ff4a00;
					border-color: #ff4a00;
				}
			}
		}
	}
	
	.price-num {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx 0 50rpx 0;
		
		.label {
			font-size: 28rpx;
			color: #333;
			font-weight: bold;
		}
		
		.num-box {
			display: flex;
			align-items: center;
			
			.img-box {
				width: 50rpx;
				height: 50rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				background: #f5f5f5;
				border-radius: 6rpx;
				
				image {
					width: 24rpx;
					height: 24rpx;
				}
			}
			
			input {
				width: 80rpx;
				text-align: center;
				font-size: 28rpx;
				color: #333;
			}
		}
	}
	
	.sub-btn {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		background: linear-gradient(90deg, #ff6000, #ff4a00);
		color: #fff;
		border-radius: 40rpx;
		font-size: 30rpx;
		margin-bottom: 20rpx;
	}
}
</style>