<template>
	<view class="lottery-container" @click="handleClickOutside">
		<view class="navbar">
			<button class="back-button" @click="goBack">X</button>
			<text class="title">没有良心的抽奖</text>
		</view>
		<view class="lottery-box">
			<view class="lottery-item" v-for="(item, index) in prizes" :key="index"
				:class="{ 'active': activeIndex === index }"
				:style="{ transform: activeIndex === index ? 'scale(1.05)' : 'scale(1)', transition: 'transform 0.5s ease' }">
				<image class="prize-image" :src="item.image" mode="aspectFill"></image>
				<text class="prize-name">{{ item.name }}</text>
			</view>
		</view>
		<view class="button-container">
			<button class="lottery-button" @click="startLottery" @touchstart.prevent="startLottery">开始抽奖</button>
			<button class="history-button" @click="getLotteryHistory"
				@touchstart.prevent="getLotteryHistory">抽奖历史</button>
			<button class="ranking-button" @click="getLotteryRanking"
				@touchstart.prevent="getLotteryRanking">排行榜</button>
		</view>
		<view class="lottery-description">
			<view class="description-box">
				<text class="description-title">抽奖说明：<br></text>
				<text class="description-text" v-for="(item, index) in lotteryDescription"
					:key="index">{{ item }}<br></text>
			</view>
		</view>
		<transition name="fade">
			<view v-if="showResult" class="result-box" @click.stop>
				<text class="result-text">恭喜你获得：{{ result.name }}</text>
			</view>
		</transition>
		<transition name="fade">
			<view v-if="showHistory" class="history-box" @click.stop>
				<text class="history-title">抽奖历史记录</text>
				<view class="history-list">
					<view v-for="(item, index) in lotteryHistory" :key="index" class="history-item">
						<text class="history-item-text">{{ item.subject }} - {{ item.created }}</text>
					</view>
				</view>
				<button class="close-button" @click="showHistory = false">×</button>
			</view>
		</transition>
		<transition name="fade">
			<view v-if="showRanking" class="ranking-box" @click.stop>
				<text class="ranking-title">抽奖排行榜</text>
				<view class="ranking-list">
					<view v-for="(item, index) in lotteryRanking" :key="index" class="ranking-item">
						<text class="ranking-item-text">{{ index + 1 }}. UID: {{ item.uid }} - 总抽奖次数:
							{{ item.total_lottery }} - 总中奖金额: {{ item.total_amount }}</text>
					</view>
				</view>
				<button class="close-button" @click="showRanking = false">×</button>
			</view>
		</transition>
	</view>
</template>

<script>
	import {
		localStorage
	} from '../../js_sdk/mp-storage/mp-storage/index.js';
	const STAR_URL = 'https://ye.lzchi.top/';
	const API = {
		// 抽奖
		lottery: function() {
			return STAR_URL + 'Plugins/sy_starpro/api.php?act=lottery';
		},
		// 获取抽奖历史记录
		getLotteryHistory: function() {
			return STAR_URL + 'Plugins/sy_starpro/api.php?act=getLotteryHistory';
		},
		// 获取抽奖排行榜
		getLotteryRanking: function() {
			return STAR_URL + 'Plugins/sy_starpro/api.php?act=getLotteryRanking';
		},
		// 获取抽奖说明
		getLotteryDescription: function() {
			return STAR_URL + 'Plugins/sy_starpro/api.php?act=getLotteryDescription';
		}
	};

	export default {
		data() {
			return {
				prizes: [{
						name: '7天会员',
						image: '/static/cj/1.png'
					},
					{
						name: '50元气',
						image: '/static/cj/2.png'
					},
					{
						name: '40元气',
						image: '/static/cj/3.png'
					},
					{
						name: '30元气',
						image: '/static/cj/4.png'
					},
					{
						name: '20元气',
						image: '/static/cj/5.png'
					},
					{
						name: '10元气',
						image: '/static/cj/6.png'
					},
					{
						name: '5元气',
						image: '/static/cj/7.png'
					},
					{
						name: '1元气',
						image: '/static/cj/8.png'
					},
					{
						name: '0元气',
						image: '/static/cj/9.png'
					},
				],
				result: {},
				showResult: false,
				isLotteryRunning: false,
				activeIndex: -1,
				interval: null,
				finalIndex: -1,
				uid: null,
				showHistory: false,
				lotteryHistory: [],
				showRanking: false,
				lotteryRanking: [],
				lotteryDescription: []
			};
		},
		created() {
			this.fetchLotteryDescription();
		},
		methods: {
			startLottery() {
				if (this.isLotteryRunning) return;
				this.isLotteryRunning = true;
				this.showResult = false;
				this.activeIndex = -1;

				let count = 0;
				this.interval = setInterval(() => {
					this.activeIndex = (this.activeIndex + 1) % this.prizes.length;
					count++;
					if (count >= 20) {
						clearInterval(this.interval);
						setTimeout(() => {
							this.fetchLotteryResult();
						}, 500);
					}
				}, 100);
			},
			fetchLotteryResult() {
				this.uid = this.getUserUid();
				const url = `${API.lottery()}&uid=${this.uid}`;
				uni.request({
					url: url,
					method: 'GET',
					success: (res) => {
						const data = res.data;
						console.log('API Response:', data);
						if (data.code === 200) {
							this.result = data.result;
							this.finalIndex = this.prizes.findIndex(prize => prize.name === this.result.name);
							this.smoothMoveToFinalIndex();
						} else {
							alert(data.msg);
						}
					},
					fail: (err) => {
						console.error('Error fetching lottery result:', err);
						alert('抽奖失败，请重试');
					},
					complete: () => {
						this.isLotteryRunning = false;
					}
				});
			},
			getUserUid() {
				const userInfo = JSON.parse(localStorage.getItem('userinfo'));
				if (userInfo && userInfo.uid) {
					return userInfo.uid;
				} else {
					throw new Error('用户UID未找到');
				}
			},
			smoothMoveToFinalIndex() {
				const currentIndex = this.activeIndex;
				const finalIndex = this.finalIndex;
				const step = finalIndex > currentIndex ? 1 : -1;
				let index = currentIndex;

				const moveInterval = setInterval(() => {
					index += step;
					this.activeIndex = index;

					if (index === finalIndex) {
						clearInterval(moveInterval);
						setTimeout(() => {
							this.showResult = true;
							setTimeout(() => {
								this.showResult = false;
							}, 5000); // 5秒后自动关闭提示框
						}, 600); // 选择框停止后，延迟500毫秒显示中奖提示
					}
				}, 300); // 每200毫秒移动一次
			},
			handleClickOutside(event) {
				const target = document.elementFromPoint(event.clientX, event.clientY);
				if (this.showResult && !target.closest('.result-box')) {
					this.showResult = false;
				}
				if (this.showHistory && !target.closest('.history-box')) {
					this.showHistory = false;
				}
				if (this.showRanking && !target.closest('.ranking-box')) {
					this.showRanking = false;
				}
			},
			fetchLotteryDescription() {
				const url = API.getLotteryDescription();
				uni.request({
					url: url,
					method: 'GET',
					success: (res) => {
						const data = res.data;
						console.log('Description API Response:', data);
						if (data.code === 200) {
							this.lotteryDescription = data.description;
						} else {
							alert(data.msg);
						}
					},
					fail: (err) => {
						console.error('Error fetching lottery description:', err);
						alert('获取抽奖说明失败，请重试');
					}
				});
			},
			getLotteryHistory() {
				this.uid = this.getUserUid();
				const url = `${API.getLotteryHistory()}&uid=${this.uid}`;
				uni.request({
					url: url,
					method: 'GET',
					success: (res) => {
						const data = res.data;
						console.log('History API Response:', data);
						if (data.code === 200) {
							this.lotteryHistory = data.history.map(item => {
								const createdDate = new Date(item.created * 1000);
								const formattedDate =
									`${createdDate.getFullYear()}-${String(createdDate.getMonth() + 1).padStart(2, '0')}-${String(createdDate.getDate()).padStart(2, '0')} ${String(createdDate.getHours()).padStart(2, '0')}:${String(createdDate.getMinutes()).padStart(2, '0')}:${String(createdDate.getSeconds()).padStart(2, '0')}`;
								return {
									...item,
									created: formattedDate
								};
							});
							this.showHistory = true;
						} else {
							alert(data.msg);
						}
					},
					fail: (err) => {
						console.error('Error fetching lottery history:', err);
						alert('获取抽奖历史记录失败，请重试');
					}
				});
			},
			getLotteryRanking() {
				const url = API.getLotteryRanking();
				uni.request({
					url: url,
					method: 'GET',
					success: (res) => {
						const data = res.data;
						console.log('Ranking API Response:', data);
						if (data.code === 200) {
							this.lotteryRanking = data.ranking;
							this.showRanking = true;
						} else {
							alert(data.msg);
						}
					},
					fail: (err) => {
						console.error('Error fetching lottery ranking:', err);
						alert('获取抽奖排行榜失败，请重试');
					}
				});
			},
			goBack() {
				uni.navigateBack({
					delta: 1
				});
			}
		},
		beforeDestroy() {
			clearInterval(this.interval);
		},
	};
</script>
<style scoped>
	.lottery-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 20px;
		background: url('https://tk.illlt.com:759/api.php?type=%E6%89%8B%E6%9C%BA%E4%BA%8C%E6%AC%A1%E5%85%83/%E6%89%8B%E6%9C%BA%E7%AB%AF-%E5%8A%A8%E6%BC%AB%E5%9B%BE%E7%89%87/%E5%8A%A8%E6%BC%AB%E5%9B%BE%E7%89%871%E5%88%86%E5%8C%BA') no-repeat center center;
		background-size: cover;
		min-height: 100vh;
		box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
		position: relative;
		overflow: hidden;
	}

	.lottery-container::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: rgba(255, 255, 255, 0.8);
		z-index: -1;
	}

	.navbar {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
		padding: 10px 20px;
		background-color: #fff;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
		position: fixed;
		top: 0;
		z-index: 1000;
	}

	.back-button {
		position: absolute;
		left: 10px;
		top: 50%;
		transform: translateY(-50%);
		padding: 5px 10px;
		font-size: 18px;
		color: #000000;
		background: none;
		border: none;
		border-radius: 10px;
		cursor: pointer;
		box-shadow: none;
		transition: transform 0.3s ease;
	}

	.back-button:hover {
		transform: translateY(-50%) translateY(-3px);
		box-shadow: 0 6px 15px rgba(0, 0, 0, 0.2);
	}

	.title {
		font-size: 24px;
		color: #333;
		font-weight: bold;
	}

	.lottery-box {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		gap: 20px;
		width: 100%;
		max-width: 800px;
		margin-top: 80px;
	}

	.lottery-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 20px;
		border: 4px solid #b6b6b6;
		border-radius: 15px;
		background-color: #fff;
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
		transition: transform 0.3s ease, box-shadow 0.3s ease, border-color 0.3s ease;
		position: relative;
		overflow: hidden;
	}

	.lottery-item.active {
		border-color: #ff0000;
		border-width: 4px;
		box-shadow: 0 6px 15px rgba(0, 0, 0, 0.2);
		transform: scale(1.05);
	}

	.prize-image {
		width: 100px;
		height: 100px;
		border-radius: 50%;
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
	}

	.prize-name {
		margin-top: 15px;
		font-size: 16px;
		color: #555;
		font-weight: bold;
	}

	.button-container {
		display: flex;
		justify-content: center;
		gap: 20px;
		margin-top: 30px;
	}

	.lottery-button,
	.history-button,
	.ranking-button {
		padding: 15px 30px;
		font-size: 18px;
		color: #fff;
		background: linear-gradient(135deg, #ff7e5f, #feb47b);
		border: none;
		border-radius: 10px;
		cursor: pointer;
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
		transition: transform 0.3s ease, box-shadow 0.3s ease;
		position: relative;
		overflow: hidden;
		display: flex;
		justify-content: center;
		align-items: center;
		text-align: center;
	}

	.lottery-button::before,
	.history-button::before,
	.ranking-button::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: rgba(255, 255, 255, 0.2);
		transform: scale(0);
		transition: transform 0.3s ease;
	}

	.lottery-button:hover::before,
	.history-button:hover::before,
	.ranking-button:hover::before {
		transform: scale(1);
	}

	.lottery-button:hover,
	.history-button:hover,
	.ranking-button:hover {
		transform: translateY(-3px);
		box-shadow: 0 6px 15px rgba(0, 0, 0, 0.2);
	}

	.lottery-description {
		margin-top: 30px;
		width: 100%;
		max-width: 800px;
	}

	.description-box {
		background-color: #f9f9f9;
		border: 1px solid #e0e0e0;
		border-radius: 10px;
		padding: 20px;
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
	}

	.description-title {
		font-size: 18px;
		color: #333;
		font-weight: bold;
		margin-bottom: 10px;
	}

	.description-text {
		font-size: 16px;
		color: #555;
		line-height: 1.5;
	}

	.result-box,
	.history-box,
	.ranking-box {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		padding: 20px;
		border: 2px solid #e0e0e0;
		border-radius: 15px;
		background-color: #fff;
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
		text-align: center;
		z-index: 1000;
		max-height: 80vh;
		overflow-y: auto;
		width: 90%;
		max-width: 600px;
	}

	.result-text,
	.history-title,
	.ranking-title {
		font-size: 20px;
		color: #333;
		margin-bottom: 15px;
		font-weight: bold;
	}

	.history-list,
	.ranking-list {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 100%;
	}

	.history-item,
	.ranking-item {
		width: 100%;
		padding: 10px;
		border-bottom: 1px solid #e0e0e0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 16px;
		color: #555;
	}

	.history-item:last-child,
	.ranking-item:last-child {
		border-bottom: none;
	}

	.close-button {
		position: absolute;
		top: 10px;
		right: 10px;
		background: none;
		border: none;
		font-size: 24px;
		color: #555;
		cursor: pointer;
		transition: color 0.3s ease;
	}

	.close-button:hover {
		color: #ff0000;
	}

	.fade-enter-active,
	.fade-leave-active {
		transition: opacity 0.5s, transform 0.5s;
	}

	.fade-enter,
	.fade-leave-to {
		opacity: 0;
		transform: translateY(20px);
	}

	@media (max-width: 600px) {
		.lottery-box {
			grid-template-columns: repeat(3, 1fr);
			gap: 10px;
		}

		.lottery-item {
			padding: 10px;
		}

		.prize-image {
			width: 60px;
			height: 60px;
		}

		.prize-name {
			font-size: 12px;
		}

		.button-container {
			flex-wrap: wrap;
		}

		.lottery-button,
		.history-button,
		.ranking-button {
			flex: 1 1 calc(33.333% - 10px);
			margin-bottom: 10px;
			width: 110px;
			height: 40px;
		}

		.description-box {
			padding: 10px;
		}

		.description-title {
			font-size: 14px;
		}

		.description-text {
			font-size: 12px;
		}

		.result-box,
		.history-box,
		.ranking-box {
			padding: 15px;
		}

		.result-text,
		.history-title,
		.ranking-title {
			font-size: 16px;
		}

		.history-item,
		.ranking-item {
			font-size: 12px;
		}

		.close-button {
			font-size: 18px;
		}
	}
</style>