<template>
	<view class="lotterypage">
		<span class="lotterypagebg"
			:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.background)})` }"></span>
		
		<div class="lotterypageturntable">
			<span class="lotterypageturntablebg"
				:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.turnTableBg)})` }"></span>
			<span class="lotterypageturntablelogo"
				:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.turnTableLogo)})` }"></span>
			
			<div class="lotterypageturntableawards">
				<div class="lotterypageturntableawards6" v-if="turntablePrizes.length > 5">
					<span class="lotterypageturntableawards6bg"
						:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.awards6Bg)})` }"></span>
					<span class="lotterypageturntableawards6name">{{ turntablePrizes[5].prizeName }}</span>
				</div>
				<div class="lotterypageturntableawards5" v-if="turntablePrizes.length > 4">
					<span class="lotterypageturntableawards5bg"
						:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.awards5Bg)})` }"></span>
					<span class="lotterypageturntableawards5name">{{ turntablePrizes[4].prizeName }}</span>
				</div>
				<div class="lotterypageturntableawards4" v-if="turntablePrizes.length > 3">
					<span class="lotterypageturntableawards4bg"
						:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.awards4Bg)})` }"></span>
					<span class="lotterypageturntableawards4name">{{ turntablePrizes[3].prizeName }}</span>
				</div>
				<div class="lotterypageturntableawards3" v-if="turntablePrizes.length > 2">
					<span class="lotterypageturntableawards3bg"
						:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.awards3Bg)})` }"></span>
					<span class="lotterypageturntableawards3name">{{ turntablePrizes[2].prizeName }}</span>
				</div>
				<div class="lotterypageturntableawards2" v-if="turntablePrizes.length > 1">
					<span class="lotterypageturntableawards2img"
						:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.awards2Img)})` }"></span>
					<span class="lotterypageturntableawards2name">{{ turntablePrizes[1].prizeName }}</span>
				</div>
				<div class="lotterypageturntableawards1" v-if="turntablePrizes.length > 0">
					<span class="lotterypageturntableawards1img"
						:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.awards1Img)})` }"></span>
					<span class="lotterypageturntableawards1name">{{ turntablePrizes[0].prizeName }}</span>
				</div>
			</div>
		</div>
		
		<span class="lotterypagetitle"
			:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.title)})` }"></span>
		<span class="lotterypagerulebtn"
			:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.ruleBtn)})` }"
			@click="handleRuleClick"></span>
		<span class="lotterypageawardbtn"
			:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.awardBtn)})` }"
			@click="handleAwardClick"></span>
		
		<div class="lotterypagenoticecon" v-if="winningCarousel.length > 0">
			<span class="lotterypagenoticeconbg"
				:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.noticeConBg)})` }"></span>
			<span class="lotterypagenoticeconsoundicon"
				:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.noticeConSoundIcon)})` }"></span>
			<div class="lotterypagenoticecontext-wrapper">
				<div class="lotterypagenoticecontext-container" :style="{ transform: `translateY(-${currentNoticeIndex * 40}rpx)` }">
					<span class="lotterypagenoticecontext" v-for="(notice, index) in recentNotices" :key="index">{{ formatNotice(notice.userNickname, notice.prizeName) }}</span>
				</div>
			</div>
		</div>
		
		<span class="lotterypagedrawbtn"
			:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.drawBtn)})` }"
			@click="handleDrawClick"
			:class="{ 'disabled-draw-btn': !canDraw }"></span>
		<span class="lotterypagelefttimes">剩余次数：{{ remainingTimes }}</span>

		<!-- 规则弹窗 -->
		<RuleModal 
			:visible="showRuleModal" 
			:rules="activityRules"
			@close="handleRuleModalClose" 
		/>

		<!-- 抽奖成功弹窗 -->
		<DrawSucModal 
			:visible="showDrawSucModal" 
			:award-name="currentAwardName"
			@close="handleDrawSucModalClose"
			@happy-get="handleHappyGet"
		/>

		<!-- 抽奖失败弹窗 -->
		<DrawFailModal 
			:visible="showDrawFailModal" 
			@close="handleDrawFailModalClose"
			@i-know="handleIKnow"
		/>
	</view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { lotteryConfig, getImageUrl } from './config.js'
import RuleModal from './components/ruleModal/ruleModal.vue'
import DrawSucModal from './components/drawSucModal/drawSucModal.vue'
import DrawFailModal from './components/drawFailModal/drawFailModal.vue'
import { getAct915LotteryDraw, getAct915LotteryInfo } from '../../api/activity0915/index.js'

// 组件名称
defineOptions({
	name: 'LotteryPage'
})

// 响应式数据
const currentState = ref('normal') // 页面状态
const remainingTimes = ref(0) // 剩余抽奖次数
const currentNotice = ref('') // 当前公告
const turntablePrizes = ref([]) // 转盘奖品列表
const winningCarousel = ref([]) // 中奖轮播列表
const userWinningPrizes = ref([]) // 用户中奖记录
const currentNoticeIndex = ref(0) // 当前公告索引

// Declare new refs
const isDrawing = ref(false);
const rotationAngle = ref(0);
const thanksPosition = 0; // Placeholder for thanks position angle

// 弹窗状态
const showRuleModal = ref(false) // 规则弹窗
const showDrawSucModal = ref(false) // 抽奖成功弹窗
const showDrawFailModal = ref(false) // 抽奖失败弹窗
const currentAwardName = ref('') // 当前中奖奖品名称
const activityRules = ref('') // 活动规则内容

// 配置对象
const config = lotteryConfig

// 计算属性 - 是否可以抽奖
const canDraw = computed(() => {
	return remainingTimes.value > 0 && currentState.value === 'normal'
})

// 加载抽奖信息
const loadLotteryInfo = async () => {
	try {
		// 使用mock数据进行测试
		const mockData = {
			ok: true,
			data: {
				remainingChances: 3,
				turntablePrizes: [
					{ prizeId: 1001, prizeName: "一等奖 - 飞鹤奶粉", prizeImageUrl: "/images/prizes/prize1.png", prizeType: "Physical", prizeDescription: "飞鹤星飞帆幼儿配方奶粉 1段 800g", displayProbability: "0.1%", remainingStock: 5 },
					{ prizeId: 1002, prizeName: "二等奖 - 婴儿推车", prizeImageUrl: "/images/prizes/prize2.png", prizeType: "Physical", prizeDescription: "高端婴儿推车，适合0-3岁宝宝", displayProbability: "0.5%", remainingStock: 10 },
					{ prizeId: 1003, prizeName: "三等奖 - 玩具套装", prizeImageUrl: "/images/prizes/prize3.png", prizeType: "Physical", prizeDescription: "益智玩具套装，适合幼儿", displayProbability: "1%", remainingStock: 20 },
					{ prizeId: 1004, prizeName: "四等奖 - 优惠券50元", prizeImageUrl: "/images/prizes/prize4.png", prizeType: "Digital", prizeDescription: "飞鹤商城50元优惠券", displayProbability: "5%", remainingStock: 100 },
					{ prizeId: 1005, prizeName: "五等奖 - 积分100分", prizeImageUrl: "/images/prizes/prize5.png", prizeType: "Digital", prizeDescription: "可用于兑换商城商品的积分", displayProbability: "10%", remainingStock: 500 },
					{ prizeId: 1006, prizeName: "六等奖 - 谢谢参与", prizeImageUrl: "/images/prizes/prize6.png", prizeType: "None", prizeDescription: "未中奖，再接再厉", displayProbability: "83.4%", remainingStock: 9999 }
				],
				winningCarousel: [
					{ userNickname: "用户123****4567", prizeName: "飞鹤奶粉", winningTime: "刚刚" },
					{ userNickname: "用户789****0123", prizeName: "婴儿推车", winningTime: "5分钟前" },
					{ userNickname: "用户456****7890", prizeName: "优惠券50元", winningTime: "10分钟前" }
				],
				userWinningPrizes: [
					{ winningRecordId: 5001, prizeId: 1004, prizeName: "优惠券50元", prizeImageUrl: "/images/prizes/prize4.png", prizeType: "Digital", prizeDescription: "飞鹤商城50元优惠券", isIssued: true, winningTime: "2023-09-15 10:30:45", issueTime: "2023-09-15 10:31:00" },
					{ winningRecordId: 5002, prizeId: 1005, prizeName: "积分100分", prizeImageUrl: "/images/prizes/prize5.png", prizeType: "Digital", prizeDescription: "可用于兑换商城商品的积分", isIssued: true, winningTime: "2023-09-14 15:22:10", issueTime: "2023-09-14 15:22:30" }
				],
				activityRules: "1. 活动期间，每位用户每天有一次抽奖机会。\n2. 抽奖结果以页面显示为准。\n3. 奖品将在活动结束后统一发放。"
			}
		};
		const response = mockData; // 替换为实际API调用：await getAct915LotteryInfo();
		if (response.ok) {
			remainingTimes.value = response.data.remainingChances;
			turntablePrizes.value = response.data.turntablePrizes;
			winningCarousel.value = response.data.winningCarousel;
			userWinningPrizes.value = response.data.userWinningPrizes;
			activityRules.value = response.data.activityRules || '';
			if (winningCarousel.value.length > 0) {
				currentNotice.value = formatNotice(winningCarousel.value[0].userNickname, winningCarousel.value[0].prizeName);
				// 启动公告轮播
				startNoticeCarousel();
			}
		} else {
			uni.showToast({
				title: response.msg || '获取抽奖信息失败',
				icon: 'none'
			});
		}
	} catch (error) {
		uni.showToast({
			title: '网络错误，请稍后重试',
			icon: 'none'
		});
	}
};

// 公告轮播
const startNoticeCarousel = () => {
	if (winningCarousel.value.length > 1) {
		setInterval(() => {
			currentNoticeIndex.value = (currentNoticeIndex.value + 1) % recentNotices.value.length;
			console.log('当前公告索引:', currentNoticeIndex.value); // 调试日志，确保索引更新
		}, 3000); // 每3秒切换一次
	}
};

// 获取最近的20条公告
const recentNotices = computed(() => {
	return winningCarousel.value.slice(0, 20);
});

// 格式化公告内容，限制为20个字符
const formatNotice = (nickname, prize) => {
	const fullText = `${nickname} 获得了 ${prize}`;
	return fullText.length > 20 ? fullText.substring(0, 20) + '…' : fullText;
};

// 规则按钮点击处理
const handleRuleClick = () => {
	console.log('点击规则按钮', showRuleModal.value);
	showRuleModal.value = true;
	console.log('规则弹窗状态已更新', showRuleModal.value);
}

// 规则弹窗关闭处理
const handleRuleModalClose = () => {
	console.log('关闭规则弹窗');
	showRuleModal.value = false;
	console.log('规则弹窗状态已关闭', showRuleModal.value);
}

// 奖品按钮点击处理
const handleAwardClick = () => {
	// Placeholder link - replace with provided link
	uni.navigateTo({ 
		url: '/pages/webview/webview?url=https://example.com/star-mom-preferred' 
	});
};

// 抽奖按钮点击处理
const handleDrawClick = async () => {
  if (isDrawing.value) return;
  
  // Check login status
  const isLoggedIn = checkLoginStatus();
  if (!isLoggedIn) {
    showLoginModal();
    return;
  }
  
  if (remainingTimes.value <= 0) {
    uni.showToast({ title: '抽奖次数已用完', icon: 'none' });
    return;
  }
  
  isDrawing.value = true;
  uni.showLoading({ title: '抽奖中...', mask: true });
  
  try {
    const response = await getAct915LotteryDraw();
    
    if (response.ok) {
      remainingTimes.value = response.data.remainingChances;
      
      const prizeIndex = findPrizeIndex(response.data.prizeId); // Placeholder function
      rotationAngle.value = calculateRotation(prizeIndex); // Placeholder
      
      setTimeout(() => {
        showResultModal(response.data); // Placeholder
        isDrawing.value = false;
        uni.hideLoading();
      }, 3000);
    } else {
      rotationAngle.value = thanksPosition;
      isDrawing.value = false;
    }
  } catch (error) {
    rotationAngle.value = thanksPosition;
    isDrawing.value = false;
    uni.hideLoading();
  }
};

// Add login check function (placeholder)
const checkLoginStatus = () => {
	// Implement actual login check
	return true; // Placeholder
};

const showLoginModal = () => {
	// Implement login modal
};

// Placeholder functions
const findPrizeIndex = (prizeId) => 0; // Implement
const calculateRotation = (index) => index * 60; // Example
const showResultModal = (data) => {
  // Implement based on win/lose
};

// Initial position to thanks
onMounted(() => {
	console.log('抽奖页面已加载')
	loadLotteryInfo();
	rotationAngle.value = thanksPosition;
});

// Remaining times already implemented

// 抽奖成功弹窗关闭处理
const handleDrawSucModalClose = () => {
	console.log('关闭抽奖成功弹窗');
	showDrawSucModal.value = false;
	console.log('抽奖成功弹窗状态已关闭', showDrawSucModal.value);
}

// 开心领取处理
const handleHappyGet = () => {
	console.log('点击开心领取');
	showDrawSucModal.value = false;
	console.log('抽奖成功弹窗状态已关闭', showDrawSucModal.value);
	uni.showToast({
		title: '奖品领取成功',
		icon: 'success'
	})
}

// 抽奖失败弹窗关闭处理
const handleDrawFailModalClose = () => {
	console.log('关闭抽奖失败弹窗');
	showDrawFailModal.value = false;
	console.log('抽奖失败弹窗状态已关闭', showDrawFailModal.value);
}

// 我知道了处理
const handleIKnow = () => {
	console.log('点击我知道了');
	showDrawFailModal.value = false;
	console.log('抽奖失败弹窗状态已关闭', showDrawFailModal.value);
	uni.showToast({
		title: '下次再来试试吧',
		icon: 'none'
	})
}

// 生命周期
onMounted(() => {
	console.log('抽奖页面已加载')
	loadLotteryInfo();
})
</script>

<style lang="less" scoped>
.lotterypageturntable {
  transform: rotate(v-bind(rotationAngle + 'deg'));
  transition: transform 3s ease-out;
}
</style>
