<template>
	<view class="sub-base-container">
		<view class="messgae-list" v-for="(item,index) in messageList" :key="index">
			<text class="date">{{item.date}}</text>
			<view class="message-item" v-for="(ele,idx) in item.list" :key="idx">
				<view class="messgae-info">
					<view class="info-text">
						<up-image class="avatar" :fade="false" :src="ele.icon" width="56rpx" height="56rpx"
							shape="circle"></up-image>
						<view><text class="my">{{ele.nickname}}</text> 使用 <text
								class="name">{{clockinTypeStr[ele.clockinType]}}</text> 能量增加 <text
								class="name">{{ele.energy}}分</text></view>
						<!-- <view><text class="my">励志人生</text> 向 <text class="name">茜茜荔</text> 留言 </view> -->
					</view>
					<!-- <text class="time">{{ele.createTime}}</text> -->
				</view>
				<view class="time">{{ele.createTime}}</view>
				<text class="message-text">{{ele.desc}}</text>
			</view>
		</view>
		<up-loadmore :status="loadStatus" />
	</view>
</template>

<script setup>
	import {
		ref,
	} from 'vue';
	import TREE from '@/api/tree.js'
	import {
		onLoad,
		onReachBottom,
		onPullDownRefresh
	} from '@dcloudio/uni-app'

	const messageList = ref([])
	const farmBuyIdData = ref('')
	const page = ref(1)
	const limit = 10
	const isLoading = ref(false)
	const hasMore = ref(true)
	const loadStatus = ref('loadmore') // loading | loadmore | nomore

	onLoad(({
		farmBuyId
	}) => {
		farmBuyIdData.value = farmBuyId
		fetchMessageList({ refresh: true })
	})

	const clockinTypeStr = {
		'1': '每日阳光',
		"2": "分享守护",
		"3": "每日祝福"
	}

	const fetchMessageList = ({ refresh = false } = {}) => {
		if (isLoading.value) return
		if (refresh) {
			page.value = 1
			hasMore.value = true
		}
		if (!hasMore.value) return
		isLoading.value = true
		loadStatus.value = 'loading'
		const params = {
			page: page.value,
			limit,
			farmBuyId: farmBuyIdData.value
		}
		TREE.getEnergyRecords(params)
			.then(res => {
				const list = (res?.data || []).map((it) => {
					const label = formatDateLabel(it)
					return { ...it, dateClass: label }
				})
				const grouped = groupByDateLabel(list)
				if (refresh) {
					messageList.value = grouped
				} else {
					mergeGroups(messageList.value, grouped)
				}
				if (list.length < limit) {
					hasMore.value = false
					loadStatus.value = 'nomore'
				} else {
					page.value += 1
					loadStatus.value = 'loadmore'
				}
			})
			.finally(() => {
				isLoading.value = false
				if (refresh) {
					uni.stopPullDownRefresh()
				}
			})
	}

	const groupByDateLabel = (records) => {
		const map = new Map()
		records.forEach((rec) => {
			const key = rec.dateClass
			if (!map.has(key)) map.set(key, [])
			map.get(key).push(rec)
		})
		return Array.from(map.entries()).map(([date, list]) => ({ date, list }))
	}

	const mergeGroups = (targetGroups, incomingGroups) => {
		incomingGroups.forEach((grp) => {
			const exist = targetGroups.find((g) => g.date === grp.date)
			if (exist) {
				exist.list = exist.list.concat(grp.list)
			} else {
				targetGroups.push({ date: grp.date, list: grp.list })
			}
		})
	}

	const formatDateLabel = (item) => {
		const src = item?.createTime || item?.dateClass || ''
		const d = parseToDate(src)
		if (!d) return (typeof item?.dateClass === 'string' && item.dateClass) ? item.dateClass : ''
		const today = new Date()
		const startOfToday = new Date(today.getFullYear(), today.getMonth(), today.getDate())
		const startOfThatDay = new Date(d.getFullYear(), d.getMonth(), d.getDate())
		const diffDays = Math.round((startOfToday - startOfThatDay) / 86400000)
		if (diffDays === 0) return '今天'
		if (diffDays === 1) return '昨天'
		return `${pad2(d.getMonth() + 1)}/${pad2(d.getDate())}`
	}

	const parseToDate = (str) => {
		if (!str || typeof str !== 'string') return null
		const normalized = str.replace(/-/g, '/').replace(/\.\d{3}.*/, '')
		const d = new Date(normalized)
		return isNaN(d.getTime()) ? null : d
	}

	const pad2 = (n) => (n < 10 ? `0${n}` : `${n}`)

	onReachBottom(() => {
		fetchMessageList()
	})

	onPullDownRefresh(() => {
		fetchMessageList({ refresh: true })
	})
</script>

<style lang="scss" scoped>
	.sub-base-container {
		.messgae-list {
			.date {
				font-size: 34rpx;
			}

			.message-item {
				margin-top: 24rpx;
				background: #fff;
				border-radius: 16rpx;
				padding: 24rpx 32rpx;
				.time {
					font-size: 28rpx;
					color: #999999;
					margin-left: 70rpx;
				}

				.messgae-info {
					display: flex;
					align-items: center;
					justify-content: space-between;
					margin-bottom: 16rpx;

					.info-text {
						display: flex;
						align-items: center;

						.my {
							font-weight: 500;
						}

						.name {
							color: #EAB400;
						}
					}

					.avatar {
						margin-right: 16rpx;
					}
				}

				.message-text {
					font-size: 28rpx;
				}
			}
		}

		.messgae-list+.messgae-list {
			margin-top: 24rpx;
		}
	}
</style>