<template>
	<uni-popup ref="turntablePopup" type="center" :is-mask-click="false">
		<view class="turntable">
			<image class="turntable-bg" src="https://cos.his.cdwjyyh.com/fs/20250910/de386927c5f44e02ab3ecc480ddb9797.png" mode="aspectFit"></image>
			<view class="turntable-box">
				<view class="turntable-wrap">
					<view class="turntable-item" :class="{ active: idx == light,disabled: item.isReceive }"
						v-for="(item,idx) in cells" :key="idx">
						<image :src="item.iconUrl" mode="aspectFit"></image>
						<view class="ellipsis">{{item.name}}</view>
					</view>
				</view>
			</view>
			<image class="close" src="https://cos.his.cdwjyyh.com/fs/20250910/93608bad8ad1479a854ec26e8eaaacea.png" @click="close"></image>
			<view class="btn-box">
				<image src="https://cos.his.cdwjyyh.com/fs/20250910/fe230bfdf74f4f0dac88af53f709d6c5.png" mode="widthFix" :class="isReceive==1 ?'gray':''" @click="start"></image>
			</view>
		</view>
	</uni-popup>
</template>

<script>
	import {getVideoRewardRules} from "@/api/course.js"
	export default {
		data() {
			return {
				baseUrl: uni.getStorageSync('requestImagesPath'),
				light: -1,
				running: false,
				targetIdx: -1,
				total: 0,
				speed: 100,
				cells:[],
				timer: null,
				isReceive: 0,
				stepAudio: null,   // 跳动音
				winAudio: null     // 中奖音
			}
		},
		computed: {
			// 剩余可用索引
			availIdx() {
				return this.cells.map((_, i) => i).filter(i => !this.cells[i].isReceive)
			},
			// 是否全部抽完
			allDone() {
				return this.availIdx.length === 0
			}
		},
		methods: {
			initAudio() {
			    this.stepAudio = uni.createInnerAudioContext();
			    this.stepAudio.src = 'https://fs-1319721001.cos.ap-chongqing.myqcloud.com/audio/spin.mp3';
			    this.stepAudio.volume = 0.6;
			
			    this.winAudio = uni.createInnerAudioContext();
			    this.winAudio.src = 'https://fs-1319721001.cos.ap-chongqing.myqcloud.com/audio/win.mp3';
			    this.winAudio.volume = 1;
			},
			getVideoRewardRules(urlOption) {
				const param = {
					type: 4,
					...urlOption
				}
				getVideoRewardRules(param).then(res=>{
					if(res.code == 200) {
						this.cells = res.data || []
						this.total = this.cells.length
						this.isReceive = this.cells.every(item => item.isReceive == true)? 1 :0
					}else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			},
			open(urlOption) {
				this.initAudio();
				this.$refs.turntablePopup.open()
				this.getVideoRewardRules(urlOption)
			},
			close(type) {
				if(type=='close') {
					this.running = false
					clearInterval(this.timer)
				}
				if (this.running) {
					uni.showToast({
						title: '抽取中，请勿关闭',
						icon: 'none'
					})
					return
				}
				this.$refs.turntablePopup.close()
			},
			start() {
				if (this.running) {
					uni.showToast({
						title: '抽取中',
						icon: 'none'
					})
					return
				}
				if(this.isReceive == 1) return
				this.running = true
				clearInterval(this.timer)
				let last = -1
				if(this.availIdx.length >1) {
					this.timer = setInterval(() => {
						let next;
						do {
						  next = this.availIdx[Math.floor(Math.random() * this.availIdx.length)];
						} while (next === last);
						last = next;
						this.light = next;
						this.stepAudio.stop();  // 停掉上一声（防止重叠）
						this.stepAudio.play();  // 播放跳动音
					}, this.speed)
				}
				this.$emit('sendRewardFun',4)
			},
			endSuccess(code) {
				this.targetIdx = this.cells.findIndex(it=>it.code == code)
				clearInterval(this.timer)
				this.timer = null
				if(this.targetIdx==-1) {
					uni.showToast({
						title: '抽奖失败',
						icon: 'none'
					})
					return
				}
				const STEP = 100;                          // 每格固定 100 ms
				const MIN_STEP = 10;                       // 最少 10 步 → 1 s
				this.speed = STEP;
				let totalSteps = Math.max(MIN_STEP, this.availIdx.length);
				// 约 2.5s / 100ms
				let step = 0
				let last = -1
				const that = this
				if(this.availIdx.length <= 1) {
					this.light = this.targetIdx
					this.stepAudio.stop();
					this.winAudio.play();   // 播放中奖音
					this.running = false
					this.isReceive = 1
					uni.showModal({
						title: '恭喜，中奖',
						content: this.cells[this.targetIdx].name,
						showCancel: false,
						success: function (res) {
							if (res.confirm) {
								if (that.stepAudio) {
									that.stepAudio.stop();
									that.stepAudio.destroy();
									that.stepAudio = null;
								}
								if (that.winAudio) {
									that.winAudio.stop();
									that.winAudio.destroy();
									that.winAudio = null;
								}
								that.$refs.turntablePopup.close()
								that.$emit("openAppPop")
							}
						}
					});
					return
				}
				this.timer = setInterval(() => {
					let next
					do {
						next = this.availIdx[Math.floor(Math.random() * this.availIdx.length)]
					} while (next === last)
					last = next
					this.light = next
					this.stepAudio.stop();  // 停掉上一声（防止重叠）
					this.stepAudio.play();  // 播放跳动音
					step++
				
					if (step >= totalSteps) {
						clearInterval(this.timer)
						this.light = this.targetIdx
						this.stepAudio.stop();
						this.winAudio.play();   // 播放中奖音
						// 置灰
						this.running = false
						this.isReceive = 1
						setTimeout(()=>{
							uni.showModal({
								title: '恭喜，中奖',
								content: this.cells[this.targetIdx].name,
								showCancel: false,
								success: function (res) {
									if (res.confirm) {
										if (that.stepAudio) {
											that.stepAudio.stop();
											that.stepAudio.destroy();
											that.stepAudio = null;
										}
										if (that.winAudio) {
											that.winAudio.stop();
											that.winAudio.destroy();
											that.winAudio = null;
										}
										that.$refs.turntablePopup.close()
										that.$emit("openAppPop")
									}
								}
							});
						},500)
						// this.cells[this.targetIdx].isReceive = true
					}
				}, this.speed)
			}
		}
	}
</script>

<style scoped lang="scss">
	.gray {
	  filter: grayscale(1);   /* 1 = 100% 灰度 */
	}
	.close {
		width: 64rpx;
		height: 64rpx;
		position: absolute;
		top:  88rpx;
		right: 20rpx;
		z-index: 2;
	}

	.active {
		transform: scale(1.05);
		background: linear-gradient(0deg, #FFD44F 0%, #FFFABD 100%) !important;
		box-shadow: 0rpx 2rpx 0rpx 0rpx #FFFCF5 !important;
	}

	.disabled {
		filter: grayscale(1) brightness(0.7);
		opacity: 0.5;
	}

	.btn-box {
		width: 540rpx;
		height: 104rpx;
		position: absolute;
		bottom: 46rpx;
		left: 50%;
		transform: translateX(-50%);
		z-index: 2;

		image {
			width: 100%;
			height: auto;
		}
	}

	.turntable {
		width: 750rpx;
		height: 1056rpx;
		position: relative;
		&-bg {
			width: 100%;
			height: 100%;
			position: absolute;
			top: 0;
			left: 0;
			z-index: 1;
		}

		&-box {
			position: absolute;
			bottom: 174rpx;
			left: 50%;
			transform: translateX(-50%);
			z-index: 2;
			width: 623rpx;
			height: 628rpx;
			padding: 16rpx 0 8rpx 16rpx;
			box-sizing: border-box;
		}

		&-wrap {
			display: flex;
			flex-wrap: wrap;
		}

		&-item {
			width: 112rpx;
			height: 112rpx;
			background: linear-gradient(0deg, #FCEFCA 0%, #FFFFFF 100%);
			border-radius: 16rpx;
			font-family: PingFang SC;
			font-weight: 500;
			font-size: 20rpx;
			color: #333333;
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;
			margin: 0 8rpx 8rpx 0;
			transition: transform 0.2s, box-shadow 0.2s;

			image {
				width: 45rpx;
				height: 63rpx;
			}

			.ellipsis {
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}
		}
	}
</style>