<template>
	<view class="credits_sale_section" v-if="shouldShowSection">
		<!-- 标题区域 -->
		<view class="credits_sale_area">
			<text class="credits_sale_title" :class="`item-${itemIndex}`" :style="{ color: getColor('textColor')[itemIndex] }">积分限时秒杀</text>
		</view>

	<!-- 积分限时购内容容器 -->
	<view class="credits_sale_container" :class="`item-${itemIndex}`" :style="{ backgroundColor: getColor('bgColor')[itemIndex] }">

			<!-- 场次Tab切换区域 -->
			<view class="credits_sale_tabs" 
				v-if="creditsSaleData.sessions && creditsSaleData.sessions.length > 1"
				:class="getTabContainerClass"
				:style="{ backgroundColor: getColor('tabsColor')[itemIndex] }">
				<view v-for="(session, index) in creditsSaleData.sessions || []" :key="index" class="tab_item"
					:class="[`item-${itemIndex}`, { active: index === currentSessionIndex }]" @click="currentSessionIndex = index">
					<!-- 背景色元素 - 只在active状态下显示 -->
					<view v-if="index === currentSessionIndex" class="tab_bg_element" :style="{ left: index > 0 ? '50rpx' : '0', right: index < creditsSaleData.sessions.length - 1 ? '50rpx' : '0', backgroundColor: getColor('bgColor')[itemIndex] }"></view>
					<!-- 左侧弧形三角形 - 使用base64 SVG，第一个tab不显示 -->
					<view v-if="index === currentSessionIndex && index > 0" class="triangle-left" :style="{ backgroundImage: getTriangleLeftSvg(itemIndex) }"></view>
					<!-- 右侧弧形三角形 - 使用base64 SVG，最后一个tab不显示 -->
					<view v-if="index === currentSessionIndex && index < creditsSaleData.sessions.length - 1" class="triangle-right" :style="{ backgroundImage: getTriangleRightSvg(itemIndex) }"></view>
					<!-- 正在秒杀状态：倒计时在上，文案在下 -->
					<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" :style="{ backgroundColor: getColor('countdownColor')[itemIndex] }">{{ timeUnit }}</text>
										<text v-if="index < 2" class="countdown_colon" :style="{ color: getColor('countdownColor')[itemIndex] }">:</text>
									</view>
								</view>
							</view>
						</view>
						<view class="session_status_tag ongoing">
							<text class="status_text" :style="{ color: getColor('ongoingStatusTextColor')[itemIndex] }">正在秒杀</text>
						</view>
					</view>
					<!-- 即将开始/已过期状态：开始时间在上，状态文案在下 -->
					<view v-else class="tab_content_other">
						<view class="tab_time_info">
							<text class="tab_time_text start_time_text" :style="{ color: getColor('statusTextColor')[itemIndex] }">{{ getStartTime(session) }}</text>
						</view>
						<view class="session_status_tag" :class="session.status">
							<text v-if="session.status === 'upcoming'" class="status_text upcoming_text" :style="{ color: getColor('statusTextColor')[itemIndex] }">即将开始</text>
							<text v-else class="status_text ended_text" :style="{ color: getColor('statusTextColor')[itemIndex] }">已结束</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" :style="{ color: getColor('ongoingStatusTextColor')[itemIndex] }">正在秒杀</text>
					<text v-else-if="creditsSaleData.sessions[0].status === 'upcoming'" class="status_text upcoming_text" :style="{ color: getColor('statusTextColor')[itemIndex] }">即将开始</text>
					<text v-else class="status_text ended_text" :style="{ color: getColor('statusTextColor')[itemIndex] }">已结束</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" :style="{ backgroundColor: getColor('countdownColor')[itemIndex] }">{{ timeUnit }}</text>
								<text v-if="index < 2" class="countdown_colon" :style="{ color: getColor('countdownColor')[itemIndex] }">:</text>
							</view>
						</view>
					</view>
					<text v-else class="tab_time_text start_time_text" :style="{ color: getColor('statusTextColor')[itemIndex] }">{{ getStartTime(creditsSaleData.sessions[0]) }}</text>
				</view>
			</view>

			<!-- 当前选中场次的商品展示区域 -->
			<view class="current_session_content"
				:class="`item-${itemIndex}`"
				:style="{ backgroundColor: getColor('bgColor')[itemIndex] }"
				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"
						@click="!getGoodButtonInfo(good, creditsSaleData.sessions[currentSessionIndex]).disabled && handleCreditsSaleClickThrottled(good)">
						<!-- 商品图片 -->
						<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" :style="{ color: getColor('goodNameColor')[itemIndex] }">{{ good.name }}</text>
							<!-- 积分价格 -->
							<view class="good_price_container">
								<text class="good_price" :style="{ color: getColor('goodPriceColor')[itemIndex] }">{{ 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="[`item-${itemIndex}`, { disabled: getGoodButtonInfo(good, creditsSaleData.sessions[currentSessionIndex]).disabled }]"
								:style="{ background: getGoodButtonInfo(good, creditsSaleData.sessions[currentSessionIndex]).disabled ? '#B9B9B9' : getColor('buttonGradientColor')[itemIndex] }">
								<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
	},
	itemIndex: {
		type: Number,
		default: 0
	}
});

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

// Store
const integralStore = useIntegralStore();

// 皮肤颜色配置 - 从Integral页面复用的颜色系统
const getColor = (type) => {
	let colors = '';
	switch (type) {
		case 'bgColor':
			colors = ['#EDE8D6', '#d6e8f7', '#eeeaf3', '#f2e9c7', '#49443f'];
			break;
		case 'textColor':
			colors = ['#000000', '#000000', '#000000', '#000000', '#fbf0e1'];
			break;
		case 'tabsColor':
			// Tab切换区域背景色
			colors = ['#e5d5b0', '#a9cce8', '#d7c9ee', '#e6d7a5', '#2b221d'];
			break;
		case 'statusTextColor':
			// 状态文字和时间文字颜色
			colors = ['#503404', '#284a6c', '#322d6f', '#513403', '#f7d1a0'];
			break;
		case 'goodPriceColor':
			// 商品价格颜色
			colors = ['#a57e35', '#354a69', '#342e6b', '#754b20', '#eae3be'];
			break;
		case 'countdownColor':
			// 倒计时数字背景色和冒号颜色
			colors = ['#a57e35', '#6c8dbf', '#7059a3', '#c3a574', '#030201'];
			break;
		case 'ongoingStatusTextColor':
			// 正在秒杀状态文字颜色
			colors = ['#1c1c1c', '#1c1c1c', '#1c1c1c', '#1c1c1c', '#fbf0e1'];
			break;
		case 'buttonGradientColor':
			// 按钮渐变背景色
			colors = [
				'linear-gradient(90deg, #916633 0%, #AB7A44 100%)',
				'linear-gradient(90deg, #5089C1 0%, #6FA2D5 100%)',
				'linear-gradient(90deg, #7253A5 0%, #9879CC 100%)',
				'linear-gradient(90deg, #CDA36B 0%, #E0B97D 100%)',
				'linear-gradient(90deg, #000000 0%, #2C1500 100%)'
			];
			break;
		case 'goodNameColor':
			// 商品名称颜色
			colors = ['#3c3c3c', '#3c3c3c', '#3c3c3c', '#3c3c3c', '#fbf0e1'];
			break;
	}
	return colors;
};

// 生成左侧三角形SVG的URL编码
const getTriangleLeftSvg = (itemIndex) => {
	const color = getColor('bgColor')[itemIndex];
	// 使用原始路径数据，只调整SVG尺寸
	const svg = `<svg width="50" height="60" viewBox="0 0 43.51 52" xmlns="http://www.w3.org/2000/svg">
		<path d="M43.51 0 C37.14 0 31.37 3.79061 28.836 9.64622 L14.684 42.3538 C12.15 48.2094 6.38 52 0 52 H43.51 V0Z" fill="${color}" />
	</svg>`;
	return `url("data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}")`;
};

// 生成右侧三角形SVG的URL编码
const getTriangleRightSvg = (itemIndex) => {
	const color = getColor('bgColor')[itemIndex];
	// 使用原始路径数据，只调整SVG尺寸
	const svg = `<svg width="50" height="60" viewBox="0 0 43.51 52" xmlns="http://www.w3.org/2000/svg">
		<path d="M0 0 C6.37 0 12.14 3.79061 14.674 9.64622 L28.826 42.3538 C31.36 48.2094 37.13 52 43.51 52 H0 V0Z" fill="${color}" />
	</svg>`;
	return `url("data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}")`;
};

// 积分限时购数据 - 秒杀场次
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();
	
	// 第一场：已结束（3小时前开始，2小时前结束）
	const session1Start = baseTime - 3 * 60 * 60 * 1000; // 3小时前
	const session1End = baseTime - 2 * 60 * 60 * 1000;   // 2小时前
	
	// 第二场：正在秒杀（30分钟前开始，30分钟后结束）
	const session2Start = baseTime - 30 * 60 * 1000;     // 30分钟前
	const session2End = baseTime + 30 * 60 * 1000;       // 30分钟后
	
	// 第三场：即将开始（1小时后开始，2小时后结束）
	const session3Start = baseTime + 1 * 60 * 60 * 1000; // 1小时后
	const session3End = baseTime + 2 * 60 * 60 * 1000;   // 2小时后

	// 第四场：即将开始（2小时后开始，3小时后结束）
	const session4Start = baseTime + 2 * 60 * 60 * 1000; // 2小时后
	const session4End = baseTime + 3 * 60 * 60 * 1000;  // 3小时后
	
	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": 1, "text": "立即抢购"},
							"credits": 200,
							"creditsType": "CREDITS",
							"creditsTypeName": "积分",
							"goods": {
								"id": 201,
								"goodsName": "限时秒杀商品A - 正在进行中",
								"goodsImage": ["https://via.placeholder.com/150/FF6B35/FFFFFF?text=SeckillA"],
								"credits": "200",
								"priceSale": "400.00",
								"stock": 15
							},
							"priceSale": "400.00",
							"stock": 15
						},
						{
							"button": {"key": 1, "text": "立即抢购"},
							"credits": 300,
							"creditsType": "CREDITS",
							"creditsTypeName": "积分",
							"goods": {
								"id": 202,
								"goodsName": "限时秒杀商品B - 正在进行中",
								"goodsImage": ["https://via.placeholder.com/150/4CAF50/FFFFFF?text=SeckillB"],
								"credits": "300",
								"priceSale": "600.00",
								"stock": 8
							},
							"priceSale": "600.00",
							"stock": 8
						},
						{
							"button": {"key": 1, "text": "立即抢购"},
							"credits": 150,
							"creditsType": "CREDITS",
							"creditsTypeName": "积分",
							"goods": {
								"id": 203,
								"goodsName": "限时秒杀商品C - 正在进行中",
								"goodsImage": ["https://via.placeholder.com/150/9C27B0/FFFFFF?text=SeckillC"],
								"credits": "150",
								"priceSale": "300.00",
								"stock": 12
							},
							"priceSale": "300.00",
							"stock": 12
						}
					],
					"sessionKey": "session_2_ongoing",
					"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>
