<template>
	<view class="lotterypage">
		<span class="lotterypagebg" :style="bgStyle"></span>
		
		<div class="lotterypageturntable">
			<span class="lotterypageturntablebg" :style="turnTableBgStyle"></span>
			<span class="lotterypageturntablelogo" :style="turnTableLogoStyle"></span>
			
			<div class="lotterypageturntableawards">
				<div class="lotterypageturntableawards6" v-if="turntablePrizes.length > 5">
					<span class="lotterypageturntableawards6bg" :style="awards6BgStyle"></span>
					<span class="lotterypageturntableawards6name">{{ turntablePrizes[5].prizeName }}</span>
				</div>
				<div class="lotterypageturntableawards5" v-if="turntablePrizes.length > 4">
					<span class="lotterypageturntableawards5bg" :style="awards5BgStyle"></span>
					<span class="lotterypageturntableawards5name">{{ turntablePrizes[4].prizeName }}</span>
				</div>
				<div class="lotterypageturntableawards4" v-if="turntablePrizes.length > 3">
					<span class="lotterypageturntableawards4bg" :style="awards4BgStyle"></span>
					<span class="lotterypageturntableawards4name">{{ turntablePrizes[3].prizeName }}</span>
				</div>
				<div class="lotterypageturntableawards3" v-if="turntablePrizes.length > 2">
					<span class="lotterypageturntableawards3bg" :style="awards3BgStyle"></span>
					<span class="lotterypageturntableawards3name">{{ turntablePrizes[2].prizeName }}</span>
				</div>
				<div class="lotterypageturntableawards2" v-if="turntablePrizes.length > 1">
					<span class="lotterypageturntableawards2img" :style="awards2ImgStyle"></span>
					<span class="lotterypageturntableawards2name">{{ turntablePrizes[1].prizeName }}</span>
				</div>
				<div class="lotterypageturntableawards1" v-if="turntablePrizes.length > 0">
					<span class="lotterypageturntableawards1img" :style="awards1ImgStyle"></span>
					<span class="lotterypageturntableawards1name">{{ turntablePrizes[0].prizeName }}</span>
				</div>
			</div>
		</div>
		
		<span class="lotterypagetitle" :style="titleStyle"></span>
		<span class="lotterypagerulebtn" :style="ruleBtnStyle" @click="handleRuleClick"></span>
		<span class="lotterypageawardbtn" :style="awardBtnStyle" @click="handleAwardClick"></span>
		
		<div class="lotterypagenoticecon" v-if="winningCarousel.length > 0">
			<span class="lotterypagenoticeconbg" :style="noticeConBgStyle"></span>
			<span class="lotterypagenoticeconsoundicon" :style="noticeConSoundIconStyle"></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="drawBtnStyle" @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, getCurrentInstance } 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

// Import getCurrentInstance
import { ref, onMounted, computed, getCurrentInstance } from 'vue'

// Update computed properties to access $baseUrl via instance
const instance = getCurrentInstance();
const $baseUrl = instance.proxy.$baseUrl; // Note: This might not work if called too early; better to access inside computed

// Instead, access inside each computed
const bgStyle = computed(() => {
  const inst = getCurrentInstance();
  const base = inst.proxy.$baseUrl;
  return { backgroundImage: `url(${base}${getImageUrl(config.images.background)})` };
});

const turnTableBgStyle = computed(() => {
  const inst = getCurrentInstance();
  const base = inst.proxy.$baseUrl;
  return { backgroundImage: `url(${base}${getImageUrl(config.images.turnTableBg)})` };
});

const turnTableLogoStyle = computed(() => {
  const inst = getCurrentInstance();
  const base = inst.proxy.$baseUrl;
  return { backgroundImage: `url(${base}${getImageUrl(config.images.turnTableLogo)})` };
});

const awards6BgStyle = computed(() => {
  const inst = getCurrentInstance();
  const base = inst.proxy.$baseUrl;
  return { backgroundImage: `url(${base}${getImageUrl(config.images.awards6Bg)})` };
});

const awards5BgStyle = computed(() => {
  const inst = getCurrentInstance();
  const base = inst.proxy.$baseUrl;
  return { backgroundImage: `url(${base}${getImageUrl(config.images.awards5Bg)})` };
});

const awards4BgStyle = computed(() => {
  const inst = getCurrentInstance();
  const base = inst.proxy.$baseUrl;
  return { backgroundImage: `url(${base}${getImageUrl(config.images.awards4Bg)})` };
});

const awards3BgStyle = computed(() => {
  const inst = getCurrentInstance();
  const base = inst.proxy.$baseUrl;
  return { backgroundImage: `url(${base}${getImageUrl(config.images.awards3Bg)})` };
});

const awards2ImgStyle = computed(() => {
  const inst = getCurrentInstance();
  const base = inst.proxy.$baseUrl;
  return { backgroundImage: `url(${base}${getImageUrl(config.images.awards2Img)})` };
});

const awards1ImgStyle = computed(() => {
  const inst = getCurrentInstance();
  const base = inst.proxy.$baseUrl;
  return { backgroundImage: `url(${base}${getImageUrl(config.images.awards1Img)})` };
});

const titleStyle = computed(() => {
  const inst = getCurrentInstance();
  const base = inst.proxy.$baseUrl;
  return { backgroundImage: `url(${base}${getImageUrl(config.images.title)})` };
});

const ruleBtnStyle = computed(() => {
  const inst = getCurrentInstance();
  const base = inst.proxy.$baseUrl;
  return { backgroundImage: `url(${base}${getImageUrl(config.images.ruleBtn)})` };
});

const awardBtnStyle = computed(() => {
  const inst = getCurrentInstance();
  const base = inst.proxy.$baseUrl;
  return { backgroundImage: `url(${base}${getImageUrl(config.images.awardBtn)})` };
});

const noticeConBgStyle = computed(() => {
  const inst = getCurrentInstance();
  const base = inst.proxy.$baseUrl;
  return { backgroundImage: `url(${base}${getImageUrl(config.images.noticeConBg)})` };
});

const noticeConSoundIconStyle = computed(() => {
  const inst = getCurrentInstance();
  const base = inst.proxy.$baseUrl;
  return { backgroundImage: `url(${base}${getImageUrl(config.images.noticeConSoundIcon)})` };
});

const drawBtnStyle = computed(() => {
  const inst = getCurrentInstance();
  const base = inst.proxy.$baseUrl;
  return { backgroundImage: `url(${base}${getImageUrl(config.images.drawBtn)})` };
});

// Add computed properties for URLs
const bgUrl = computed(() => `url(${$baseUrl}${getImageUrl(config.images.background)})`);
const turnTableBgUrl = computed(() => `url(${$baseUrl}${getImageUrl(config.images.turnTableBg)})`);
const turnTableLogoUrl = computed(() => `url(${$baseUrl}${getImageUrl(config.images.turnTableLogo)})`);
const awards6BgUrl = computed(() => `url(${$baseUrl}${getImageUrl(config.images.awards6Bg)})`);
const awards5BgUrl = computed(() => `url(${$baseUrl}${getImageUrl(config.images.awards5Bg)})`);
const awards4BgUrl = computed(() => `url(${$baseUrl}${getImageUrl(config.images.awards4Bg)})`);
const awards3BgUrl = computed(() => `url(${$baseUrl}${getImageUrl(config.images.awards3Bg)})`);
const awards2ImgUrl = computed(() => `url(${$baseUrl}${getImageUrl(config.images.awards2Img)})`);
const awards1ImgUrl = computed(() => `url(${$baseUrl}${getImageUrl(config.images.awards1Img)})`);
const titleUrl = computed(() => `url(${$baseUrl}${getImageUrl(config.images.title)})`);
const ruleBtnUrl = computed(() => `url(${$baseUrl}${getImageUrl(config.images.ruleBtn)})`);
const awardBtnUrl = computed(() => `url(${$baseUrl}${getImageUrl(config.images.awardBtn)})`);
const noticeConBgUrl = computed(() => `url(${$baseUrl}${getImageUrl(config.images.noticeConBg)})`);
const noticeConSoundIconUrl = computed(() => `url(${$baseUrl}${getImageUrl(config.images.noticeConSoundIcon)})`);
const drawBtnUrl = computed(() => `url(${$baseUrl}${getImageUrl(config.images.drawBtn)})`);

// 计算属性 - 是否可以抽奖
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
// };

// Implement placeholder functions
const findPrizeIndex = (prizeId) => {
  // Find index based on prizeId, placeholder returns 0
  return turntablePrizes.value.findIndex(p => p.prizeId === prizeId) || 0;
};

const calculateRotation = (index) => {
  // Assuming 6 prizes, each 60 degrees
  return index * 60 + Math.random() * 30 - 15; // Add some randomness for realism
};

const showResultModal = (data) => {
  // Check if won
  const newPrize = data.userWinningPrizes.find(prize => !userWinningPrizes.value.some(old => old.winningRecordId === prize.winningRecordId));
  userWinningPrizes.value = data.userWinningPrizes;
  if (newPrize) {
    currentAwardName.value = newPrize.prizeName;
    showDrawSucModal.value = true;
  } else {
    showDrawFailModal.value = true;
  }
};

// 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>
.lotterypagebg {
  background-image: v-bind(bgUrl);
}

.lotterypageturntablebg {
  background-image: v-bind(turnTableBgUrl);
}

.lotterypageturntablelogo {
  background-image: v-bind(turnTableLogoUrl);
}

.lotterypageturntableawards6bg {
  background-image: v-bind(awards6BgUrl);
}

.lotterypageturntableawards5bg {
  background-image: v-bind(awards5BgUrl);
}

.lotterypageturntableawards4bg {
  background-image: v-bind(awards4BgUrl);
}

.lotterypageturntableawards3bg {
  background-image: v-bind(awards3BgUrl);
}

.lotterypageturntableawards2img {
  background-image: v-bind(awards2ImgUrl);
}

.lotterypageturntableawards1img {
  background-image: v-bind(awards1ImgUrl);
}

.lotterypagetitle {
  background-image: v-bind(titleUrl);
}

.lotterypagerulebtn {
  background-image: v-bind(ruleBtnUrl);
}

.lotterypageawardbtn {
  background-image: v-bind(awardBtnUrl);
}

.lotterypagenoticeconbg {
  background-image: v-bind(noticeConBgUrl);
}

.lotterypagenoticeconsoundicon {
  background-image: v-bind(noticeConSoundIconUrl);
}

.lotterypagedrawbtn {
  background-image: v-bind(drawBtnUrl);
}
</style>
