<template>
	<view class="sign-in-page">
		<!-- 顶部导航栏 -->
		<view class="header">
			<view class="back-btn" @click="goBack">
				<text class="back-icon">‹</text>
			</view>
			<text class="header-title">签到</text>
			<view class="placeholder"></view>
		</view>

		<scroll-view scroll-y class="content">
			<!-- 签到日历标题 -->
			<view class="calendar-header">
				<text class="calendar-title">{{ currentMonthText }}签到日历</text>
				<text class="calendar-subtitle">红线相系，良缘成就一生欢喜。</text>
			</view>

			<!-- 月份选择 -->
			<view class="month-selector">
				<text class="month-text">{{ currentMonthText }}</text>
				<view class="streak-badge">
					<text class="streak-text">红线季良缘</text>
				</view>
				<view class="calendar-icon">📅</view>
			</view>

			<!-- 日历 -->
			<view class="calendar">
				<view class="weekdays">
					<text class="weekday">日</text>
					<text class="weekday">一</text>
					<text class="weekday">二</text>
					<text class="weekday">三</text>
					<text class="weekday">四</text>
					<text class="weekday">五</text>
					<text class="weekday">六</text>
				</view>

				<view class="days">
					<view 
						v-for="(day, index) in calendarDays" 
						:key="index" 
						class="day-item"
						:class="{ 
							'other-month': day.isOtherMonth,
							'signed': day.isSigned,
							'today': day.isToday
						}"
					>
						<text class="day-number">{{ day.day }}</text>
					</view>
				</view>
			</view>

			<!-- 签到统计 -->
			<view class="sign-stats">
				<view class="stat-item">
					<text class="stat-icon">📊</text>
					<text class="stat-text">累计签到: {{ totalSignDays }}天</text>
				</view>
				<view class="stat-item">
					<text class="stat-icon">💗</text>
					<text class="stat-text">可用积分: {{ availablePoints }}</text>
				</view>
				<view class="gift-icon">🎁</view>
			</view>

			<!-- 连续签到进度 -->
			<view class="streak-progress">
				<text class="progress-label">连续签到奖励</text>
				<text class="progress-days">连续{{ consecutiveDays }}天</text>
			</view>
			<view class="progress-bar">
				<view class="progress-fill" :style="{ width: progressWidth }"></view>
			</view>

			<!-- 签到按钮 -->
			<view class="sign-button" :class="{ disabled: isSigned }" @click="handleSignIn">
				<text class="button-text">{{ isSigned ? '今日已签到' : '今日签到 +10积分' }}</text>
			</view>

			<!-- 提示文字 -->
			<view class="tips">
				<text class="tips-text">坚持签到，缘分更近一步</text>
				<text class="tips-sub">品牌出品 | 青鸟之恋1跟平台</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import api from '@/utils/api.js'

export default {
	data() {
		return {
			currentYear: new Date().getFullYear(),
			currentMonth: new Date().getMonth() + 1,
			totalSignDays: 0,
			availablePoints: 0,
			consecutiveDays: 0,
			makerId: null,
			isSigned: false,
			calendarDays: [],
			signedDates: [], // 已签到的日期字符串数组，格式：YYYY-MM-DD
			currentMonthText: '' // 当前月份显示文本
		}
	},
	computed: {
		progressWidth() {
			// 假设7天为一个周期
			const progress = (this.consecutiveDays % 7) / 7 * 100
			return progress + '%'
		}
	},
	onLoad() {
		this.initData()
	},
	onShow() {
		// 每次显示页面时刷新数据
		if (this.makerId) {
			this.loadSignInData()
		}
	},
	methods: {
		goBack() {
			uni.navigateBack()
		},
		async initData() {
			// 获取红娘ID
			const userInfo = uni.getStorageSync('userInfo')
			if (userInfo && userInfo.matchmakerId) {
				this.makerId = userInfo.matchmakerId
			} else if (userInfo && userInfo.userId) {
				// 如果没有matchmakerId，通过API获取
				try {
					const res = await api.matchmaker.getByUserId(userInfo.userId)
					let matchmaker = res
					if (res && res.data) {
						matchmaker = res.data
					}
					if (matchmaker && (matchmaker.matchmakerId || matchmaker.matchmaker_id)) {
						this.makerId = matchmaker.matchmakerId || matchmaker.matchmaker_id
						userInfo.matchmakerId = this.makerId
						uni.setStorageSync('userInfo', userInfo)
					}
				} catch (e) {
				
				}
			}
			
			await this.loadSignInData()
			this.generateCalendar()
		},
		async loadSignInData() {
			if (!this.makerId) return
			
			try {
				// 获取签到统计数据
				const statsRes = await api.matchmaker.checkinStats(this.makerId)
				let stats = statsRes
				if (statsRes && statsRes.data) {
					stats = statsRes.data
				}
				
				this.totalSignDays = stats.totalDays || 0
				this.consecutiveDays = stats.continuousDays || 0
				
				// 获取积分余额
				const balanceRes = await api.pointsMall.getBalance(this.makerId)
				this.availablePoints = balanceRes.balance || 0
				
				// 获取本月所有签到日期
				const checkinInfoRes = await api.matchmaker.checkinInfo(this.makerId, this.currentYear, this.currentMonth)
			
				let checkinInfo = checkinInfoRes
				if (checkinInfoRes && checkinInfoRes.data) {
					checkinInfo = checkinInfoRes.data
				}
			
				// 获取已签到日期列表
				this.signedDates = checkinInfo.checkedDates || []
				
				// 检查今日签到状态
				const statusRes = await api.matchmaker.checkinStatus(this.makerId)
				
				let statusData = statusRes
				if (statusRes && statusRes.data !== undefined) {
					statusData = statusRes.data
				}
				this.isSigned = statusData === true || statusData?.isCheckedIn === true || statusData?.checked === true
			
				
				// 更新日历，显示所有已签到日期
				this.generateCalendar()
			} catch (e) {
				
			}
		},
		generateCalendar() {
			
			const year = this.currentYear
			const month = this.currentMonth
			
			
			// 更新月份显示文本
			this.currentMonthText = `${year}年${month}月`
			
			
			// 获取当月第一天是星期几
			const firstDay = new Date(year, month - 1, 1).getDay()
			// 获取当月天数
			const daysInMonth = new Date(year, month, 0).getDate()
			// 获取上月天数
			const prevMonthDays = new Date(year, month - 1, 0).getDate()
		
			
			// 获取今天的日期字符串
			const today = new Date()
			const todayStr = this.formatDate(today)
			
			
			const days = []
			
			// 添加上月日期
			for (let i = firstDay - 1; i >= 0; i--) {
				days.push({
					day: prevMonthDays - i,
					isOtherMonth: true,
					isSigned: false,
					isToday: false
				})
			}
			
			// 添加当月日期
			for (let i = 1; i <= daysInMonth; i++) {
				const date = new Date(year, month - 1, i)
				const dateStr = this.formatDate(date)
				const isToday = dateStr === todayStr
				const isSigned = this.signedDates.includes(dateStr)
				
				
				days.push({
					day: i,
					isOtherMonth: false,
					isSigned: isSigned,
					isToday: isToday
				})
			}
			
			// 添加下月日期补齐
			const remainingDays = 42 - days.length // 6行7列
			for (let i = 1; i <= remainingDays; i++) {
				days.push({
					day: i,
					isOtherMonth: true,
					isSigned: false,
					isToday: false
				})
			}
			
			this.calendarDays = days
			
		},
		// 格式化日期为YYYY-MM-DD
		formatDate(date) {
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			return `${year}-${month}-${day}`
		},
		async handleSignIn() {
			if (this.isSigned) {
				uni.showToast({
					title: '今日已签到',
					icon: 'none'
				})
				return
			}
			
			if (!this.makerId) {
				uni.showToast({ title: '请先登录', icon: 'none' })
				return
			}
			
			try {
				// 调用后端签到接口
				const signRes = await api.matchmaker.doCheckin(this.makerId)
				
				// 签到成功后更新状态
				this.isSigned = true
				this.totalSignDays++
				this.consecutiveDays++
				
				// 更新今天的签到状态
				const today = new Date()
				const todayStr = this.formatDate(today)
				if (!this.signedDates.includes(todayStr)) {
					this.signedDates.push(todayStr)
				}
				this.generateCalendar()
				
				// 刷新积分余额
				const balanceRes = await api.pointsMall.getBalance(this.makerId)
				this.availablePoints = balanceRes.balance || 0
				
				// 重新加载签到信息，确保数据最新
				await this.loadSignInData()
				this.generateCalendar()
				
				uni.showToast({
					title: '签到成功 +5积分',
					icon: 'success'
				})
			} catch (e) {
			
				// 如果是已签到的错误，更新状态
				if (e.message && e.message.includes('已签到')) {
					this.isSigned = true
				}
				uni.showToast({
					title: e.message || '签到失败',
					icon: 'none'
				})
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.sign-in-page {
	min-height: 100vh;
	background: linear-gradient(180deg, #F3E5F5 0%, #FFF9F9 40%);
	display: flex;
	flex-direction: column;
}

/* 顶部导航栏 */
.header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	padding-top: calc(20rpx + env(safe-area-inset-top));
	background: transparent;

	.back-btn {
		width: 50rpx;
		height: 50rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		.back-icon {
			font-size: 40rpx;
			color: #333;
		}
	}

	.header-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.placeholder {
		width: 50rpx;
	}
}

.content {
	flex: 1;
	padding: 10rpx 20rpx 20rpx;
}

/* 日历标题 */
.calendar-header {
	margin-bottom: 20rpx;

	.calendar-title {
		display: block;
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 8rpx;
	}

	.calendar-subtitle {
		display: block;
		font-size: 24rpx;
		color: #FF6B9D;
	}
}

/* 月份选择 */
.month-selector {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 20rpx;

	.month-text {
		font-size: 28rpx;
		font-weight: bold;
		color: #7B1FA2;
	}

	.streak-badge {
		background: linear-gradient(135deg, #9C27B0 0%, #BA68C8 100%);
		color: #FFFFFF;
		font-size: 22rpx;
		font-weight: bold;
		padding: 6rpx 14rpx;
		border-radius: 12rpx;
	}

	.calendar-icon {
		font-size: 32rpx;
	}
}

/* 日历 */
.calendar {
	background: #FFFFFF;
	border-radius: 16rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

	.weekdays {
		display: grid;
		grid-template-columns: repeat(7, 1fr);
		margin-bottom: 15rpx;

		.weekday {
			text-align: center;
			font-size: 24rpx;
			color: #666;
			font-weight: bold;
		}
	}

	.days {
		display: grid;
		grid-template-columns: repeat(7, 1fr);
		gap: 8rpx;

		.day-item {
			aspect-ratio: 1;
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 12rpx;
			background: #F5F5F5;

			&.other-month {
				background: transparent;

				.day-number {
					color: #CCC;
				}
			}

			&.signed {
				background: #F3E5F5;
				border: 2rpx solid #CE93D8;

				.day-number {
					color: #7B1FA2;
					font-weight: bold;
				}
			}

			&.today {
				background: #9C27B0;
				border: 2rpx solid #7B1FA2;

				.day-number {
					color: #FFFFFF;
					font-weight: bold;
				}
			}

			&.today.signed {
				background: #9C27B0;
				border: 2rpx solid #7B1FA2;

				.day-number {
					color: #FFFFFF;
					font-weight: bold;
				}
			}

			.day-number {
				font-size: 24rpx;
				color: #333;
			}
		}
	}
}

/* 签到统计 */
.sign-stats {
	display: flex;
	align-items: center;
	justify-content: space-between;
	background: #FFFFFF;
	border-radius: 16rpx;
	padding: 15rpx 20rpx;
	margin-bottom: 15rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

	.stat-item {
		display: flex;
		align-items: center;
		gap: 8rpx;
		flex: 1;

		.stat-icon {
			font-size: 24rpx;
		}

		.stat-text {
			font-size: 24rpx;
			color: #666;
		}
	}

	.gift-icon {
		font-size: 32rpx;
	}
}

/* 连续签到进度 */
.streak-progress {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 10rpx;

	.progress-label {
		font-size: 24rpx;
		color: #666;
	}

	.progress-days {
		font-size: 24rpx;
		color: #9C27B0;
		font-weight: bold;
	}
}

.progress-bar {
	width: 100%;
	height: 12rpx;
	background: #E0E0E0;
	border-radius: 6rpx;
	margin-bottom: 25rpx;
	overflow: hidden;

	.progress-fill {
		height: 100%;
		background: linear-gradient(90deg, #9C27B0 0%, #BA68C8 100%);
		border-radius: 6rpx;
		transition: width 0.3s ease;
	}
}

/* 签到按钮 */
.sign-button {
	background: linear-gradient(135deg, #9C27B0 0%, #BA68C8 100%);
	border-radius: 16rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 4rpx 12rpx rgba(156, 39, 176, 0.3);

	&.disabled {
		background: #E0E0E0;
		box-shadow: none;
	}

	.button-text {
		display: block;
		text-align: center;
		font-size: 28rpx;
		font-weight: bold;
		color: #FFFFFF;
	}
}

/* 提示文字 */
.tips {
	text-align: center;

	.tips-text {
		display: block;
		font-size: 26rpx;
		color: #666;
		margin-bottom: 8rpx;
	}

	.tips-sub {
		display: block;
		font-size: 22rpx;
		color: #999;
	}
}
</style>
