<template>
	<view v-if="visible" class="normal-popup-view-container">
			<view class="normal-popup-view" @click.stop="handleMaskClick">
				<view class="normal-popup-content">
					<view class="popup-content-view" :style="{ 'background-color': themeStore.theme.popup.bgColor }">
						<view class="tips-popup-content">
							<view class="content-top" @touchmove.prevent="handleMaskMove">
								<view class="title text-a-center" :style="{ color: themeStore.theme.text.normal }">
									{{ promoStore.turnplate.title || 'Lucky Spin' }}
								</view>
								<view class="text" :style="{ color: themeStore.theme.text.normal }">
									<view class="flex-acenter flex-sbetween w-100p plr16">
										<view class="ft12 flex-1">
											{{ $t('promo.turnplate.yourBonus') }} {{ pageData.myBonus }}
										</view>
										<view class="act-btn mr10" :style="{ background: pageData.myBonus <= 0 ? '#999999' : themeStore.theme.button.normal2 }" @click.stop="handleClaimClick">
											{{ $t('promo.turnplate.claim') }}
										</view>
										<view class="act-btn" :style="{ background: themeStore.theme.button.normal1 }" @click.stop="shareWithSystem({ url: appStore.inviteLink })">
											{{ $t('promo.turnplate.share') }}
										</view>
									</view>
									<view class="mt24 flex-scenter">
										<view class="spin-container">
											<theme-image class="spin-round-bg" src="@/static/promo/turnplate/plate-round.png" mode="scaleToFill" />
											<theme-image class="spin-arrow-top" src="@/static/promo/turnplate/plate-arrow-top.png" mode="scaleToFill" />	
											<view class="spin-btn" @click.stop="start" >
												<theme-image class="spin-btn-img" src="@/static/promo/turnplate/plate-arrow.png" mode="aspectFit"/>
												<view class="spin-btn-text">
													<view class="spin-title">
														Spin
													</view>
													<view>
														Remaining
													</view>
													<view>
														{{ promoStore.turnplate.remainTimes }} times
													</view>
												</view>
											</view>
											<view class="prize-list" id="prize-wrap" ref="prizeWrapRef" :style="bgColor">
												<view class="prize-item" v-for="(item, index) in promoStore.turnplate.spinList" :style="prizeStyle(index)">
													<div class="prize-item-title">
														{{ item.amount }}
													</div>
													<theme-image class="prize-item-img" src="@/static/promo/turnplate/icon-coin.png" mode="aspectFit" />
												</view>
											</view>
										</view>
									</view>
									<view class="mt24">
										<NormalTabs
											v-model="promoStore.turnplate.tabIndex"
											:normalColor="themeStore.theme.tabs.normal"
											:activeColor="themeStore.theme.tabs.active"
											size="small"
											:tabList="[
												{
													title: $t('promo.turnplate.rules'),
												},
												{
													title: $t('promo.turnplate.winning')
												},
												{
													title: $t('promo.turnplate.myRecord')
												}
											]"
										/>
									</view>
								</view>
							</view>
							<view style="width: 100%;">
								<view id="list">
									<view v-if="promoStore.turnplate.tabIndex === 0" class="list-container mt20 plr16">
										<view class="list-scroll">
											<view v-for="(item, index) in promoStore.turnplate.rules" :key="index">
												<view class="flex-acenter ptb16">
													<theme-image src="@/static/promo/rz.png" style="width: 24rpx; height: 24rpx;"></theme-image>
													<view class="ml8 ft13" :style="{ color: themeStore.theme.text.highlight }">
														{{ item.head_1 }}
													</view>
												</view>
												<view class="ft12">
													{{ item.desc_1 }}
												</view>
											</view>
										</view>
									</view>
									<view v-if="promoStore.turnplate.tabIndex === 1" class="list-container mt20 plr16">
										<view class="list-item" :style="{ 'background': themeStore.theme.list.headerBgColor }">
											<view class="list-value">
												{{ $t('promo.turnplate.phone') }}
											</view>
											<view class="list-value">
												{{ $t('promo.turnplate.bonus') }}
											</view>
											<view class="list-value">
												{{ $t('promo.turnplate.time') }}
											</view>
										</view>
										<view class="list-scroll">
											<view
												class="list-item top3"
												v-for="(item, index) in pageData.bigList"
											>
												<view class="list-value">
													{{ encipherAccountPhone(item.mobile) }}
												</view>
												<view class="list-value">
													Got {{ item.amount }} bonus
												</view>
												<view class="list-value">
													{{ formatDateStr(item.createTime, 10) }}
												</view>
											</view>
											<view
												class="list-item"
												v-for="(item, index) in pageData.list"
											>
												<view class="list-value">
													{{ encipherAccountPhone(item.mobile) }}
												</view>
												<view class="list-value">
													Got {{ item.amount }} bonus
												</view>
												<view class="list-value">
													{{ formatDateStr(item.createTime, 10) }}
												</view>
											</view>
										</view>
									</view>
									<view v-if="promoStore.turnplate.tabIndex === 2" class="list-container mt20 plr16">
										<view class="list-item" :style="{ 'background': themeStore.theme.list.headerBgColor }">
											<view class="list-value">
												{{ $t('promo.turnplate.claimTime') }}
											</view>
											<view class="list-value">
												{{ $t('promo.turnplate.bonus') }}
											</view>
										</view>
										<view class="list-scroll">
											<view
												class="list-item"
												v-for="(item, index) in pageData.myList"
											>
												<view class="list-value">
													{{ formatDateStr(item.createTime, 3) }}
												</view>
												<view class="list-value" style="width: 49%;">
													{{ item.amount }}
												</view>
											</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				<theme-image class="popup-close-btn" src="@/static/mail/icon-popup-close.png" mode="aspectFit" @click.stop="hide"/>
			</view>
		</view>
		<TipsPopup
			ref="tipsPopupRef"
			:text="pageData.tipText"
		/>
	</view>
</template>

<script setup>
	import { ref, computed, reactive, onMounted, onUnmounted } from 'vue'
	import NormalPopupView from '@/components/popup/NormalPopupView.vue'
	import { useThemeStore } from '@/store/useThemeStore'
	import { usePromoStore } from '@/store/usePromoStore'
	import { useAppStore } from '@/store/useAppStore.js'
	import { useI18n } from 'vue-i18n'
	import { nextTick } from 'vue'
	import NormalTabs from '@/components/tabs/NormalTabs.vue'
	import { onBeforeUnmount } from 'vue'
	import { encipherAccountPhone } from "@/module/utils/encipherPhone.js";
	import { getPromoListApi, requestGetSpinReward, requestGetSpinRewardLog, requestClaimSpinAward, getSpinBigAward } from '@/api/promo.js'
	import Toast from '@/module/toast/toast.js'
	import { shareWithSystem } from '@/module/utils/system.js'
	import { formatDateStr } from '@/module/formatter/date-formatter'
	import TipsPopup from '@/components/popup/TipsPopup.vue'
	
	const { t } = useI18n()
	const themeStore = useThemeStore()
	const promoStore = usePromoStore()
	const appStore = useAppStore()

	const visible = ref(false)
	const emit = defineEmits(['confirm'])
	const prizeWrapRef = ref(null)
	const tipsPopupRef = ref(null)
	
	const pageData = reactive({
		activityId: null,
		tipText: '',
		myBonus: 0,
		finishStatus: 0,
		isRunning: false,
		prizeId: 0,
		baseRunAngle: 360 * 5,
		list: [],
		myList: [],
		bigList: [{}, {}, {}],
	})
	
	const getRotateAngle = () => {
		const prizeAngle = 360 / promoStore.turnplate.spinList.length
		return prizeAngle
	}
	
	const getTotalRunAngle = () => {
		const totalRunAngle = pageData.baseRunAngle + 360 - pageData.prizeId * getRotateAngle() - getRotateAngle() / 2
		return totalRunAngle
	}
	
	const bgColor = computed(() => {
		const _len = promoStore.turnplate.spinList.length
		const colorList = ['#ffffff', '#FFE08D']
		let colorVal = ''
		for (let i = 0; i < _len; i++) {
			colorVal += `${colorList[i % 2]} ${getRotateAngle() * i}deg ${getRotateAngle() * (i + 1)}deg,`
		}
		return `background: conic-gradient(${colorVal.slice(0, -1)});`
	})
	
	const prizeStyle = computed(() => {
		const _degree = getRotateAngle()
		return (i) => {
			return `
				width: ${2 * 225 * Math.sin(_degree / 2 * Math.PI / 180)}rpx;
				height: 225rpx;
				transform: rotate(${_degree * i + _degree / 2}deg);
				transform-origin: 50% 100%;
			`
		}
	})
	
	const loadData = async () => {
		const { code, data } = await requestGetSpinRewardLog({
			activityId: promoStore.turnplate.id,
			self: 0,
			page: 1,
			pageSize: 30
		})
		if (code !== 200) { return }
		pageData.list = data || []
	}
	
	const loadMyData = async () => {
		const { code, data } = await requestGetSpinRewardLog({
			activityId: promoStore.turnplate.id,
			self: 1,
			page: 1,
			pageSize: 30
		})
		if (code !== 200) { return }
		pageData.myList = data || []
	}
	
	const loadBigData = async () => {
		const { code, data } = await getSpinBigAward({
			activityId: promoStore.turnplate.id,
		})
		if (code !== 200) { return }
		pageData.bigList = data || []
	}
	
	const start = async () => {
		if (pageData.isRunning) { return }
		
		if (promoStore.turnplate.remainTimes === 0) {
			if (pageData.finishStatus === 1) {
				pageData.tipText = 'Your number of spins has been used up.'
				tipsPopupRef.value.show()
			} else {
				pageData.tipText = 'You have not yet met the spin requirements. Please review the rules to complete the requirements.'
				tipsPopupRef.value.show()
			}
			return
		}
		const { code, data } = await requestGetSpinReward({
			activityId: promoStore.turnplate.id
		})
		if (code !== 200) { return }
		
		pageData.isRunning = true
		
		
		
		const prizeId = data
		pageData.prizeId = prizeId
		startRun()
	}
	
	const startRun = () => {
		// 设置动效
		const style = `width: 100%;height: 100%;overflow: hidden;${bgColor.value} transform: rotate(${getTotalRunAngle()}deg);transition: all 4s ease;`
		document.getElementById('prize-wrap').style = style
		
		console.log('start run', style)
		
		setTimeout(() => {
			stopRun()
			loadMyBonusData()
			setTimeout(() => {
				loadMyData()
			}, 200)
			loadData()
			loadBigData()
		}, 4000)
	}
	
	const stopRun = () => {
		pageData.isRunning = false
		const style = `width: 100%;height: 100%;overflow: hidden;${bgColor.value} transform: rotate(${getTotalRunAngle() - pageData.baseRunAngle}deg);`
		document.getElementById('prize-wrap').style = style
		console.log('stop run', style)
		
		const getBonus = promoStore.turnplate.spinList[pageData.prizeId].amount
		pageData.tipText = `Congratulations on winning bonus ${getBonus}`
		tipsPopupRef.value.show()
	}
	
	const resetRun = () => {
		nextTick(() => {
			const style = `width: 100%;height: 100%;overflow: hidden;${bgColor.value} transform: rotate(0deg);`
			document.getElementById('prize-wrap').style = style
			console.log('reset run', style)
		})
	}
	
	const show = (id) => {
		visible.value = true
		if (id) {
			pageData.activityId = id
		} else {
			pageData.activityId = null
		}
		loadAllData(id)
	}
	
	const hide = () => {
		visible.value = false
	}
	
	const loadAllData = async (id) => {
		pageData.myBonus = 0
		resetRun()
		
		await promoStore.getSpinActivityData()
		if (pageData.activityId) {
			promoStore.turnplate.activityRewardList.forEach(el => {
				if (el.activityId === pageData.activityId) {
					promoStore.turnplate.id = el.activityId
					pageData.myBonus = el.yourBonus || 0
					pageData.finishStatus = el.finishStatus || 0
					promoStore.turnplate.remainTimes = el.remainTimes || 0
				}
			})
		} else {
			promoStore.turnplate.activityRewardList.forEach(el => {
				if (el.remainTimes > 0) {
					promoStore.turnplate.id = el.activityId
					pageData.myBonus = el.yourBonus || 0
					pageData.finishStatus = el.finishStatus || 0
					promoStore.turnplate.remainTimes = el.remainTimes || 0
				}
			})
		}
		
		loadPromoData()
		loadData()
		setTimeout(() => {
			loadMyData()
		}, 200)
		loadBigData()
	}
	
	const loadMyBonusData = async () => {
		await promoStore.getSpinActivityData()
		promoStore.turnplate.activityRewardList.forEach(el => {
			if (promoStore.turnplate.id === el.activityId) {
				pageData.myBonus = el.yourBonus || 0
				promoStore.turnplate.remainTimes = el.remainTimes || 0
			}
		})
	}
	
	const loadPromoData = async () => {
		const { code, data } = await getPromoListApi()
		
		if (code === 200 && data) {
			const turnplateData = data.find(el => {
				return el.jumpUrl === "module:spin" && el.id === promoStore.turnplate.id
			})
			if (turnplateData && turnplateData.content) {
				const tasks = JSON.parse(turnplateData.content || {})
				promoStore.turnplate.title = turnplateData.name || ''
				promoStore.turnplate.content = tasks
				promoStore.turnplate.spinList = tasks.spin_award || []
				promoStore.turnplate.rules = tasks.desc || []
			}
		}
	}

	const handleClaimClick = async () => {
		if(pageData.myBonus <= 0) { return }
		const { code, data } = await requestClaimSpinAward({
			activityId: promoStore.turnplate.id
		})
		if (code !== 200) { return }
		pageData.tipText = 'The bonus has been successfully received, please check the balance.'
		tipsPopupRef.value.show()
		loadAllData(promoStore.turnplate.id)
	}
	
	const handleMaskClick = () => {
	}
	
	const handleMaskMove = (e) => {
		// const listDoc = document.getElementById('list')
		// const touchX = e.target.offsetLeft
		// const touchY = e.target.offsetTop
		// if (touchX > listDoc.offsetLeft && touchX < listDoc.offsetLeft + listDoc.offsetWidth
		// && touchY > listDoc.offsetTop && touchY < listDoc.offsetTop + listDoc.offsetHeight) {
		// 	e.prevent()
		// }
		// console.log(111, e, listDoc.offsetTop, listDoc.offsetHeight, listDoc.offsetLeft)
	}
	
	const handleContentClick = () => {
	}

	defineExpose({
		show,
		hide
	})
</script>

<style lang="scss" scoped>
	.normal-popup-view-container {
		position: relative;
	}
	
	.normal-popup-view {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 1001;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #00000090;
	}
	
	.normal-popup-content {
		position: absolute;
		top: 70rpx;
		z-index: 1;
	}
	
	.popup-close-btn {
		width: 60rpx;
		height: 60rpx;
		position: absolute;
		right: -20rpx;
		top: -20rpx;
	}
	
	.popup-content-view {
		border-radius: 20rpx;
		width: 650rpx;
		height: 80vh;
		padding: 30rpx;
	}
	
	.tips-popup-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		
		.title {
			font-size: 38rpx;
			font-weight: bold;
		}
		
		.text {
			margin-top: 50rpx;
			font-size: 30rpx;
			// overflow-y: scroll;
		}
		
		.act-btn {
			width: 132rpx;
			height: 40rpx;
			border-radius: 20rpx;
			font-size: 20rpx;
			text-align: center;
			line-height: 40rpx;
		}
		
		.act-btn.disable {
			background: #f7f7f7;
		}
		
		.spin-container {
			margin-top: 16rpx;
			width: 450rpx;
			height: 450rpx;
			position: relative;
			
			.spin-round-bg {
				position: absolute;
				z-index: 1;
				left: 0;
				right: 0;
				bottom: 0;
				top: 0;
				width: 100%;
				height: 100%;
			}
			
			.spin-arrow-top {
				position: absolute;
				z-index: 3;
				top: 0px;
				left: calc(50% - 80rpx);
				width: 160rpx;
				height: 60rpx;
			}
			
			.spin-btn {
				position: absolute;
				left: calc(50% - 65rpx);
				top: calc(50% - 110rpx);
				z-index: 3;
				width: 130rpx;
				height: 170rpx;
				cursor: pointer;
				
				.spin-btn-img {
					width: 100%;
					height: 100%;
				}
				
				.spin-btn-text {
					position: absolute;
					top: 65rpx;
					left: 20rpx;
					right: 20rpx;
					bottom: 10rpx;
					z-index: 1;
					font-size: 12rpx;
					color: #E71A50;
					text-align: center;
					
					.spin-title {
						font-size: 28rpx;
						color: #ffffff;
						text-stroke: 2rpx #E16410;
						font-weight: 1000;
						-webkit-text-stroke: 2rpx #E16410;
					}
				}
			}
			
			.prize-list {
				width: 100%;
				height: 100%;
				border-radius: 50%;
				overflow: hidden;
				
				.prize-item {
					position: absolute;
					left: 0;
					right: 0;
					top: 0;
					z-index: 1;
					margin: auto;
					
					.prize-item-img {
						width: 45rpx;
						height: 45rpx;
						margin: 20rpx auto 10rpx;
						display: block;
					}
					
					.prize-item-title {
						color: #DF0404FF;
						font-size: 26rpx;
						text-align: center;
						line-height: 30rpx;
						margin-top: 45rpx;
						font-weight: bold;
						font-family: 'Arial-Black';
					}
				}
			}
		}
		
		.list-container {
			width: 100%;
			box-sizing: border-box;
			
			.list-scroll {
				height: calc(85vh - 70rpx - 850rpx);
				overflow-y: scroll;
			}
			
			.list-item {
				width: 100%;
				border-radius: 20rpx;
				display: flex;
				height: 50rpx;
				justify-content: space-around;
				text-align: center;
				line-height: 50rpx;
				margin-top: 12rpx;
				
				.list-value {
					font-size: 24rpx;
					min-width: 25%;
				}
			}
			
			.list-item.top3 {
				border: 1rpx solid #F8EB59;
				background: linear-gradient(180deg, #FA6767, #F51212, #A00A12, #F3444D);
				font-weight: bold;
				font-size: 24rpx;
				color: #F8EB59;
				text-stroke: 1rpx #A31317;
				-webkit-text-stroke: 1rpx #A31317;
			}
		}
	}
</style>