<template>
	<view class="sign-page">
		<image src="@/static/sign/fh.png" mode="" class="back-icon" @click="goBack"></image>
		<view class="mian">
			<view class="sign-main">
				<view class="total-num">本月累计签到
				<image :src="`../../static/sign/${item}.png`" mode="aspectFit" v-for="(item,index) in total" :key="index" style="width: 40rpx;height: 50rpx;"></image>
				天</view>
				<view class="title">{{dateValue}}</view>
				<view class="cell">
					<view class="cell-item" v-for="(item,index) in list" :key="index">
						<image src="@/static/sign/lq.png" mode="" v-if="item.sign" class="is-sign-b-icon"></image>
						<text class="sign-num">{{item.numDay}}</text>
						<template v-if="item.rewardVoList.length === 1">
							<image src="@/static/sign/jif.png" mode="aspectFit" v-if="item.rewardVoList[0].type === 'POINTS'" class="point"></image>
							<image src="@/static/sign/yhq.png" mode="aspectFit" v-if="item.rewardVoList[0].type === 'COUPON'" class="coupon"></image>
							<image src="@/static/sign/tsk.png" mode="aspectFit" v-if="item.rewardVoList[0].type === 'PROMPT'" class="tip"></image>
						</template>
						<template v-if="item.rewardVoList.length > 1">
							<image src="@/static/sign/zh.png" mode="aspectFit" class="zuhe"></image>
						</template>
					</view>
				</view>
			</view>
			<view style="width: 100%;text-align: center;margin-top: -40rpx;height: 52rpx;">
				<template v-if="currentObj.rewardVoList">
					<!-- {{rewardTypeObj[item.type]}} -->
					<text v-for="(item,index) in currentObj.rewardVoList" class="reward-txt"><text v-if="item.info">{{item.info.name}}</text>*{{item.num}}</text>
				</template>
				
			</view>
			<image src="@/static/sign/wdq.png" mode="" @click="sign" v-if="!isSign" class="sign-btn"></image>
			<image src="@/static/sign/yqd.png" mode="" v-else class="sign-btn"></image>
		</view>
	</view>
</template>

<script>
	import {
		signInInfo,
		signIn,
		taskListApi,
		taskReceive
	} from '@/API/sign.js'
	import reportClickFn from '@/utils/report.js'
	export default {
		data() {
			return {
				list: [],
				isSign:false,
				rewardTypeObj:{
					FORMULA:'组合奖励',
					POINTS:"积分",
					COUPON:'优惠券',
					PROMPT:'提示卡',
					COIN:'代币'
				},
				total:[],
				dateValue:"",
				currentObj:{
					
				}
			}
		},
		mounted() {
			this.getSignInInfo()
			this.getTime()
			
		},
		methods: {
			goBack(){
				uni.navigateBack()
			},
			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.dateValue = `${year}年${month}月`
				this.time = `${year}-${month}-${day}`
			},
			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); // 使用负数索引从末尾开始取
				}
			},
			
			sign(){
				// 签到次数点击埋点
				reportClickFn('sign_clk')
				if(this.isSign){
					this.$api.msg('您已签到')
					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);
							// this.$api.msg(`${resultStr}领取成功`)
							let txt = ''
							res.data.forEach(obj => {
								console.log(obj)
								if(obj.type === "COUPON"){
									txt += `${obj.info.name}${this.rewardTypeObj[obj.type]}*${obj.num};` 
								}else{
									txt += `${this.rewardTypeObj[obj.type]}*${obj.num};` 
								}
							});
							console.log(txt)
							this.$api.msg(`${txt}领取成功`)
						}
						setTimeout(() => {
							uni.hideLoading()
							this.isSign = true
							this.getSignInInfo()
							this.$emit('signOk')
							// this.getUserInfo()
						},500)
						
						
					}else{
						this.$api.msg(res.message)
					}
				}).catch(err => {
					uni.hideLoading()
				})
			},
			toArray(num) {
			  return num.toString().split('').map(digit => parseInt(digit, 10));
			},
			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+1
							})
							// this.list = this.truncateArray(res.data.details, this.daysBetweenDates(res.data.details[0].dt))
							this.list = res.data.details
							let signObj = {}
							let total = []
							this.list.forEach(item => {
								signObj[item.dt] = item
								if(item.sign){
									total.push(item.sign)
								}
							})
							this.total = this.toArray(total.length)
							console.log("total:",this.total)
							if (signObj[this.time].sign) {
								this.isSign = true
							}
							this.currentObj = signObj[this.time]
							console.log(this.currentObj)
							console.log(this.list)
						}
					} else {
						this.$api.msg(res.message)
					}
				}).catch(err => {
					uni.hideLoading()
				})
			},
			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>
	page{
		background-color: #ceedf2;
	}
	.sign-page {
		width: 100%;
		height: 100vh;
		display: flex;
		align-items: center;
		justify-content: center;
		.back-icon{
			position: fixed;
			top: 34rpx;
			left: 0;
			width: 126rpx;
			height: 46rpx;
		}
		.mian {
			.sign-main {
				width: 723rpx;
				height: 884rpx;
				background-image: url('@/static/sign/gz.png');
				background-size: 100%;
				background-repeat: no-repeat;
				padding-top: 114rpx;
				position: relative;
				.total-num{
					position: absolute;
					top: 10rpx;
					left: 0;
					width: 100%;
					text-align: center;
					color: #0B6CC5;
					font-family: YouSheBiaoTiHei; 
					font-size: 40rpx;
				}
				.title{
					padding-right: 24rpx;
					font-size: 38rpx;
					text-align: center;
					// font-family: Impacts; 
					font-family: YouSheBiaoTiHei; 
					color: #FFFFFF;
					text-stroke: 2rpx #2087D9;
					font-style: normal;
					text-transform: none;
					background: radial-gradient(0deg, #B2E5F7 0%, #AAE0F6 54%, #FFFFFF 100%);
					-webkit-text-stroke: 2rpx #2087D9;
				}
				.cell {
					width: 640rpx;
					// height: 360rpx;
					margin-left: 30rpx;
					display: grid;
					gap: 0rpx;
					grid-template-rows: 1fr;
					margin: 0px auto;
					grid-template-columns: repeat(7, 1fr);
					margin-top: 60rpx;
					// border: 1px solid red;
					.cell-item {
						margin-bottom: 6rpx;
						width: 86rpx;
						height: 90rpx;
						position: relative;
						text-align: center;
						margin-left: -4rpx;
						
						display: flex;
						align-items: center;
						justify-content: center;
						flex-direction: column;
						// border: 1px solid red;
						.is-sign-b-icon{
							position: absolute;
							width: 80rpx;
							height: 84rpx;
							top: 0rpx;
							left: 2rpx;
							z-index: 2;
						}
						.sign-num{
							font-family: Impacts;
							font-size: 32rpx;
						}
						.point{
							width: 39rpx;
							height: 38rpx;
						}
						.coupon{
							width: 37rpx;
							height: 38rpx;
						}
						.tip{
							width: 42rpx;
							height: 38rpx;
						}
						.zuhe{
							width: 62rpx;
							height: 38rpx;
						}
					}
				}
			}
			.reward-txt{
				color: #0B6CC5;
				font-family: YouSheBiaoTiHei; 
				font-size: 40rpx;
				text-align: center;
				width: 100%;
			}
			.sign-btn{
				width: 330rpx;
				height: 90rpx;
				display: block;
				margin: 20rpx auto;
			}
		}
	}
</style>