<template>
	<view class="luckyDraw">
		<image src="../../static/backImg.png" class="back" mode="widthFix"></image>
		<view class="luckyDrawContent">
			<!-- 个人信息模块 -->
			<view class="luckyDrawTop">
				<view class="left">
					<view class="avatarView" @click="startAni(3)">
						<!-- <open-data type="userAvatarUrl" class="avatar"></open-data> -->
						<image src="../../static/avatar.png" mode="widthFix"></image>
					</view>
					<view class="userInfo">
						<view class="account" v-if="mpName">{{mpName}}</view>
						
						<view class="ID" v-if="mpData.mpAppId">
							<text>书币：{{balanceCount}}</text>
							<navigator :url="`../extractBookCurr/extractBookCurr?mpAppId=${mpData.mpAppId}&mpOpenId=${mpData.mpOpenId}`" class="extract" hover-class="none">提取</navigator>
						</view>
						<view class="ID" v-else>ID:{{userId}}</view>
					</view>
				</view>
				<navigator :url="'../checkInRecord/checkInRecord' + getSerialize({...mpData, openId})" class="right" hover-class="none">
					<text>中奖记录</text>
				</navigator>
			</view>
			
			<!-- 滚动通知 -->
			<view class="notice">
				<image src="../../static/horn.png" class="horn" mode="widthFix"></image>
				<view class="txts">
					<u-notice-bar mode="vertical" :volume-icon="false" color="#FFFFFF" type="none" :list="list"></u-notice-bar>
				</view>
			</view>
			
			
			<!-- 去抽奖路口 -->
			<view class="qLuckDraw" @click="jumpSign">
				<image src="../../static/redEnv.png" mode="widthFix"></image>
			</view>
			
			<!-- 大转盘 -->
			<view class="turntable">
				<view class="decorate">
					<image src="../../static/decorate.png" class="decorateBack" mode="widthFix"></image>
					<image src="../../static/chassis.png" class="decorateChassis" mode="widthFix"></image>
				</view>
				<view class="turntableContent">
					<view class="al">
						<almost-lottery
							:canvasId="canvasConfig.canvasId"
							:canvasWidth="canvasConfig.width"
							:canvasHeight="canvasConfig.height"
							:outerWidth="canvasConfig.outerWidth"
							:outerHeight="canvasConfig.outerHeight"
							:colors="canvasConfig.colors"
							:ringCount="8"
							:duration="5" 
							:prizeList="prizeList"
							:prizeIndex="prizeIndex"
							@reset-index="prizeIndex = -1"
							@draw-start="handleDrawStart"
							@draw-end="handleDrawEnd"
							@finish="handleDrawFinish"
							v-if="prizeList.length"
						/>
					</view>
					<view class="bottom">
						<view class="cont">今日剩余抽奖次数：<text>{{freeNum}}</text></view>
					</view>
				</view>
			</view>
			
			<view style="margin: 0 30rpx;" v-if="adConfig.bannerAd">
				<ad-view :unitId="adConfig.bannerAd" adIntervals="200"></ad-view>
			</view>
			
			<!-- 我的奖品 -->
			<view class="myPrize">
				<view class="title">我的奖品</view>
				<view class="chips">
					<view class="chip" v-for="(item, index) in prizeCountDtoList" :key="index">
						<image src="../../static/iPhone12Chip.png" mode="widthFix" v-if="item.prizeType === 3"></image>
						<image src="../../static/vipChip.png" mode="widthFix" v-else></image>
						<view class="text">{{item.prizeName}}</view>
						<view class="progress">
							<view class="value" :style="{width: item.prizeCount && item.prizeCount > 0 ? (item.prizeCount/item.maxCount*100) + '%' : '0'}"></view>
							<text>{{item.prizeCount}}/{{item.maxCount}}</text>
						</view>
					</view>
				</view>
				<view class="clearTime" v-if="clearTime">碎片有效期至：{{clearTime | getTimerFilter}} </view>
			</view>
		
			<!-- 活动规则模块 -->
			<view class="activityRules">
				<view class="top" @click="activityRulesHandle">
					<text>活动规则</text>
					<image :src="!activityRules ? '../../static/unfold.png' : '../../static/retract.png'" mode="widthFix"></image>
				</view>
				<view class="bottom" v-if="activityRules">
					<view>1、每个用户账户每天最多有10次抽奖机会，每天0点刷新。</view>
					<view>2、每天前2次可直接领取抽奖奖品，其他8次抽奖机会需要通过观看激励视频来获得。</view>
					<view>3、用户必须在对应公众号内登陆抽奖，否则书币将无法顺利领取。</view>
					<view>4、书币及7天书城VIP会员抽中后自动发放至书城账号，可在中奖记录中查看，或进入书城的“个人中心-充值记录-赠送”查看。</view>
					<view>5、用户可以通过完成本产品抽奖获得碎片，碎片种类由系统随机发放，兑换手机需集满50个碎片， 兑换书城VIP需集满30个碎片。碎片累计有效期为7天，在碎片超出有效期后或用户成功兑换奖品后，此前已获得的该奖品碎片都将清零。</view>
					<view>6、实物奖品请联系公众号内客服领取，实物奖品颜色随机寄送，以中奖用户收到的实物为准。</view>
					<view>7、若发现用户恶意违规行为，开发者有权取消其获奖资格。</view>
					<view>8、本活动解释权由开发者所有，有任何疑问请联系公众号内客服。</view>
				</view>
			</view>
			
			<!-- 弹窗 -->
			<view class="popup" v-if="popupShow">
				<view class="popupContent">
					<view class="content">
						<image src="../../static/popupBack.png"></image>
						<view class="textCon">
							<text class="ts">恭喜您获得</text> </br>
							<text class="reward ts">{{luckyDay.name}}</text> </br>
							<image src="../../static/doubleBt.png" class="doubleBt" mode="widthFix" :style="{transform: `scale(${scale})`}" @click="lookVideo"></image> </br>
							<text class="bt" @click="receiveGold(false)">不了，单倍领取</text>
						</view>
					</view>
					<image src="../../static/close.png" class="close" mode="widthFix" @click="closeHandle"></image>
				</view>
			</view>
			<!-- 弹窗VIP -->
			<view class="popupVIP popup" v-if="popupVIPShow">
				<view class="popupContent" style="width: 524rpx;">
					<view class="content">
						<image src="../../static/vipBack.png"></image>
						<view class="textCon" style="display: flex; align-items: flex-end;">
							<view class="againLuckDrawBt btVip" @click="againLuckDraw('vip');startAni(2)" :style="{transform: `scale(${scale})`}">再次抽奖</view>
						</view>
					</view>
					<image src="../../static/close.png" class="close" mode="widthFix" @click="popupVIPShow = false;startAni(2); showCpAd()"></image>
				</view>
			</view>
			<!-- 弹窗12 -->
			<view class="popup12 popup" v-if="popup12Show">
				<view class="popupContent" style="width: 702rpx;">
					<view class="content">
						<image src="../../static/12Back.png" style="height: 722rpx;"></image>
						<view class="textCon" style="display: flex; align-items: flex-end;">
							<view class="againLuckDrawBt" @click="againLuckDraw('12'); startAni(3)" :style="{transform: `scale(${scale})`, marginBottom: 0}">再次抽奖</view>
						</view>
					</view>
					<image src="../../static/close.png" class="close" mode="widthFix" @click="popup12Show = false; startAni(3); showCpAd()"></image>
				</view>
			</view>
			<!-- 弹窗金币 -->
			<view class="popup12 popup" v-if="popupGoldShow">
				<view class="popupContent" style="width: 636rpx;">
					<view class="content">
						<image src="../../static/goldBack.png" style="height: 790rpx;"></image>
						<view class="textCon" style="display: flex; align-items: center; flex-direction: column; justify-content: flex-end;">
							<text class="goldText">恭喜您获得</text> </br>
							<text class="goldText" style="margin-bottom: 48rpx;">{{luckyDay.name}}</text>
							<view class="againLuckDrawBt btGold" @click="againLuckDraw('gold'); startGold(false)" :style="{transform: `translateX(12rpx) scale(${scale})`}">再次抽奖</view>
						</view>
					</view>
					<image src="../../static/close.png" class="close" mode="widthFix" @click="popupGoldShow = false; startGold(false); showCpAd()"></image>
				</view>
			</view>
		
			<!-- 碎片飞行 -->
			<view class="fragmentAni" :animation="animationData">
				<image :src="prizeType === 3 ? '../../static/turntable_iPhone12.png' : '../../static/turntable_VIP.png'" mode="widthFix"></image>
			</view>
			<!-- 金币飞行组 -->
			<view class="fragmentGold" :animation="animationDatas[index]" v-for="(item, index) in goldData" :key="index" :style="{top: item.top, left: item.left}">
				<image src="../../static/turntable_gold.png" mode="widthFix"></image>
			</view>
			<!-- 弹窗提示 -->
			<view class="receiveTs" :animation="animationDataTs">
				{{tsTitle}}
			</view>
			
			<!-- 格子广告 -->
			<view class="singleLattice" v-if="adConfig.singleLatticeAd">
				<ad-custom-view :unit-id="adConfig.singleLatticeAd" adIntervals="200"></ad-custom-view>
			</view>
		</view>
	</view>
</template>

<script>
	let timer = null, powerOnTimer = null, adTimer = null, lqTimer = null;
	import AlmostLottery from '@/uni_modules/almost-lottery/components/almost-lottery/almost-lottery.vue'
	import { config, getHome, getOpenId, getBanner, setDrawGain, getPond, setReceive, getVersion, getBalance } from '@/api/api.js'
	import { clearCacheFile } from '@/uni_modules/almost-lottery/utils/almost-utils.js'
	import { bannerAd, urgeVideoAd, insertScreenAd, singleLatticeAd } from '@/utils/ad_config.js'
	import adView from '@/components/ad-view/ad-view.vue'
	import adCustomView from '@/components/ad-custom-view/ad-custom-view.vue'
	const systemInfo = uni.getSystemInfoSync()
	export default {
		components: {
			AlmostLottery,
			adView,
			adCustomView
		},
		data() {
			return {
				title: 'Hello',
				adConfig: {
					bannerAd,
					singleLatticeAd
				},
				list: [
					'恭喜用户 “9016” 成功提现 2000书币',
					'恭喜用户 “9017” 成功提现 10书币',
					'恭喜用户 “9018” 成功提现 20书币',
					'恭喜用户 “9019” 成功提现 100书币'
				],
				// canvas id、宽、高
				canvasConfig: {
					canvasId: 'almostLotteryCanvas',
					width: 280,
					height: 280,
					outerWidth: 305,
					outerHeight: 305,
					colors: [
						'#FEE3C6',
						'#FFFFFF'
					]
				},
				// 以下是奖品配置数据
				// 奖品数据
				prizeList: [],
				// 中奖下标
				prizeIndex: -1,
				// 是否正在抽奖中，避免重复触发
				prizeing: false,
				
				// 以下为业务需求有关示例数据
				// 当日免费抽奖次数余额
				freeNum: 10,
				
				// 以下是
				// 活动规则开关控制
				activityRules: false,
				// 弹窗控制
				popupShow: false,
				// 抽到VIP碎片弹窗控制
				popupVIPShow: false,
				// 抽到12碎片弹窗控制
				popup12Show: false,
				// 抽到金币弹窗控制
				popupGoldShow: false,
				
				openId: '',
				mpData: {},
				prizeCountDtoList: [], // 碎片列表
				mpName: null, // 渠道号 
				userId: 91874, // 
				luckyDay: {}, // 中奖信息
				doubleKey: "", // 领取key
				clearTime: "", // 碎片有效期
				scale: 1,
				animation: null,  // 动画实例
				animationData: null, // 动画
				animationDatas: [null, null, null, null, null, null, null, null], // 动画组
				animationDataTs: null,
				prizeType: 3, // 奖品类型
				durationMath: 20,  // 防止动画每次都一样
				durationMath1: 20,
				durationMath2: 20,
				goldData: [
					{top: '404rpx', left: '300rpx'},
					{top: '434rpx', left: '240rpx'},
					{top: '430rpx', left: '398rpx'},
					{top: '448rpx', left: '424rpx'},
					{top: '380rpx', left: '412rpx'},
					{top: '332rpx', left: '332rpx'},
					{top: '356rpx', left: '240rpx'},
					{top: '474rpx', left: '294rpx'}
				],
				tsTitle: '',   //提示信息
				remoteVersion: null,
				loading: false,
				_isLoaded: false,
				powerOnCount: 0,  // 记录开机秒数
				powerOnTimer: new Date().getTime(), // 保存当前进入页面的时间挫
				videoType: null,  // 1 前面两次看视频翻倍 2 后面8次看视频抽奖
				
				// 本地
				weightTotal: 0,
				// 权重数组
				weightArr: [],
				balanceCount: 0,
			}
		},
		computed: {
			isApple() {
				return uni.getSystemInfoSync().platform === 'ios'
			}
		},
		onLoad(options) {
			// 请求奖品数据
			this.mpData = options
			this.getData()
			this.animation = uni.createAnimation({ timingFunction: 'ease' })
			getVersion({appId: config.appid}).then(res => {
				this.remoteVersion = res.data
			})
		},
		onUnload() {
			uni.hideLoading()
			timer && clearInterval(timer)
			lqTimer && clearInterval(lqTimer)
			adTimer && clearTimeout(adTimer)
			powerOnTimer && clearInterval(powerOnTimer)
			this.interstitialAd.destroy()
		},
		onHide() {
			console.log('页面隐藏')
			timer && clearInterval(timer)
			lqTimer && clearTimeout(lqTimer)
			adTimer && clearTimeout(adTimer)
			powerOnTimer && clearInterval(powerOnTimer)
		},
		onShareAppMessage() {},
		filters: {
			getTimerFilter(value) { // 获取年月日时分秒
				if(!value) return ""
				let timestamp = Date.parse(new Date(value))
				let date = new Date(timestamp)
				let Y = date.getFullYear()
				let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1)
				let D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
				
				let H = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
				let minute = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
				let S = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
				
				return `${Y}-${M}-${D} ${H}:${minute}:${S}`
			}
		},
		async onPullDownRefresh() {
			await this.handleInitCanvas()
			await this.getList()
			uni.stopPullDownRefresh();
		},
		onReady() {
			if(urgeVideoAd) {
				this.createInterstitialAd()
				this.powerOnShowAd()
			}
		},
		watch: {
			// 监听获奖序号的变动
			popupShow(newVal, oldVal) {
				this.openAniBt(newVal)
			},
			popupVIPShow(newVal) {
				this.openAniBt(newVal)
			},
			popup12Show(newVal) {
				this.openAniBt(newVal)
			},
			popupGoldShow(newVal) {
				this.openAniBt(newVal)
			}
		},
		methods: {
			// 获取金币余额
			getBookCurr() {
				getBalance({appId: config.appid, mpAppId: this.mpData.mpAppId, mpOpenId: this.mpData.mpOpenId}).then(res => {
					this.balanceCount = res.data || 0
				})
			},
			powerOnShowAd() {
				// 开机25秒调取弹窗广告 以后没5分钟调取
				powerOnTimer = setInterval(() => {
					this.powerOnCount += 1
					if(this.powerOnCount === 25 || this.powerOnCount % 325 === 0) {
						this.showInterstitialAd()
					}
				}, 1000)
			},
			// 创建插屏广告 激励视频广告
			createInterstitialAd() {
				// 创建插屏广告
				let interstitialAd = this.interstitialAd = uni.createInterstitialAd({adUnitId: insertScreenAd});
				interstitialAd.onLoad(() => {
					// 插屏 广告加载成功 
					console.log("插屏 广告加载成功");
					this.loading = false;
				});
				interstitialAd.onClose(() => {
					// 用户点击了关闭或返回键(仅Android有返回键)
					console.log("插屏 广告关闭");
				});
				interstitialAd.onError((err) => {
					// 插屏 广告加载失败
					console.log("插屏 广告加载失败", err);
					this.loading = false;
				});
				// 广告实例创建成功后默认会执行一次 load，加载广告数据
				// 如果界面有 "显示广告" 按钮，需要先禁用掉，防止用户点击，等待广告数据加载成功后在放开
				this.loading = true;
				
				// 激励视频广告
				this._isLoaded = false
				let rewardedVideoAd = this._rewardedVideoAd = uni.createRewardedVideoAd({ adUnitId: urgeVideoAd })
				rewardedVideoAd.onLoad(() => {
					this._isLoaded = true
					console.log('onLoad event')
					// 加载激励视频成功
					// 当激励视频被关闭时，默认预载下一条数据，加载完成时仍然触发 `onLoad` 事件
				})
				rewardedVideoAd.onError((err) => {
					// 加载激励视频失败
					this._isLoaded = false
					console.log('onError event', err)
				})
				rewardedVideoAd.onClose((res) => {
					// 用户点击了【关闭广告】按钮
					console.log('==============>', res)
					if (res && res.isEnded) {
						// 正常播放结束
						if(this.videoType === 1){ // 看视频翻倍领取
							this.receiveGold(true)
						} else if (this.videoType === 2) { // 看视频抽奖
							if (!this.mpName) {  // 首次没有重公众号进入
								this.localGetPrizeIndex()
								return
							}
							this.remoteGetPrizeIndex()
						}
					} else {
						// 播放中途退出
						this.prizeing = false
						this.freeNum++
					}
				})
			},
			// 抽完奖显示插屏广告
			showCpAd () {
				lqTimer && clearTimeout(lqTimer)
				setTimeout(() => {
					this.showInterstitialAd()
				}, 10000)
			},
			// 显示插屏广告广告
			showInterstitialAd() {
				// 调用 interstitialAd.show()，如果数据正在加载中不会显示广告，加载成功后才显示
				// 在数据没有加载成功时，需要防止用户频繁点击显示广告
				if(!insertScreenAd) {
					console.log('没有插屏广告')
					return
				}
				if(adTimer) {
					clearTimeout(adTimer)
				}
				let newT = new Date().getTime()
				if (((newT / 1000) - (this.powerOnTimer / 1000)) < 15) {  // 判断是否开机15秒
					adTimer = setTimeout(() => {
						if (this.loading == true) {
							return
						}
						this.loading = true;
						this.interstitialAd.show().then((res) => {
							console.log('插屏广告成功---》', res)
							this.loading = false;
						}).catch(err => {
							console.log('插屏广告错误---》', err)
						});
						clearTimeout(adTimer)
					}, newT - this.powerOnTimer + 1000)
					return
				}
				if (this.loading == true) {
					return
				}
				console.log(11111)
				this.loading = true;
				this.interstitialAd.show().then((res) => {
					console.log('插屏广告成功---》', res)
					this.loading = false;
				}).catch(err => {
					console.log('插屏广告错误---》', err)
				});
			},
			// 显示激励视频广告
			showVideoAd(type) {
				console.log('显示激励视频广告')
				this.videoType = type
				if (this._isLoaded) {
					uni.showLoading({
						title: '正在拉取~~',
					})
					this._rewardedVideoAd.show().then(()=>{
						uni.hideLoading()
						console.log('拉取视频then')
					}).catch((err) => {
						console.log('拉取视频catch', err)
						uni.hideLoading()
						this._rewardedVideoAd && this._rewardedVideoAd.load().then(() => this._rewardedVideoAd && this._rewardedVideoAd.show()).catch(err => {
							uni.showToast({
								title: '当前无视频广告',
								icon: 'none'
							})
						})
					})
				} else {
					if(this.videoType === 1){ // 看视频翻倍领取
						this.receiveGold(true)
					} else if (this.videoType === 2) { // 看视频抽奖
						if (!this.mpName) {  // 首次没有重公众号进入
							this.localGetPrizeIndex()
							return
						}
						this.remoteGetPrizeIndex()
					}
				}
			},
			// 是否开始呼吸开关动画
			openAniBt(val) {
				if(val) {
					timer = setInterval(() => {
						if(this.scale === 1) {
							this.scale = 0.92
						}else {
							this.scale = 1
						}
					}, 500)
				} else {
					timer && clearInterval(timer)
				}
			},
			// 开始动画 12 vip 碎片
			startAni(prizeType = 3) {
				if(prizeType === 3 || prizeType === 2) {
					this.prizeType = prizeType
					this.startTsAni(false)
					let index = this.prizeCountDtoList.findIndex(item => item.prizeType === prizeType)
					let left = index !== -1 ? index === 0 ? '150rpx' : '500rpx' : '500rpx'
					this.animation.opacity(1).step({ duration: this.durationMath })
					if( this.durationMath >= 50 ) {
						this.durationMath = 20
					} else {
						this.durationMath = this.durationMath + 1
					}
					// this.animation.top('1300rpx').left(left).step({ duration: 1200, delay: 100 })
					this.animation.top('76rpx').left('60rpx').step({ duration: 1000, delay: 100 })
					this.animation.opacity(0).top('453rpx').left('331rpx').step({ duration: 0 })
					this.animationData = this.animation.export()
				}
			},
			startGold(watchVideos) {
				this.prizeType = 1
				this.startTsAni(watchVideos)
				if( this.durationMath1 >= 50 ) {
					this.durationMath1 = 20
				} else {
					this.durationMath1 = this.durationMath1 + 1
				}
				this.animationDatas = this.goldData.map(item => {
					let animation = uni.createAnimation({ timingFunction: 'ease' })
					animation.opacity(1).step({ duration: this.durationMath1 })
					animation.top('76rpx').left('60rpx').step({ duration: Math.floor(Math.random() * 101) + 1000, delay: 100 })  //  
					animation.opacity(0).top(item.top).left(item.left).step({ duration: 0 })
					return animation.export()
				})
			},
			startTsAni(watchVideos) {
				if(this.prizeType === 1) {
					if (watchVideos) {
						this.tsTitle = '+' + (this.luckyDay.prizeCount * 2) + this.luckyDay.prizeName
					} else {
						this.tsTitle = '+' + this.luckyDay.name
					}
				} else {
					this.tsTitle = this.luckyDay.prizeName + '+1'
				}
				if( this.durationMath2 >= 50 ) {
					this.durationMath2 = 20
				} else {
					this.durationMath2 = this.durationMath2 + 1
				}
				let animation = uni.createAnimation({ timingFunction: 'ease' })
				animation.opacity(1).step({ duration: this.durationMath2 })
				animation.top('250rpx').step({ duration: 1000, delay: 100 })
				animation.opacity(0).top('450rpx').step({ duration: 0 })
				this.animationDataTs = animation.export()
			},
			// 再次抽奖
			againLuckDraw(type) {
				if (type === 'vip') {
					this.popupVIPShow = false
				} else if (type === '12') {
					this.popup12Show = false
				} else {
					this.popupGoldShow = false
				}
				this.handleDrawStart()
			},
			// 看视频双倍
			lookVideo() {
				this.showVideoAd(1)
			},
			// 领取金币
			receiveGold(watchVideos = false) {
				if (!this.mpName) {  // 首次没有重公众号进入
					this.startGold(watchVideos)
					this.popupShow = false
					return
				}
				if(this.doubleKey) {
					setReceive({appId: config.appid, doubleKey: this.doubleKey, openId: this.openId, watchVideos, ...this.mpData }).then(res => {
						this.startGold(watchVideos)
						this.popupShow = false
						this.doubleKey = ""
						this.getList()
						if(watchVideos) {
							
						} else {
							this.showInterstitialAd()
						}
					})
				}
			},
			// 
			getData() {
				uni.login({
					success: async res => {
						if (res.code) {
							let openIDInfo = await getOpenId({appId: config.appid, code: res.code})
							this.openId = openIDInfo.data
							let response = await this.getList()
							if(response) {
								await this.getPrizeList()
								getBanner({appId: config.appid, openId: this.openId, mpAppId: this.mpData.mpAppId}).then(res => {
									this.list = res.data
								})
							} else {
								this.prizeList = [
									{"prizeId":1,"name":"100书币","stock":100,"prizeCount": 100,"prizeName": '书币',"weight":0.1,"prizeType": 1,"prizeImage":"/static/turntable_golds.png"},
									{"prizeId":2,"name":"书城VIP碎片","stock":100,"weight":5,"prizeType": 2,"prizeImage":"/static/turntable_VIP.png"},
									{"prizeId":3,"name":"30书币","stock":100,"prizeCount": 30,"prizeName": '书币',"weight":1,"prizeType": 1,"prizeImage":"/static/turntable_gold.png"},
									{"prizeId":4,"name":"书城VIP碎片","stock":100,"weight":5,"prizeType": 2,"prizeImage":"/static/turntable_VIP.png"},
									{"prizeId":5,"name":"10书币","stock":100,"prizeCount": 10,"prizeName": '书币',"weight":10000,"prizeType": 1,"prizeImage":"/static/turntable_gold.png"},
									{"prizeId":6,"name":"50书币","stock":100,"weight":1,"prizeCount": 50,"prizeName": '书币',"prizeType": 1,"prizeImage":"/static/turntable_golds.png"},
									{"prizeId":7,"name":"iPhone12碎片","stock":100,"weight":5,"prizeType": 3,"prizeImage":"/static/turntable_iPhone12.png"},
									{"prizeId":8,"name":"20书币","stock":100,"prizeCount": 20,"prizeName": '书币',"weight":10000,"prizeType": 1,"prizeImage":"/static/turntable_gold.png"}]
								this.prizeCountDtoList = [{"prizeType":2,"prizeCount":0,"prizeName":"书城VIP碎片","maxCount":30},{"prizeType":3,"prizeCount":0,"prizeName":"iPhone12碎片","maxCount":50}]
							
								this.prizeList.forEach((item) => this.weightTotal += item.weight)
								this.weightArr = this.prizeList.map((item) => item.weight)
							}
						}
					}
				})
			},
			// 跳转小程序
			jumpSign() {
				let path = 'pages/index/index'
				if(Object.keys(this.mpData).length > 0) {
					path = path + this.getSerialize(this.mpData)
				}
				uni.navigateToMiniProgram({
				  appId: 'wx162370635292eef2',
				  path,
				  success(res) {
				    // 打开成功
				  }
				})
			},
			// 对象序列化成 a=1&b=2
			getSerialize(value) {
				if(Object.prototype.toString.call(value) === "[object Object]") {
					let path = ""
					for (const key in value) {
						if (Object.prototype.hasOwnProperty.call(value, key)) {
							const element = value[key];
							if (path === "") {
								path = `?${key}=${element}`
							}else {
								path = path + `&${key}=${element}`
							}
						}
					}
					return path
				} else {
					return ""
				}
			},
			// 活动规则
			activityRulesHandle() {
				this.activityRules = !this.activityRules
			},
			// 关闭弹窗
			closeHandle() {
				this.receiveGold(false)
				this.popupShow = false
			},
			// 重新生成
			handleInitCanvas() {
				clearCacheFile()
				this.prizeList = []
				this.getPrizeList()
			},
			// 获取首页信息
			async getList() {
				let res = await getHome({appId: config.appid, openId: this.openId, userSource: 1, ...this.mpData})
				let data = res.data
				if(data) {
					this.userId = data.userId
					this.clearTime = data.clearTime
					this.prizeCountDtoList = data.prizeCountDtoList
					this.mpName = data.mpName
					this.freeNum = data.luckDraw
					this.mpData = {
						mpAppId: data.mpAppId,
						mpName: data.mpName,
						mpOpenId: data.mpOpenId
					}
					this.getBookCurr()
					return Promise.resolve(true)
				} else {
					return Promise.resolve(false)
				}
			},
			// 获取奖品列表
			async getPrizeList() {
				uni.showLoading({
					title: '奖品准备中...'
				})
				let res = await getPond({appId: config.appid, openId: this.openId, mpAppId: this.mpData.mpAppId})
				if(res.data && res.data.length > 0) {
					this.prizeList = res.data.map(item => {
						let prizeImage = ""
						if (item.prizeType === 1) {
							prizeImage = '/static/turntable_gold.png'
							if(item.prizeCount > 30) {
								prizeImage = '/static/turntable_golds.png'
							}
							return {
								prizeId: item.id,
								name: item.prizeCount + item.prizeName,
								stock: 100,
								weight: 10,
								prizeImage,
								prizeType: item.prizeType,
								prizeCount: item.prizeCount,
								prizeName: item.prizeName,
							}
						} else {
							prizeImage = '/static/turntable_iPhone12.png'
							if(item.prizeType === 2){
								prizeImage = '/static/turntable_VIP.png'
							}
							return {
								prizeId: item.id,
								name: item.prizeName,
								stock: 100,
								weight: 10,
								prizeImage,
								prizeType: item.prizeType,
								prizeCount: item.prizeCount,
								prizeName: item.prizeName,
							}
						}
					})
				}else {
					uni.hideLoading()
					uni.showToast({
						title: '获取奖品失败'
					})
				}
			},
			// 本次抽奖开始
			handleDrawStart() {
				console.log('触发抽奖按钮')
				if (systemInfo.system.includes('indows')) {
					uni.showToast({
						title: '请到手机端抽奖!',
						icon: 'error',
						duration: 4000
					})
					return
				}
				if (!this.mpName) {  // 首次没有重公众号进入
					if(this.remoteVersion !== config.version) {
						uni.showToast({
							title: '请先关注公众号~~',
							icon: 'none'
						})
					}
					// uni.navigateTo({
					// 	url: '../officialAccount/officialAccount'
					// })
					// 没有公众号本地抽奖
					if (this.freeNum > 0) {
						// 更新免费次数或金币余额
						if (this.freeNum > 0) {
							this.freeNum--
						}
						if(this.freeNum < 8) {
							// 看视频
							this.showVideoAd(2)
						} else {
							// 发起抽奖
							this.localGetPrizeIndex()
						}
					}
					return
				} 
				if (this.prizeing) return
				this.prizeing = true
			
				// 还有免费数次或者剩余金币足够抽一次
				if (this.freeNum > 0) {
					// 更新免费次数或金币余额
					if (this.freeNum > 0) {
						this.freeNum--
					}
					lqTimer && clearTimeout(lqTimer)
					if(this.freeNum < 8) {
						// 看视频
						this.showVideoAd(2)
					} else {
						// 发起抽奖
						this.remoteGetPrizeIndex()
					}
				} else {
					this.prizeing = false
					uni.showToast({
						title: '抽奖次数不足',
						icon:'none'
					})
				}
			},
			// 远程请求接口获取中奖下标
			remoteGetPrizeIndex() {
				console.warn('###当前处于模拟的请求接口，并返回了中奖信息###')
				let { mpName, ...mp } = this.mpData
				setDrawGain({appId: config.appid, openId: this.openId, ...mp}).then(res => {
					let data = res.data
					this.doubleKey = data.doubleKey
					let prizeIndex = this.prizeList.findIndex(item => item.prizeId === data.id)
					if(prizeIndex !== -1){
						this.prizeIndex = prizeIndex
					} else {
						uni.showToast({
							title: '抽奖异常，请稍后重试'
						})
					}
				})
			},
			// 没有公众号模拟抽奖
			// 本地获取中奖下标
			localGetPrizeIndex() {
				console.warn('###当前处于前端控制中奖概率，安全起见，强烈建议由后端控制###')
				// 前端控制概率的情况下，需要拿到最接近随机权重且大于随机权重的值
				// 后端控制概率的情况下，通常会直接返回 prizeId
				if (!this.weightTotal) {
					console.warn('###当前已开启前端控制中奖概率，但是奖品数据列表中的 weight 参数似乎配置不正确###')
					return
				}
				console.log('当前权重总和为 =>', this.weightTotal)
			
				// 注意这里使用了 Math.ceil，如果某个权重的值为 0，则始终无法中奖
				let weight = Math.ceil(Math.random() * this.weightTotal)
				console.log('本次权重随机数 =>', weight)
			
				let list = [...this.prizeList]
			
				// 生成大于等于随机权重的数组
				let tempMaxArrs = []
				list.forEach((item) => {
					if (item.weight >= weight) {
						tempMaxArrs.push(item.weight)
					}
				})
			
				// 如果大于随机权重的数组有值，先对这个数组排序然后取值
				// 反之新建一个临时的包含所有权重的已排序数组，然后取值
				let tempMaxArrsLen = tempMaxArrs.length
				if (tempMaxArrsLen) {
					tempMaxArrs.sort((a, b) => a - b)
					// 取值时，如果存在多个值，分两种情况
					if (tempMaxArrsLen > 1) {
						// 值不相等的情况下取最接近的值，也就是第1个值
						let sumWeight = tempMaxArrs.reduce((a, b) => a + b)
						if ((sumWeight / tempMaxArrsLen) !== tempMaxArrs[0]) {
							this.prizeIndex = this.weightArr.indexOf(tempMaxArrs[0])
						} else {
							// 值相等时，随机取值，当然这里你可以自己决定是否随机取值
							let sameWeight = tempMaxArrs[0]
							let sameWeightArr = []
							let sameWeightItem = {}
							this.weightArr.forEach((item, index) => {
								if (item === sameWeight) {
									sameWeightArr.push({
										weight: item,
										index
									})
								}
							})
							console.log('sameWeightArr', sameWeightArr)
							sameWeightItem = sameWeightArr[Math.floor(Math.random() * sameWeightArr.length)]
							console.log('sameWeightItem', sameWeightItem)
							this.prizeIndex = sameWeightItem.index
						}
					} else {
						this.prizeIndex = this.weightArr.indexOf(tempMaxArrs[0])
					}
				} else {
					let tempWeightArr = [...this.weightArr]
					tempWeightArr.sort((a, b) => a - b)
					this.prizeIndex = this.weightArr.indexOf(tempWeightArr[tempWeightArr.length - 1])
				}
			
				console.log('本次抽中奖品 =>', this.prizeList[this.prizeIndex].name)
			},
			// 本次抽奖结束
			handleDrawEnd() {
				console.log('旋转结束，执行拿到结果后到逻辑')
				// 旋转结束后，开始处理拿到结果后的逻辑
				this.prizeing = false
				let prizeName = this.prizeList[this.prizeIndex].name
				let { prizeType, prizeCount } = this.prizeList[this.prizeIndex]
				
				console.log('1111->', this.prizeList[this.prizeIndex])
				this.luckyDay = this.prizeList[this.prizeIndex]
				
				if (prizeName === '谢谢参与') {
				} else if (prizeName.indexOf('碎片') === -1 && this.freeNum >= 8) {
					this.popupShow = true
					return
				} else {
					if (prizeType === 1) {
						this.popupGoldShow = true
					} else if (prizeType === 2) {
						this.popupVIPShow = true
					} else if (prizeType === 3) {
						this.popup12Show = true
					}
				}
				
				if (!this.mpName) {  // 首次没有重公众号进入
					console.log("首次没有重公众号进入")
					return
				}
				this.getList()
			},
			// 抽奖转盘绘制完成
			handleDrawFinish(res) {
				console.log('抽奖转盘绘制完成', res)
				uni.showToast({
					title: res.msg,
					duration: 800,
					mask: true,
					icon: 'none'
				})
			}
		}
	}
</script>

<style lang="scss">
	page{
		background-color: #F0524C;
	}
	.luckyDraw {
		position: relative;
		&>.back {
			width: 100%;
		}
	}
	
	.luckyDrawContent {
		overflow-x: hidden;
		position: absolute;
		top: 0;
		width: 100%;
		padding: 28rpx 0;
		margin-bottom: 20rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		
		// 用户信息
		.luckyDrawTop {
			padding: 0 28rpx;
			height: 104rpx;
			display: flex;
			
			justify-content: space-between;
			align-items: center;
			.left{
				display: flex;
				justify-content: flex-start;
				align-items: center;
				&>.avatarView {
					overflow: hidden;
					width: 104rpx;
					height: 104rpx;
					background: #D8D8D8;
					border-radius: 10px;
					&>image {
						width: 100%;
						height: 100%;
					}
				}
				
				.userInfo{
					margin-left: 28rpx;
					&>view{
						font-size: 32rpx;
						font-weight: 500;
						color: #FFFFFF;
						
						&.account {
							display: flex;
							justify-content: flex-start;
							align-items: center;
							&>image {
								width: 36rpx;
								height: 36rpx;
								margin-right: 10rpx;
							}
						}
						
						&.ID{
							margin-top: 4rpx;
							display: flex;
							justify-content: flex-start;
							align-items: center;
						}
						.extract {
							font-size: 30rpx;
							margin-left: 30rpx;
							background-color: rgb(213, 51, 186);
							// background-image: linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186));
							padding: 6rpx 16rpx;
							border-radius: 26rpx;
						}
					}
				}
			}
			.right{
				width: 180rpx;
				height: 64rpx;
				background: #BA3A11;
				border-radius: 30rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				&>text {
					font-size: 28rpx;
					font-weight: 400;
					color: #FFFFFF;
				}
			}
		}
	
		// 滚动通知
		.notice {
			width: 656rpx;
			height: 60rpx;
			background: #C7322C;
			box-shadow: 0px 4rpx 8rpx 0rpx rgba(49, 49, 49, 0.08);
			border-radius: 38rpx;
			opacity: 0.53;
			margin: 38rpx auto 0;
			padding: 0 30rpx;
			box-sizing: border-box;
			display: flex;
			justify-content: flex-start;
			align-items: center;

			.horn {
				width: 28rpx;
				height: 28rpx;
			}
			.txts {
				// flex: 1;
				height: 68rpx;
				width: 600rpx;
			}
		}
		
		// 去签到
		.qLuckDraw {
			position: absolute;
			top: 180rpx;
			right: 10rpx;
			z-index: 200;
			animation: lanimation 1.3s linear infinite;
			&>image {
				width: 120rpx;
				height: 120rpx;
			}
		}
	
		// 大转盘
		.turntable {
			position: relative;
			margin-top: 20rpx;
			.decorate{
				position: relative;
				width: 100%;
				height: 880rpx;
				&>image {
					width: 100%;
					position: absolute;
					z-index: 10;
					
					&.decorateBack {
						top: 0;
					}
					&.decorateChassis{
						position: absolute;
						z-index: 1;
						bottom: 0;
					} 
				}
			}
		
			.turntableContent {
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				width: 100%;
				height: 100%;
				z-index: 20;
				.al {
					width: 100%;
					height: 804rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					padding-bottom: 40rpx;
				}
				
				.bottom {
					margin-top: 30rpx;
					text-align: center;
					position: absolute;
					bottom: 25rpx;
					left: 50%;
					transform: translateX(-50%);
					.cont{
						font-size: 28rpx;
						font-weight: 400;
						color: #FFFFFF;
						margin-bottom: 12rpx;
						text {
							font-size: 36rpx;
							color: #FEED22;
							font-weight: 500;
						}
					}
				}
			}
		}
	
		// 我的奖品
		.myPrize {
			margin: 30rpx 26rpx 0;
			min-height: 352rpx;
			background: #F4E2CA;
			border-radius: 20rpx;
			position: relative;
			padding: 40rpx 0  20rpx;
			.title {
				position: absolute;
				width: 232rpx;
				height: 64rpx;
				background: linear-gradient(180deg, #FFEDD1 0%, #FFC954 100%);
				box-shadow: 0 4rpx 8rpx 0 rgba(0, 0, 0, 0.07);
				border-radius: 0 0 24rpx 24rpx;
				font-size: 32rpx;
				font-weight: 500;
				color: #F33938;
				text-align: center;
				line-height: 64rpx;
				left: 50%;
				transform: translateX(-50%);
				top: -12rpx;
			}
			.chips {
				display: flex;
				justify-content: space-between;
			}
			.chip {
				display: flex;
				flex-direction: column;
				align-items: center;
				width: 50%;
				&>image {
					width: 180rpx;
					height: 140rpx;
				}
				.text{
					font-size: 32rpx;
					font-weight: 500;
					color: #F33938;
					line-height: 44rpx;
					margin-top: 12rpx;
				}
				.progress{
					position: relative;
					width: 200rpx;
					height: 38rpx;
					margin-top: 12rpx;
					background: #FFFCF7;
					border-radius: 26rpx;
					overflow: hidden;
					.value{
						position: absolute;
						width: 1%;
						height: 100%;
						top: 0;
						left: 0;
						z-index: 1;
						background: #F37938;
					}
					&>text {
						font-size: 28rpx;
						font-weight: 500;
						color: #333333;
						position: absolute;
						top: 50%;
						left: 50%;
						transform: translate(-50%, -50%);
						z-index: 2;
					}
				}
			}
			.clearTime{
				margin: 20rpx 0 0;
				text-align: center;
				font-size: 24rpx;
				font-weight: 400;
				color: #F33938;
			}
		}
		
		// 活动规则
		.activityRules {
			margin: 28rpx 28rpx 0;
			background: #F4E2CA;
			border-radius: 20rpx;
			color: #F33938;
			font-size: 32rpx;
			font-weight: 400;
			&>.top {
				height: 92rpx;
				padding: 0 28rpx;
				box-sizing: border-box;
				display: flex;
				justify-content: space-between;
				align-items: center;
				&>image {
					width: 40rpx;
				}
			}
			&>.bottom {
				padding: 0 28rpx 30rpx;
				box-sizing: border-box;
				
				&> view {
					margin-bottom: 12rpx;
					font-size: 28rpx;
					font-weight: 400;
					color: #666666;
					line-height: 46rpx;
				}
			}
		}
		
		// 弹窗
		.popup {
			position: fixed;
			width: 100%;
			height: 100vh;
			background: rgba(0, 0, 0, 0.6);
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			z-index: 201;
			.popupContent {
				width: 632rpx;
				
				position: absolute;
				top: 50%;
				left: 50%;
				transform: translate(-50%, -50%);
				text-align: center;
				&>.content {
					position: relative;
					&>image {
						width: 100%;
						height: 652rpx;
					}
					&>.textCon {
						position: absolute;
						width: 100%;
						top: 0;
						left: 0;
						right: 0;
						bottom: 0;
						padding-top: 192rpx;
						.ts {
							font-size: 60rpx;
							font-weight: 500;
							color: #F5631D;
						}
						
						.reward {
							height: 60rpx;
							// background: #FFD9A2;
							// border-radius: 31rpx;
							font-size: 50rpx;
							font-weight: 400;
							display: inline-block;
							padding: 0 32rpx;
							color: #F5631E;
							line-height: 60rpx;
							margin-top: 20rpx;
						}
						
						.goldText {
							font-size: 64rpx;
							font-family: FZZZHONGJW--GB1-0, FZZZHONGJW--GB1;
							font-weight: normal;
							color: #FFFFFF;
							margin-bottom: 25rpx;
							transform: translateX(12rpx);
						}
						
						.doubleBt {
							width: 456rpx;
							height: 104rpx;
							margin-top: 90rpx;
							transition: all linear .5s; 
						}
						
						.bt {
							margin-top: 14rpx;
							font-size: 32rpx;
							font-weight: 400;
							color: #FCE8CD;
						}
						
						.againLuckDrawBt {
							width: 424rpx;
							height: 86rpx;
							background: linear-gradient(180deg, #FDDEA5 0%, #FFC981 75%, #FFC983 100%);
							border-radius: 43rpx;
							font-size: 36rpx;
							font-family: SourceHanSansCN-Medium, SourceHanSansCN;
							font-weight: 500;
							color: #854007;
							text-align: center;
							line-height: 86rpx;
							margin: 0 auto 40rpx;
							transition: all linear .5s;
						}
						.btGold {
							width: 448rpx;
							height: 104rpx;
							border-radius: 52rpx;
							line-height: 104rpx;
							font-size: 40rpx;
							box-shadow: 0px 2rpx 8rpx 4rpx rgba(183, 2, 2, 0.37);
							background: linear-gradient(180deg, #FFFCBE 0%, #F87527 100%);
						}
						.btVip {
							width: 426rpx;
							height: 88rpx;
							background: linear-gradient(180deg, #F6E5CA 0%, #EDC388 100%);
							box-shadow: 0rpx 6rpx 16rpx 0rpx rgba(162, 58, 20, 0.77);
							border-radius: 44rpx;
						}
					}
				}
				&>.close {
					width: 54rpx;
					height: 54rpx;
					margin-top: 76rpx;
				}
			}
		}
	
		// 碎片飞行初始样式 // 金币飞行
		.fragmentAni, .fragmentGold {
			position: absolute;
			z-index: 201;
			top: 453rpx;
			left: 330rpx;
			opacity: 0;
			&>image {
				width: 100rpx;
				height: 100rpx;
			}
		}
		.fragmentGold {
			// opacity: 1;
		}
		
		.receiveTs {
			position: absolute;
			border: 2rpx solid rgb(242, 69, 69);
			top: 450rpx;
			z-index: 201;
			color: #FFFFFF;
			left: 50%;
			transform: translateX(-50%);
			padding: 10rpx 20rpx;
			background-color: rgba(131, 37, 37, 0.6);
			border-radius: 5rpx;
			opacity: 0;
		}
		
		.singleLattice {
			position: absolute;
			top: 900rpx;
			right: 8rpx;
			z-index: 201;
		}
	}
	
	@-webkit-keyframes lanimation {
		0% {
			transform: rotate(0deg);
		}
		8% {
			transform: rotate(12deg);
		}
		16% {
			transform: rotate(0deg);
		}
		24% {
			transform: rotate(-12deg);
		}
		32% {
			transform: rotate(0deg);
		}
		100% {
			transform: rotate(0deg);
		}
	}
</style>
