<template>
	<view class="sign-main" @click.stop="">
		<view class="sign-title">7日签到领大奖</view>
		<view class="list">
			<view class="main-item" :class="{'last-one':list.length === index+1 && isTop,'last-two':list.length === index+1 && isBottom}" v-for="(item,index) in list" :key="index">
				<image src="@/static/home/ylq.png" mode="" v-if="list.length !== index+1 && item.sign" class="is-sign-icon"></image>
				<image src="@/static/home/ylq-b.png" mode="" v-if="list.length === index+1 && item.sign" class="is-sign-b-icon"></image>
				<view class="item-title" v-if="list.length !== index+1">第{{convertToChinese(item.numDay)}}天</view>
				<template v-if="item.rewardVoList.length === 1 && list.length !== index+1">
					<image src="@/static/home/s-yhq.png" class="coupon-icon" v-if="item.rewardVoList[0].type === 'COUPON'"></image>
					<image src="@/static/home/s-jf.png" class="point-icon" v-if="item.rewardVoList[0].type === 'POINTS'"></image>
				</template>
				<template v-if="item.rewardVoList.length > 1 && list.length !== index+1">
					<image src="@/static/home/zh.png" class="zh-icon"></image>
				</template>
				<view class="item-title-jl" v-if="list.length !== index+1">
					<template v-if="item.rewardVoList.length">
						<text v-for="(childItem,childIndex) in item.rewardVoList">{{childItem.info.name}}X{{childItem.num}}</text>
						
					</template>
				</view>
			</view>
		</view>
		<view class="sign-btn" @click="sign" :class="{'dis-btn':isSign}">{{isSign ? '已签到' : '立即签到'}}</view>
		<image src="@/static/home/sign-close.png" mode="" class="close-icon" @click="close"></image>
	</view>
</template>

<script>
	import { myMixins } from "@/mixins/mixins.js";
	import { signInInfo,signIn,taskListApi,taskReceive } from '@/API/sign.js'
	
	import { userInfo } from '@/API/user.js'
	import NoOpenCom from '@/pages/index/components/noOpen.vue'
	import reportClickFn from '@/utils/report.js'
	export default{
		mixins: [myMixins],
		data(){
			return{
				list:[],
				isSign:false,
				time:'',
				isBottom:false,
				isTop:false,
				differenceInDays:'',
				rewardTypeObj:{
					FORMULA:'组合奖励',
					POINTS:"积分",
					COUPON:'优惠券',
					PROMPT:'提示卡',
					COIN:'代币'
				},
			}
		},
		mounted() {
			this.getSignInInfo()
			this.getTime()
		},
		methods:{
			convertToChinese(value) {
			      // if (!value || value < 0 || value > 20 || !Number.isInteger(value)) {
			      //   return '无效的数字';
			      // }
			      const chineseNumbers = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十',
			        '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十'];
			      return chineseNumbers[value];
			    },
			getTime(){
				let now = new Date();
				let year = now.getFullYear();
				let month = now.getMonth() + 1;  // 月份从0开始，所以要加1
				let day = now.getDate();
				let hour = now.getHours();
				let minute = now.getMinutes();
				let second = now.getSeconds();
				month = month < 10 ? `0${month}` : month
				day = day < 10 ? `0${day}` : day
				this.time = `${year}-${month}-${day}`
			},
			getSignInInfo(){
				uni.showLoading()
				signInInfo().then(res => {
					uni.hideLoading()
					if(res.code === 200){
						console.log(res)
						if(res.data.details.length > 0){
							res.data.details.forEach((item,index) => {
								item['numDay'] = index
							})
							this.list = this.truncateArray(res.data.details,this.daysBetweenDates(res.data.details[0].dt))
							console.log(this.list)
							let signObj = {}
							this.list.forEach(item => {
								signObj[item.dt] = item.sign
							})
							if(signObj[this.time]){
								this.isSign = true
							}
						}
					}else{
						this.$api.msg(res.message)
					}
				}).catch(err => {
					uni.hideLoading()
				})
			},
			sign(){
				// 签到次数点击埋点
				reportClickFn('sign_clk')
				if(this.isSign){
					this.$api.msg('您已签到')
					console.log("aaaaa")
					return
				}
				uni.showLoading()
				signIn().then(res => {
					console.log(res)
					if(res.code === 200){
						if(res.data){
							// 创建一个对象来存储每个类型的总数
							const typeSums = {};
							
							// 遍历数组，将相同类型的 num 相加
							res.data.forEach(obj => {
							  if (typeSums[obj.type]) {
							    typeSums[obj.type] += obj.num;
							  } else {
							    typeSums[obj.type] = obj.num;
							  }
							});
							
							// 构造输出字符串
							let resultStr = '';
							
							// 将相同类型的 num 乘以其总数，构造输出字符串
							for (const type in typeSums) {
							  resultStr += `${this.rewardTypeObj[type]}*${typeSums[type]}、`;
							}
							
							// 去除末尾多余的 '、'
							resultStr = resultStr.slice(0, -1);
							console.log("resultStr：",resultStr)
							this.$api.msg(`${resultStr}领取成功`)
							// uni.hideLoading()
							// this.isSign = true
							// this.getSignInInfo()
							// this.$emit('signOk')
						}
						setTimeout(() => {
							uni.hideLoading()
							this.isSign = true
							this.getSignInInfo()
							this.$emit('signOk')
							// this.getUserInfo()
						},1000)
						
						
					}else{
						this.$api.msg(res.message)
					}
				}).catch(err => {
					uni.hideLoading()
				})
			},
			close(){
				this.$emit('close')
			},
			truncateArray(arr, threshold) {
			    // 检查阈值并确定要保留的部分
			    if (threshold < 8) {
					this.isTop = true
					this.isBottom = false
			        // 如果阈值小于8，则保留前七位
			        return arr.slice(0, 7);
			    } else {
					this.isTop = false
					this.isBottom = true
			        // 如果阈值大于或等于8，则保留后七位
			        // 注意：如果数组长度小于7，我们需要做额外的检查
			        const endIndex = Math.min(arr.length, threshold - 1) - (threshold - 8); // 确保不越界
			        return arr.slice(-endIndex); // 使用负数索引从末尾开始取
			    }
			},
			daysBetweenDates(dateString) {
			      // 创建两个Date对象，一个是目标日期，一个是当前日期
			      const targetDate = new Date(dateString);
			      const currentDate = new Date();
			
			      // 检查目标日期是否有效
			      if (isNaN(targetDate.getTime())) {
			        throw new Error('Invalid date string');
			      }
			
			      // 计算时间差（毫秒）
			      const differenceInMilliseconds = currentDate - targetDate;
			
			      // 转换为天数
			      const differenceInDays = Math.ceil(differenceInMilliseconds / (1000 * 60 * 60 * 24));
					console.log(differenceInDays)
					this.differenceInDays = differenceInDays
			      // 返回天数差
			      return differenceInDays;
			    }
		}
	}
</script>

<style lang="scss" scoped>
	.sign-main{
		
		width: 604rpx;
		height: 717rpx;
		background-image: url('@/static/home/sign-bg.png');
		background-size: 100%;
		background-repeat: no-repeat;
		position: absolute;
		top: 0;
		left: 0;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		.sign-title{
			font-family: YouSheBiaoTiHei;
			font-size: 46rpx;
			color: #FFFFFF;
			padding-top: 134rpx;
			text-align: center;
		}
		.list{
			display: grid;
			gap: 6rpx;
			grid-template-rows: 1fr;
			margin: 0px auto;
			grid-template-columns: repeat(3, 1fr);
			padding: 38rpx 60rpx;
			position: relative;
			.main-item{
				display: inline-block;
				width: 150rpx;
				height: 137rpx;
				background-image: url('@/static/home/s-bj.png');
				background-size: 100%;
				background-repeat: no-repeat;
				display: flex;
				align-items: center;
				flex-direction: column;
				padding-top: 9rpx;
				position: relative;
				overflow: hidden;
				.is-sign-icon{
					position: absolute;
					top: 0;
					left: 0;
					width: 150rpx;
					height: 137rpx;
					z-index: 2;
				}
				.item-title{
					width: 115rpx;
					height: 28rpx;
					background-image: url('@/static/home/bg-t.png');
					background-size: 100%;
					background-repeat: no-repeat;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 22rpx;
					color: #000000;
				}
				.item-title-jl{
					width: 115rpx;
					height: 28rpx;
					text-align: center;
					font-size: 20rpx;
					color: #000000;
					overflow: hidden;
					white-space: nowrap;
					text-overflow: ellipsis;
				}
				.coupon-icon{
					width: 71rpx;
					height: 70rpx;
					margin-top: 4rpx;
					z-index: 1;
				}
				.point-icon{
					width: 77rpx;
					height: 62rpx;
					margin-top: 4rpx;
					z-index: 1;
				}
				.zh-icon{
					width: 113rpx;
					height: 65rpx;
					margin-top: 4rpx;
					z-index: 1;
				}
			}
			.last-one{
				position: absolute;
				width: 474rpx;
				height: 130rpx;
				left: 60rpx;
				bottom: -104rpx;
				background-image: url('@/static/home/d7.png');
				background-size: 100%;
				background-repeat: no-repeat;
			}
			.last-two{
				position: absolute;
				width: 474rpx;
				height: 130rpx;
				left: 60rpx;
				bottom: -104rpx;
				background-image: url('@/static/home/d14.png');
				background-size: 100%;
				background-repeat: no-repeat;
			}
			.is-sign-b-icon{
				position: absolute;
				top: 0;
				left: 0;
				width: 474rpx;
				height: 130rpx;
			}
		}
		.sign-btn{
			width: 296rpx;
			height: 95rpx;
			background-image: url('@/static/home/sign-btn.png');
			background-size: 100%;
			background-repeat: no-repeat;
			font-family: YouSheBiaoTiHei;
			font-size: 45rpx;
			color: #FFFFFF;
			text-align: center;
			line-height: 95rpx;
			display: block;
			margin: 124rpx auto 61rpx auto;
		}
		.close-icon{
			width: 66rpx;
			height: 66rpx;
			display: block;
			margin: 0 auto;
		}
	}
</style>