<template>
  <layout-page>
		<view style="position: relative;">
			<!-- 日历 -->
			<Calendar
				:date="date"
				class="uni-calendar--hook"
				:selected="selected"
				:lunar="true"
				:range="false"
				:showMonth="true"
				@change="handleChange"
				@monthSwitch="handleMonthSwitch"
			/>

			<!-- <button 
        size="default" 
        class="send-button" 
        @click="handleClear"
       >
				清除缓存
			</button> -->

			<!-- 手账 -->
			<view class="journal" v-if="calendarRecord && calendarRecord.length > 0">
				<view class="title">手账</view>
				<uni-card v-for="(val, index) in calendarRecord.filter(item => item.notes)" :key="index" @tap="handleUpdateJournal(val)">
					<uni-section :title="val.date" type="line"></uni-section>
					<view class="description ss-m-t-15">{{ val.notes }}</view>
				</uni-card>
			</view>

			<!-- 添加手账 -->
			<view class="add-btn" @tap="handleAddJournal">
				<uni-icons type="plusempty" size="30" color="#fff"></uni-icons>
			</view>

			<!-- 黄历弹窗 -->
			<uni-popup ref="popupRef" type="dialog">
				<view class="popupContent">
					<view class="content-box">
						<view class="text-center ss-p-y-30">
							<view class="yangli">{{ calendarInfo.yangli }}</view>
							<view class="yinli">{{ calendarInfo.yinli }}</view>
							<view class="d-flex align-center justify-center">
								<span style="color: #7f7f7f;">幸运色</span>
								<span v-if="calendarInfo.color === '白'" class="ss-m-l-20" style="color: #7f7f7f;">白色</span>
								<view
									v-else
									class="luckyColor ss-m-l-20"
									:style="{ 'background-color': `${colorDict[calendarInfo.color] || '#2979ff'}` }"
								></view>
							</view>
						</view>
						<view class="center-box ss-p-y-30 ss-p-x-30">
							<view class="d-flex">
								<view class="yi d-flex align-center justify-center">宜</view>
								<view class="font-size-15" style="flex: 1; color: #c6b393;">{{ calendarInfo.yi }}</view>
							</view>
							<view class="d-flex ss-m-t-30">
								<view class="ji d-flex align-center justify-center">忌</view>
								<view class="font-size-15" style="flex: 1; color: #7f7f7f;">{{ calendarInfo.ji }}</view>
							</view>
						</view>
						<view class="bottom-box">
							<view class="bottom-box-item d-flex flex-column align-center justify-center">
								<view class="padding">
									<view class="label">五行</view>
									<view class="value">{{ calendarInfo.wuxing }}</view>
								</view>
								<view class="border"></view>
								<view class="padding">
									<view class="label">吉神</view>
									<view class="value">{{ calendarInfo.jishen }}</view>
								</view>
							</view>
							<view class="bottom-box-item d-flex align-center justify-center">
								<view class="padding">
									<view class="label">彭祖</view>
									<view class="value">{{ calendarInfo.baiji }}</view>
								</view>
							</view>
							<view class="bottom-box-item d-flex flex-column align-center justify-center">
								<view class="padding">
									<view class="label">冲煞</view>
									<view class="value">{{ calendarInfo.chongsha }}</view>
								</view>
								<view class="border"></view>
								<view class="padding">
									<view class="label">凶神</view>
									<view class="value">{{ calendarInfo.xiongshen }}</view>
								</view>
							</view>
						</view>
					</view>
				</view>

				<view class="text-center ss-m-t-50">
					<uni-icons type="close" size="40" color="#fff" @click="handleClose"></uni-icons>
				</view>
			</uni-popup>
		</view>
	</layout-page>
</template>

<script setup>
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import { ref } from 'vue'
	import Calendar from '@/components/uni-calendar/components/uni-calendar/uni-calendar.vue'
	import { getDrawLots } from '@/api/drawLots.js'
	import layoutPage from '@/layout'
	import { showAuthModal } from '@/hooks/useModal'
	import { getCalendarRecord, saveCalendarRecord } from '@/api/drawLots.js'

	const colorDict = {
		'白': '#FAFAFA',
		'黑': '#212121',
		'绿': '#43A047',
		'红': '#F44336',
		'黄': '#FDD835'
	}

	function getDate(date, AddDayCount = 0) {
		if (!date) {
			date = new Date()
		}
		if (typeof date !== 'object') {
			date = date.replace(/-/g, '/')
		}
		const dd = new Date(date)
		
		dd.setDate(dd.getDate() + AddDayCount) // 获取AddDayCount天后的日期
		
		const y = dd.getFullYear()
		const m = dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1 // 获取当前月份的日期，不足10补0
		const d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate() // 获取当前几号，不足10补0
		return {
			fullDate: y + '-' + m + '-' + d,
			year: y,
			month: m,
			date: d,
			day: dd.getDay()
		}
	}
	
	const date = ref(getDate(new Date()).fullDate)
	// 设置日期选中内容
	const selected = ref([])

	// 登录信息
	const userInfo = ref(uni.getStorageSync('wechat_user') || {})
	onLoad(() => {
		if (!userInfo.value || !userInfo.value?.openid) return showAuthModal()
	})

	onShow(() => {
		// 刷新一次本地登录信息，防止 onLoad 时未拿到最新登录态
		const latestUser = uni.getStorageSync('wechat_user')
		if (latestUser?.openid && latestUser?.openid !== userInfo.value?.openid) {
			userInfo.value = latestUser
		}
		if (userInfo.value?.openid) getCalendarData(date.value.slice(0, 7))
	})

	// 监听登录成功事件，立刻刷新数据
	uni.$off && uni.$off('auth:login')
	uni.$on && uni.$on('auth:login', (user) => {
		userInfo.value = user || uni.getStorageSync('wechat_user')
		if (userInfo.value?.openid) {
			getCalendarData(date.value.slice(0, 7))
		}
	})

	// const handleClear = () => {
	// 	selected.value = []
	// 	calendarRecord.value = []
	// 	userInfo.value = {}
	// 	uni.clearStorageSync()
	// 	showAuthModal()
	// }
	
	// 点击日期查看黄历信息
	const popupRef = ref()
	const calendarInfo = ref({})
	const handleChange = async (e) => {
		date.value = e.fulldate
		if (e.isBackToday) return // 点击左上角“今日”按钮不弹窗
		const index = calendarRecord.value.findIndex(val => val.date === e.fulldate)

		// 有存储过的黄历信息直接使用
		if (calendarRecord.value[index]?.almanac) {
			calendarInfo.value = calendarRecord.value[index].almanac
			popupRef.value.open()
			return
		}

		try {
			const { result } = await getDrawLots({ date: e.fulldate })
			if (!result) return uni.showToast({ title: '黄历信息获取失败', icon: 'none' })
			calendarInfo.value = result || {}

			// 将黄历信息存储到手账中
			if (calendarRecord.value?.length && userInfo.value?.openid) {
				const month_key = date.value.slice(0, 7)
				if (index > -1) {
					calendarRecord.value[index].almanac = result
				} else calendarRecord.value.push({ date: e.fulldate, notes: '', events: [], almanac: result })
				await saveCalendarRecord({
					openid: userInfo.value.openid,
					month_key,
					calendar_content: calendarRecord.value
				})
				getCalendarData(month_key)
			}

			popupRef.value.open()
		} catch (error) {
			console.log(error, '错误信息')
		}
	}

	// 获取手账记录
	const calendarRecord = ref([])
	const getCalendarData = async (month_key) => {
		try {
			const { result } = await getCalendarRecord({ month_key, openid: userInfo.value.openid })
			calendarRecord.value = result?.calendar_content || []
			selected.value = calendarRecord.value?.length ? calendarRecord.value.map((item) => {
				return { date: item.date, color: item?.almanac?.color ? colorDict[item?.almanac?.color] : '#f8bbd0' }
			}) : []
		} catch {}
	}

	// 切换月份
	const handleMonthSwitch = (e) => {
		console.log(e, '切换月份')
		getCalendarData(`${e.year}-${e.month < 10 ? '0' + e.month : e.month}`)
	}

	const handleClose = () => {
		popupRef.value.close()
		calendarInfo.value = {}
	}

	// 添加手账
	const handleAddJournal = () => {
		let url = `/pages/drawLots/journal?date=${date.value}`
		const index = calendarRecord.value.findIndex((item) => item.date === date.value)
		if (index > -1 && calendarRecord.value[index].notes) {
			// uni.showToast({ title: '手账已存在，可进行编辑', icon: 'none' })
			url += `&notes=${calendarRecord.value[index].notes}`
		}
		uni.navigateTo({
			url
		})
	}

	// 更新手账
	const handleUpdateJournal = (val) => {
		uni.navigateTo({
			url: `/pages/drawLots/journal?date=${val.date}&notes=${val.notes}`
		})
	}
</script>

<style lang="scss" scoped>
$commonColor: #c2a08c;
$size: 25px;

:deep {
	.uni-card {
		border-radius: 10px !important;
	}
}
.journal {
	margin-top: 30rpx;
	padding-bottom: 100px;
	.title {
		color: #999;
		margin: 0 30px;
	}
	.description {
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
	}
}

.add-btn {
	position: fixed;
	right: 20px;
	bottom: 50px;
	width: 60px;
	height: 60px;
	border-radius: 50%;
	background-color: #2979ff;
	display: flex;
	align-items: center;
	justify-content: center;
}

.popupContent {
	position: relative;
	background-color: #fff;
	width: 70vw;
	padding: 30rpx;
	.content-box {
		height: 100%;
		border: 1px solid $commonColor;
		border-radius: 6px; 
	}
	.yangli {
		font-weight: bold;
		color: $commonColor;
		font-size: 30px;
	}
	.yinli {
		color: #7f7f7f;
		margin: 10px 0;
	}
	.center-box {
		border-top: 1px solid $commonColor;
		border-bottom: 1px solid $commonColor;
		.yi {
			width: $size;
			height: $size;
			background-color: #c39c87;
			border-radius: 50%;
			color: #fff;
			margin-right: 10px;
			font-size: 14px;
		}
		.ji {
			width: $size;
			height: $size;
			background-color: #bfbfbf;
			border-radius: 50%;
			color: #fff;
			margin-right: 10px;
			font-size: 14px;
		}
	}
	.bottom-box {
		display: flex;
		&-item {
			width: 33.3%;
			text-align: center;
			border-right: 1px solid $commonColor;
			&:nth-child(3n) {
				border-right: none;
			}
			.label {
				font-size: 17px;
			}
			.value {
				color: #7f7f7f;
				font-size: 14px;
				margin-top: 10px;
			}
			.padding {
				padding: 10px;
			}
			.border {
				border-top: 1px solid #c2a08c;
				height: 1px;
				width: 100%;
			}
		}
	}
	.luckyColor {
		width: 50rpx;
		height: 50rpx;
		border-radius: 50%;
	}
}
</style>
