<template>
	<view class="credits_sale_section" v-if="shouldShowSection">
		<!-- 标题区域 -->
		<view class="credits_sale_area">
			<text class="credits_sale_title">积分限时购</text>
		</view>

		<!-- 积分限时购内容容器 -->
		<view class="credits_sale_container">

			<!-- 场次Tab切换区域 -->
			<view class="credits_sale_tabs" 
				v-if="creditsSaleData.sessions && creditsSaleData.sessions.length > 1"
				:class="getTabContainerClass">
				<view v-for="(session, index) in creditsSaleData.sessions || []" :key="index" class="tab_item"
					:class="{ active: index === currentSessionIndex }" @click="currentSessionIndex = index">
					<!-- 正在秒杀状态：倒计时在上，文案在下 -->
					<view v-if="session.status === 'ongoing'" class="tab_content_ongoing">
						<view class="tab_time_info">
							<view class="tab_time_text countdown_display">
								<view class="countdown_numbers">
									<view v-for="(timeUnit, index) in getCountdownUnits(session.countdown)" 
										:key="index" 
										class="countdown_unit">
										<text class="countdown_number">{{ timeUnit }}</text>
										<text v-if="index < 2" class="countdown_colon">:</text>
									</view>
								</view>
							</view>
						</view>
						<view class="session_status_tag ongoing">
							<text class="status_text">正在秒杀</text>
						</view>
					</view>
					<!-- 即将开始/已过期状态：开始时间在上，状态文案在下 -->
					<view v-else class="tab_content_other">
						<view class="tab_time_info">
							<text class="tab_time_text start_time_text">{{ getStartTime(session) }}</text>
						</view>
						<view class="session_status_tag" :class="session.status">
							<text v-if="session.status === 'upcoming'" class="status_text upcoming_text">即将开始</text>
							<text v-else class="status_text ended_text">已结束</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 单场次状态显示 -->
			<view class="single_session_status" v-else-if="creditsSaleData.sessions && creditsSaleData.sessions.length === 1">
				<view class="session_status_tag" :class="creditsSaleData.sessions[0].status">
					<text v-if="creditsSaleData.sessions[0].status === 'ongoing'" class="status_text">正在秒杀</text>
					<text v-else-if="creditsSaleData.sessions[0].status === 'upcoming'" class="status_text upcoming_text">即将开始</text>
					<text v-else class="status_text ended_text">已结束</text>
				</view>
				<view class="tab_time_info">
					<view v-if="creditsSaleData.sessions[0].status === 'ongoing'" class="tab_time_text countdown_display">
						<text class="countdown_label">倒计时</text>
						<view class="countdown_numbers">
							<view v-for="(timeUnit, index) in getCountdownUnits(creditsSaleData.sessions[0].countdown)" 
								:key="index" 
								class="countdown_unit">
								<text class="countdown_number">{{ timeUnit }}</text>
								<text v-if="index < 2" class="countdown_colon">:</text>
							</view>
						</view>
					</view>
					<text v-else class="tab_time_text start_time_text">{{ getStartTime(creditsSaleData.sessions[0]) }}</text>
				</view>
			</view>

			<!-- 当前选中场次的商品展示区域 -->
			<view class="current_session_content"
				v-if="creditsSaleData.sessions && creditsSaleData.sessions[currentSessionIndex]">

				<!-- 场次商品列表 - 根据商品数量动态调整布局 -->
				<view class="session_goods_list"
					:class="getGoodsListClass()">
					<view v-for="(good, goodIndex) in creditsSaleData.sessions[currentSessionIndex]?.goods || []"
						:key="goodIndex" class="credits_sale_good_item">
						<!-- 商品图片 -->
						<view class="good_image_placeholder">
							<image v-if="good.image" :src="good.image" mode="aspectFill" class="good_image" />
						</view>
						<!-- 商品信息容器 -->
						<view class="good_info_container">
							<!-- 商品信息 -->
							<text class="good_name">{{ good.name }}</text>
							<!-- 积分价格 -->
							<view class="good_price_container">
								<text class="good_price">{{ good.points }}积分</text>
								<text class="good_original_price"
									v-if="good.originalPoints && good.originalPoints !== good.points">{{
										good.originalPoints }}积分</text>
							</view>
							<!-- 立即抢购按钮 -->
							<view class="credits_sale_button" 
								:class="{ disabled: getGoodButtonInfo(good, creditsSaleData.sessions[currentSessionIndex]).disabled }"
								@click="!getGoodButtonInfo(good, creditsSaleData.sessions[currentSessionIndex]).disabled && handleCreditsSaleClickThrottled(good)">
								<text class="credits_sale_button_text">{{ getGoodButtonInfo(good, creditsSaleData.sessions[currentSessionIndex]).text }}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useIntegralStore } from '../stores/integral';
import { throttleTap } from '../utils/index';

// Props
const props = defineProps({
	isdebug: {
		type: Boolean,
		default: false
	}
});

// Emits
const emit = defineEmits(['credits-sale-click']);

// Store
const integralStore = useIntegralStore();

// 积分限时购数据 - 秒杀场次
const creditsSaleData = ref({
	sessions: []
});

// 积分限时购相关数据
const currentSessionIndex = ref(0); // 当前选中的场次索引

// 倒计时相关
const countdownTimers = ref({}); // 存储每个场次的倒计时定时器

// 格式化倒计时显示
const formatCountdown = (timeStr) => {
	// 如果是字符串，直接返回
	if (typeof timeStr === 'string') {
		return timeStr || '00:00:00';
	}
	// 如果是数字（秒数），转换为时分秒格式
	if (typeof timeStr === 'number') {
		const hours = Math.floor(timeStr / 3600);
		const minutes = Math.floor((timeStr % 3600) / 60);
		const secs = timeStr % 60;
		return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
	}
	return '00:00:00';
};

// 获取倒计时时间单位数组
const getCountdownUnits = (timeStr) => {
	const formatted = formatCountdown(timeStr);
	return formatted.split(':');
};

// 获取开始时间（时分格式）
const getStartTime = (session) => {
	if (!session || !session.timeTags || session.timeTags.length === 0) {
		return '';
	}
	// 从 timeTags 中提取时间，格式如 "18:00开始"
	// 需要找到包含时间格式的标签（如 "08:00开始"），而不是状态文案（如 "即将开始"）
	const timeTag = session.timeTags.find(tag => tag.includes('开始') && /^\d{2}:\d{2}开始$/.test(tag));
	if (timeTag) {
		// 提取时间部分，去掉"开始"文字
		return timeTag.replace('开始', '');
	}
	return '';
};

// 获取商品按钮文案和状态
const getGoodButtonInfo = (good, session) => {
	if (!session || !good) {
		return { text: '立即秒杀', disabled: false };
	}

	const { status } = session;
	const { stock } = good;

	// 未开始场次
	if (status === 'upcoming') {
		return { text: '即将开始', disabled: true };
	}

	// 已结束场次
	if (status === 'ended') {
		return { text: '已结束', disabled: true };
	}

	// 进行中场次
	if (status === 'ongoing') {
		if (stock > 0) {
			return { text: '立即秒杀', disabled: false };
		} else {
			return { text: '已抢完', disabled: true };
		}
	}

	// 默认情况
	return { text: '立即秒杀', disabled: false };
};

// 判断是否应该显示整个section
const shouldShowSection = computed(() => {
	// 检查是否有有效的秒杀数据
	const hasSessions = creditsSaleData.value && creditsSaleData.value.sessions && creditsSaleData.value.sessions.length > 0;
	
	// console.log('shouldShowSection 检查:', {
	// 	hasSessions,
	// 	sessionsLength: creditsSaleData.value?.sessions?.length || 0,
	// 	creditsSaleData: creditsSaleData.value
	// });
	
	return hasSessions;
});

// 获取Tab容器类名 - 使用计算属性
const getTabContainerClass = computed(() => {
	const sessionCount = creditsSaleData.value.sessions?.length || 0;
	if (sessionCount === 2) {
		return 'session_count_2';
	} else if (sessionCount >= 3) {
		return 'session_count_3_plus';
	}
	return '';
});

// 获取商品列表类名
const getGoodsListClass = () => {
	const goodsCount = creditsSaleData.value.sessions[currentSessionIndex.value]?.goods?.length || 0;
	if (goodsCount === 1) {
		return 'goods_count_1';
	} else if (goodsCount === 2) {
		return 'goods_count_2';
	} else if (goodsCount >= 3) {
		return 'goods_count_3_plus';
	}
	return '';
};

// 智能定位场次索引
const getTargetSessionIndex = (sessions) => {
	if (!sessions || sessions.length === 0) return 0;
	
	// 1. 有正在秒杀的就定位到正在秒杀的场次
	const ongoingSessions = sessions.filter(session => session.status === 'ongoing');
	if (ongoingSessions.length > 0) {
		// 如果有多个正在秒杀的场次，选择开始时间最早的
		const earliestOngoingSession = ongoingSessions.reduce((earliest, current) => {
			const getStartTimeFromTags = (session) => {
				const timeTag = session.timeTags.find(tag => tag.includes('开始') && /^\d{2}:\d{2}开始$/.test(tag));
				if (timeTag) {
					const timeStr = timeTag.replace('开始', '');
					const [hours, minutes] = timeStr.split(':').map(Number);
					return hours * 60 + minutes;
				}
				return 0;
			};
			return getStartTimeFromTags(current) < getStartTimeFromTags(earliest) ? current : earliest;
		});
		return sessions.findIndex(session => session.id === earliestOngoingSession.id);
	}
	
	// 2. 只有已结束和未开始时定位到即将开始的场次
	const upcomingSessions = sessions.filter(session => session.status === 'upcoming');
	if (upcomingSessions.length > 0) {
		// 选择开始时间最早的即将开始的场次
		const earliestUpcomingSession = upcomingSessions.reduce((earliest, current) => {
			const getStartTimeFromTags = (session) => {
				const timeTag = session.timeTags.find(tag => tag.includes('开始') && /^\d{2}:\d{2}开始$/.test(tag));
				if (timeTag) {
					const timeStr = timeTag.replace('开始', '');
					const [hours, minutes] = timeStr.split(':').map(Number);
					return hours * 60 + minutes;
				}
				return 0;
			};
			return getStartTimeFromTags(current) < getStartTimeFromTags(earliest) ? current : earliest;
		});
		return sessions.findIndex(session => session.id === earliestUpcomingSession.id);
	}
	
	// 3. 全部结束定位到最后一个场次
	const allEnded = sessions.every(session => session.status === 'ended');
	if (allEnded) {
		return sessions.length - 1;
	}
	
	// 4. 所有场次未开始时定位到第一个场次
	return 0;
};

// 开始倒计时
const startCountdown = (sessionId, initialSeconds) => {
	if (countdownTimers.value[sessionId]) {
		clearInterval(countdownTimers.value[sessionId]);
	}

	let seconds = initialSeconds;
	countdownTimers.value[sessionId] = setInterval(() => {
		seconds--;
		if (seconds <= 0) {
			clearInterval(countdownTimers.value[sessionId]);
			// 倒计时结束，自动切换到下一场
			handleCountdownEnd(sessionId);
		}
		// 更新对应场次的倒计时数据
		const session = creditsSaleData.value.sessions.find(s => s.id === sessionId);
		if (session) {
			session.countdown = formatCountdown(seconds);
		}
	}, 1000);
};

// 处理倒计时结束
const handleCountdownEnd = (endedSessionId) => {
	const sessions = creditsSaleData.value.sessions;
	const currentIndex = sessions.findIndex(s => s.id === endedSessionId);
	const endedSession = sessions[currentIndex];
	
	// 如果当前场次是"即将开始"状态，转换为"正在秒杀"
	if (endedSession && endedSession.status === 'upcoming') {
		// 更新场次状态为正在秒杀
		endedSession.status = 'ongoing';
		
		// 重新计算结束时间倒计时
		const now = new Date();
		const endTime = new Date(endedSession.endTime);
		const remainingMs = endTime.getTime() - now.getTime();
		
		if (remainingMs > 0) {
			const hours = Math.floor(remainingMs / (1000 * 60 * 60));
			const minutes = Math.floor((remainingMs % (1000 * 60 * 60)) / (1000 * 60));
			const seconds = Math.floor((remainingMs % (1000 * 60)) / 1000);
			const totalSeconds = hours * 3600 + minutes * 60 + seconds;
			
			// 更新倒计时显示
			endedSession.countdown = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
			
			// 重新启动倒计时
			if (totalSeconds > 0) {
				startCountdown(endedSessionId, totalSeconds);
			}
			
			console.log('场次开始，状态转换为正在秒杀:', endedSession);
		}
	} else if (endedSession && endedSession.status === 'ongoing') {
		// 正在秒杀场次结束，标记为已结束
		endedSession.status = 'ended';
		
		// 如果当前场次不是最后一场，切换到下一场
		if (currentIndex < sessions.length - 1) {
			const nextSession = sessions[currentIndex + 1];
			// 检查下一场是否已经开始或即将开始
			if (nextSession.status === 'ongoing' || nextSession.status === 'upcoming') {
				currentSessionIndex.value = currentIndex + 1;
				console.log('自动切换到下一场:', nextSession);
			}
		}
	}
};

// 初始化倒计时
const initCountdowns = () => {
	if (creditsSaleData.value.sessions && Array.isArray(creditsSaleData.value.sessions)) {
		// 检查是否全部结束
		const allEnded = creditsSaleData.value.sessions.every(session => session.status === 'ended');
		if (allEnded) {
			return; // 全部结束，不需要倒计时
		}
		
		// 其他情况都需要倒计时
		creditsSaleData.value.sessions.forEach(session => {
			if (session.status === 'ongoing' || session.status === 'upcoming') {
				// 将倒计时字符串转换为秒数
				const timeParts = session.countdown.split(':');
				const hours = parseInt(timeParts[0]) || 0;
				const minutes = parseInt(timeParts[1]) || 0;
				const secs = parseInt(timeParts[2]) || 0;
				const totalSeconds = hours * 3600 + minutes * 60 + secs;
				
				if (totalSeconds > 0) {
					startCountdown(session.id, totalSeconds);
				}
			}
		});
	}
};

// 将接口数据映射到 creditsSaleData 结构
const mapSeckillDataToCreditsSale = (seckillData) => {
	console.log('原始接口数据:', seckillData);
	
	if (!seckillData || !seckillData.data || !seckillData.data.configs) {
		console.log('接口数据格式错误');
		return;
	}
	
	// 保存活动ID
	creditsSaleData.value.activityId = seckillData.data.id;
	
	console.log('开始处理接口数据，configs长度:', seckillData.data.configs.length);

	const sessions = seckillData.data.configs.map((config, index) => {
		// 判断场次状态
		const now = new Date();
		const startTime = new Date(config.start);
		const endTime = new Date(config.end);
		
		console.log('时间判断调试:', {
			now: now.toLocaleString(),
			startTime: startTime.toLocaleString(),
			endTime: endTime.toLocaleString(),
			nowTime: now.getTime(),
			startTimeStamp: config.start,
			endTimeStamp: config.end
		});

		let status = 'upcoming';
		let countdown = '00:00:00';

		if (now >= startTime && now <= endTime) {
			status = 'ongoing';
			// 计算剩余时间
			const remainingMs = endTime.getTime() - now.getTime();
			const hours = Math.floor(remainingMs / (1000 * 60 * 60));
			const minutes = Math.floor((remainingMs % (1000 * 60 * 60)) / (1000 * 60));
			const seconds = Math.floor((remainingMs % (1000 * 60)) / 1000);
			countdown = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
		} else if (now < startTime) {
			status = 'upcoming';
			// 计算开始倒计时
			const remainingMs = startTime.getTime() - now.getTime();
			const hours = Math.floor(remainingMs / (1000 * 60 * 60));
			const minutes = Math.floor((remainingMs % (1000 * 60 * 60)) / (1000 * 60));
			const seconds = Math.floor((remainingMs % (1000 * 60)) / 1000);
			countdown = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
		} else {
			// 已结束
			status = 'ended';
			countdown = '00:00:00';
		}

		// 格式化时间标签 - 使用24小时制
		const startTimeStr = `${startTime.getHours().toString().padStart(2, '0')}:${startTime.getMinutes().toString().padStart(2, '0')}`;
		const endTimeStr = `${endTime.getHours().toString().padStart(2, '0')}:${endTime.getMinutes().toString().padStart(2, '0')}`;

		const timeTags = status === 'ongoing'
			? ['正在秒杀', `${startTimeStr}开始`, `${endTimeStr}结束`]
			: status === 'ended'
			? ['已结束', `${startTimeStr}开始`]
			: ['即将开始', `${startTimeStr}开始`];

		// 映射商品数据 - 根据实际接口数据结构
		const goods = config.goods.map((good, goodIndex) => {
			console.log('处理商品数据:', good);
			return {
				id: good.goods?.id || `good_${index}_${goodIndex}`,
				name: good.goods?.goodsName || '商品名称',
				points: good.credits || 0,
				originalPoints: good.goods?.priceSale || good.priceSale || 0,
				image: (good.goods?.goodsImage && good.goods.goodsImage.length > 0) ? good.goods.goodsImage[0] : '',
				stock: good.stock || 0,
				buttonText: good.button?.text || '立即秒杀'
			};
		});

		return {
			id: index + 1,
			status,
			countdown,
			timeTags,
			goods,
			sessionKey: config.sessionKey,
			startTime: config.start,
			endTime: config.end
		};
	});

	// 按开始时间从早到晚排序
	sessions.sort((a, b) => {
		// 从timeTags中提取开始时间进行比较
		const getStartTimeFromTags = (session) => {
			const timeTag = session.timeTags.find(tag => tag.includes('开始') && /^\d{2}:\d{2}开始$/.test(tag));
			if (timeTag) {
				const timeStr = timeTag.replace('开始', '');
				const [hours, minutes] = timeStr.split(':').map(Number);
				return hours * 60 + minutes; // 转换为分钟数进行比较
			}
			return 0;
		};
		
		return getStartTimeFromTags(a) - getStartTimeFromTags(b);
	});

	creditsSaleData.value.sessions = sessions;
	
	// 智能定位场次逻辑
	const targetIndex = getTargetSessionIndex(sessions);
	currentSessionIndex.value = targetIndex;
	
	console.log('映射后的秒杀数据:', creditsSaleData.value);
	console.log('当前选中场次索引:', currentSessionIndex.value);
};

// 处理积分抢购点击事件
const handleCreditsSaleClick = (good) => {
	console.log('点击抢购商品:', good);
	// 获取当前活动ID和场次Key
	const activityId = creditsSaleData.value.activityId;
	const sessionKey = creditsSaleData.value.sessions[currentSessionIndex.value]?.sessionKey;
	emit('credits-sale-click', { good, activityId, sessionKey });
};

// 创建防连点的点击处理函数
const handleCreditsSaleClickThrottled = throttleTap(handleCreditsSaleClick, 1000);

// 生成测试数据
const generateTestSeckillData = () => {
	const now = new Date();
	const baseTime = now.getTime();
	
	// 第一场：已结束（2小时前开始，1小时前结束）
	const session1Start = baseTime - 2 * 60 * 60 * 1000; // 2小时前
	const session1End = baseTime - 1 * 60 * 60 * 1000;   // 1小时前
	
	// 第二场：已结束（1小时前开始，30分钟前结束）
	const session2Start = baseTime - 1 * 60 * 60 * 1000; // 1小时前
	const session2End = baseTime - 30 * 60 * 1000;       // 30分钟前
	
	// 第三场：即将开始（20秒后开始，30秒后结束）
	const session3Start = baseTime + 20 * 1000; // 20秒后
	const session3End = baseTime + 30 * 1000;   // 30秒后

	// 第四场：即将开始（40分钟后开始，50分钟后结束）
	const session4Start = baseTime + 40 * 60 * 1000; // 40分钟后
	const session4End = baseTime + 50 * 60 * 1000;  // 50分钟后
	
	return {
		"code": "000000",
		"data": {
			"activityTime": baseTime,
			"configs": [
				{
					"end": session1End,
					"goods": [
						{
							"button": {"key": 1, "text": "立即抢购"},
							"credits": 100,
							"creditsType": "CREDITS",
							"creditsTypeName": "积分",
							"goods": {
								"id": 101,
								"goodsName": "测试商品A - 正在进行中",
								"goodsImage": ["https://via.placeholder.com/150/FF6B35/FFFFFF?text=GoodA"],
								"credits": "100",
								"priceSale": "200.00",
								"stock": 10
							},
							"priceSale": "200.00",
							"stock": 10
						},
						{
							"button": {"key": 1, "text": "立即抢购"},
							"credits": 150,
							"creditsType": "CREDITS",
							"creditsTypeName": "积分",
							"goods": {
								"id": 102,
								"goodsName": "测试商品B - 正在进行中",
								"goodsImage": ["https://via.placeholder.com/150/4CAF50/FFFFFF?text=GoodB"],
								"credits": "150",
								"priceSale": "300.00",
								"stock": 5
							},
							"priceSale": "300.00",
							"stock": 5
						}
					],
					"sessionKey": "session_1_ongoing",
					"start": session1Start
				},
				{
					"end": session2End,
					"goods": [
						{
							"button": {"key": 2, "text": "即将开始"},
							"credits": 200,
							"creditsType": "CREDITS",
							"creditsTypeName": "积分",
							"goods": {
								"id": 201,
								"goodsName": "测试商品C - 即将开始",
								"goodsImage": ["https://via.placeholder.com/150/2196F3/FFFFFF?text=GoodC"],
								"credits": "200",
								"priceSale": "400.00",
								"stock": 8
							},
							"priceSale": "400.00",
							"stock": 8
						}
					],
					"sessionKey": "session_2_upcoming",
					"start": session2Start
				},
				{
					"end": session3End,
					"goods": [
						{
							"button": {"key": 2, "text": "即将开始"},
							"credits": 300,
							"creditsType": "CREDITS",
							"creditsTypeName": "积分",
							"goods": {
								"id": 301,
								"goodsName": "测试商品D - 即将开始",
								"goodsImage": ["https://via.placeholder.com/150/9C27B0/FFFFFF?text=GoodD"],
								"credits": "300",
								"priceSale": "600.00",
								"stock": 3
							},
							"priceSale": "600.00",
							"stock": 3
						},
						{
							"button": {"key": 2, "text": "即将开始"},
							"credits": 250,
							"creditsType": "CREDITS",
							"creditsTypeName": "积分",
							"goods": {
								"id": 302,
								"goodsName": "测试商品E - 即将开始",
								"goodsImage": ["https://via.placeholder.com/150/FF9800/FFFFFF?text=GoodE"],
								"credits": "250",
								"priceSale": "500.00",
								"stock": 6
							},
							"priceSale": "500.00",
							"stock": 6
						},
						{
							"button": {"key": 2, "text": "即将开始"},
							"credits": 180,
							"creditsType": "CREDITS",
							"creditsTypeName": "积分",
							"goods": {
								"id": 303,
								"goodsName": "测试商品F - 即将开始",
								"goodsImage": ["https://via.placeholder.com/150/795548/FFFFFF?text=GoodF"],
								"credits": "180",
								"priceSale": "360.00",
								"stock": 12
							},
							"priceSale": "360.00",
							"stock": 12
						}
					],
					"sessionKey": "session_3_upcoming",
					"start": session3Start
				},
				{
					"end": session4End,
					"goods": [
						{
							"button": {"key": 2, "text": "即将开始"},
							"credits": 300,
							"creditsType": "CREDITS",
							"creditsTypeName": "积分",
							"goods": {
								"id": 301,
								"goodsName": "测试商品D - 即将开始",
								"goodsImage": ["https://via.placeholder.com/150/9C27B0/FFFFFF?text=GoodD"],
								"credits": "300",
								"priceSale": "600.00",
								"stock": 3
							},
							"priceSale": "600.00",
							"stock": 3
						},
						{
							"button": {"key": 2, "text": "即将开始"},
							"credits": 250,
							"creditsType": "CREDITS",
							"creditsTypeName": "积分",
							"goods": {
								"id": 302,
								"goodsName": "测试商品E - 即将开始",
								"goodsImage": ["https://via.placeholder.com/150/FF9800/FFFFFF?text=GoodE"],
								"credits": "250",
								"priceSale": "500.00",
								"stock": 6
							},
							"priceSale": "500.00",
							"stock": 6
						},
						{
							"button": {"key": 2, "text": "即将开始"},
							"credits": 180,
							"creditsType": "CREDITS",
							"creditsTypeName": "积分",
							"goods": {
								"id": 303,
								"goodsName": "测试商品F - 即将开始",
								"goodsImage": ["https://via.placeholder.com/150/795548/FFFFFF?text=GoodF"],
								"credits": "180",
								"priceSale": "360.00",
								"stock": 12
							},
							"priceSale": "360.00",
							"stock": 12
						}
					],
					"sessionKey": "session_3_upcoming",
					"start": session4Start
				}
			],
			"id": 1141,
			"name": "测试秒杀",
			"state": 1
		},
		"message": "success",
		"ok": true,
		"success": true
	};
};

// 获取秒杀数据
const loadSeckillData = async () => {
	try {
		// 使用测试数据
		// const testData = generateTestSeckillData();
		// mapSeckillDataToCreditsSale(testData);
		// // // 初始化倒计时
		// initCountdowns();
		
		// 如果需要真实数据，可以取消注释下面的代码
		const seckillData = await integralStore.getSeckillData(props.isdebug);
		if (seckillData) {
			mapSeckillDataToCreditsSale(seckillData);
			// 初始化倒计时
			initCountdowns();
		}
	} catch (error) {
		console.error('获取秒杀数据失败:', error);
	}
};

// 暴露方法给父组件
defineExpose({
	loadSeckillData
});

// 组件挂载时加载数据
onMounted(() => {
	loadSeckillData();
});
</script>

<style lang="less" scoped>
@import './SeckillSection.less';
</style>
