<template>
	<view class="content">
		<!-- 标题栏 -->
		<view class="header-row">
			<view class="back-button" @click="back">
				<image src="/static/ic_back.png" class="back-icon"></image>
			</view>
			<text class="title">{{ $t('me.notification') }}</text>
			<view class="mark-read-btn" @click="markAllRead">
				<!-- <text class="mark-read-text">{{ $t('notification.markAllRead') }}</text> -->
			</view>
		</view>

		<!-- Tab 区域 -->
		<view class="tab-container">
			<view class="tab-item" :class="{ active: activeTab === 'all' }" @click="switchTab('all')">
				<text class="tab-text" :class="{ active: activeTab === 'all' }">{{ $t('notification.all') }}</text>
				<view v-if="unreadCount.all > 0" class="badge">{{ unreadCount.all }}</view>
			</view>
			<view class="tab-item" :class="{ active: activeTab === 'system' }" @click="switchTab('system')">
				<text class="tab-text" :class="{ active: activeTab === 'system' }">{{ $t('notification.system') }}</text>
				<view v-if="unreadCount.system > 0" class="badge">{{ unreadCount.system }}</view>
			</view>
			<view class="tab-item" :class="{ active: activeTab === 'activity' }" @click="switchTab('activity')">
				<text class="tab-text" :class="{ active: activeTab === 'activity' }">{{ $t('notification.activity') }}</text>
				<view v-if="unreadCount.activity > 0" class="badge">{{ unreadCount.activity }}</view>
			</view>
			<view class="tab-item" :class="{ active: activeTab === 'service' }" @click="switchTab('service')">
				<text class="tab-text" :class="{ active: activeTab === 'service' }">{{ $t('notification.service') }}</text>
				<view v-if="unreadCount.service > 0" class="badge">{{ unreadCount.service }}</view>
			</view>
		</view>

		<!-- 通知列表 -->
		<scroll-view class="notification-list" scroll-y @scrolltolower="loadMore" :show-scrollbar="false">
			<view class="notification-item" :class="{ unread: !item.isRead }" v-for="item in notificationList"
				:key="item.id" @click="readNotification(item)">
				<view class="item-header">
					<text class="item-title">{{ item.title }}</text>
					<view v-if="!item.isRead" class="unread-dot"></view>
				</view>
				<text class="item-content">{{ item.content }}</text>
				<text class="item-time">{{ formatTime(item.createdAt) }}</text>
			</view>

			<!-- 加载更多 -->
			<view v-if="loading" class="loading-more">
				<text class="loading-text">{{ $t('common.loading') }}</text>
			</view>

			<!-- 没有更多 -->
			<view v-if="!loading && !hasMore && notificationList.length > 0" class="loading-more">
				<text class="loading-text">{{ $t('common.noMore') || '没有更多了' }}</text>
			</view>

			<!-- 空状态 -->
			<view v-if="notificationList.length === 0 && !loading" class="empty-state">
				<image src="/static/ic_notice.png" class="empty-icon" mode="aspectFit"></image>
				<text class="no-data">{{ $t('notification.noNotification') }}</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import { AppServer } from '@/modules/api/AppServer.js'

	export default {
		data() {
			return {
				activeTab: 'all',
				loading: false,
				notificationList: [],
				unreadCount: { all: 0, system: 0, activity: 0, service: 0 },
				pagination: { page: 1, limit: 10, total: 0 },
				hasMore: true
			}
		},
		onLoad() {
			this.fetchUnreadCount()
			this.fetchNotifications()
		},
		methods: {
			back() {
				uni.navigateBack({ delta: 1 })
			},
			switchTab(tab) {
				if (this.activeTab === tab) return
				this.activeTab = tab
				this.pagination.page = 1
				this.notificationList = []
				this.hasMore = true
				this.fetchNotifications()
			},
			async fetchUnreadCount() {
				try {
					const appserver = new AppServer()
					const res = await appserver.GetNotificationUnreadCount()
					if (res.code === 0 && res.data) {
						this.unreadCount = res.data
					}
				} catch (e) {
					console.error('获取未读数量失败:', e)
				}
			},
			async fetchNotifications() {
				if (this.loading) return
				this.loading = true
				try {
					const appserver = new AppServer()
					const params = {
						page: this.pagination.page,
						limit: this.pagination.limit
					}
					if (this.activeTab !== 'all') {
						params.type = this.activeTab
					}
					const res = await appserver.GetNotifications(params)
					if (res.code === 0) {
						const newList = res.data || []
						if (this.pagination.page === 1) {
							this.notificationList = newList
						} else {
							this.notificationList = [...this.notificationList, ...newList]
						}
						this.pagination.total = res.pagination?.total || 0
						this.hasMore = newList.length >= this.pagination.limit
					}
				} catch (e) {
					console.error('获取通知列表失败:', e)
				} finally {
					this.loading = false
				}
			},
			loadMore() {
				if (!this.hasMore || this.loading) return
				this.pagination.page++
				this.fetchNotifications()
			},
			async readNotification(item) {
				if (item.isRead) return
				try {
					const appserver = new AppServer()
					await appserver.MarkNotificationAsRead(item.id)
					item.isRead = true
					// 更新未读数量
					this.unreadCount.all = Math.max(0, this.unreadCount.all - 1)
					this.unreadCount[item.type] = Math.max(0, this.unreadCount[item.type] - 1)
				} catch (e) {
					console.error('标记已读失败:', e)
				}
			},
			async markAllRead() {
				if (this.unreadCount.all === 0) {
					uni.showToast({ title: this.$t('notification.allRead') || '已全部已读', icon: 'none' })
					return
				}
				try {
					const appserver = new AppServer()
					await appserver.MarkAllNotificationsAsRead()
					// 更新本地状态
					this.notificationList.forEach(item => { item.isRead = true })
					this.unreadCount = { all: 0, system: 0, activity: 0, service: 0 }
					uni.showToast({ title: this.$t('common.success'), icon: 'success' })
				} catch (e) {
					console.error('标记全部已读失败:', e)
					uni.showToast({ title: this.$t('common.failed') || '操作失败', icon: 'none' })
				}
			},
			formatTime(timestamp) {
				if (!timestamp) return ''
				const now = Date.now()
				const time = new Date(timestamp).getTime()
				const diff = now - time
				const minutes = Math.floor(diff / (1000 * 60))
				const hours = Math.floor(diff / (1000 * 60 * 60))
				const days = Math.floor(diff / (1000 * 60 * 60 * 24))

				if (minutes < 1) return this.$t('notification.justNow') || '刚刚'
				if (minutes < 60) return (this.$t('notification.minutesAgo') || '{n}分钟前').replace('{n}', minutes)
				if (hours < 24) return (this.$t('notification.hoursAgo') || '{n}小时前').replace('{n}', hours)
				return (this.$t('notification.daysAgo') || '{n}天前').replace('{n}', days)
			}
		}
	}
</script>

<style lang="scss">
	.content {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #F3F3F3;
	}

	.header-row {
		width: 100%;
		margin-top: 100rpx;
		padding-bottom: 20rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
	}

	.back-button {
		width: 80rpx;
		height: 50rpx;
		margin-left: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.back-icon {
		width: 48rpx;
		height: 48rpx;
	}

	.title {
		font-size: 36rpx;
		font-weight: 500;
		color: #333;
	}

	.mark-read-btn {
		width: 80rpx;
		margin-right: 32rpx;
		display: flex;
		justify-content: flex-end;
	}

	.mark-read-text {
		font-size: 24rpx;
		color: #00A0BC;
	}

	.tab-container {
		display: flex;
		flex-direction: row;
		padding: 0 24rpx 24rpx;
	}

	.tab-item {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 16rpx 0;
		position: relative;
		margin: 0 8rpx;
		border-radius: 50rpx;
		border: 2rpx solid transparent;

		&.active {
			background-color: #E5FBFF;
			border-color: #00A0BC;
		}
	}

	.tab-text {
		font-size: 26rpx;
		color: #666;

		&.active {
			color: #00A0BC;
			font-weight: 500;
		}
	}

	.badge {
		position: absolute;
		top: -5rpx;
		right: 2rpx;
		min-width: 32rpx;
		height: 32rpx;
		padding: 0 2rpx;
		background-color: #FF3B30;
		border-radius: 16rpx;
		font-size: 20rpx;
		color: #fff;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.notification-list {
		flex: 1;
		height: 0;
	}

	.notification-item {
		width: 686rpx;
		background-color: #fff;
		border-radius: 20rpx;
		padding: 36rpx 32rpx;
		margin: 0 auto 24rpx;
		box-shadow: 0 2rpx 16rpx rgba(0, 0, 0, 0.08);
		box-sizing: border-box;

		&.unread {
			background-color: #fff;
		}
	}

	.item-header {
		display: flex;
		flex-direction: row;
		align-items: center;
		margin-bottom: 16rpx;
	}

	.item-title {
		font-size: 32rpx;
		font-weight: 500;
		color: #333;
		flex: 1;
	}

	.unread-dot {
		width: 12rpx;
		height: 12rpx;
		background-color: #FF3B30;
		border-radius: 50%;
		margin-left: 16rpx;
		flex-shrink: 0;
	}

	.item-content {
		font-size: 28rpx;
		color: #666;
		line-height: 1.7;
		display: block;
		margin-bottom: 16rpx;
	}

	.item-time {
		font-size: 24rpx;
		color: #999;
		display: block;
	}

	.loading-more {
		padding: 40rpx;
		display: flex;
		justify-content: center;
	}

	.loading-text {
		font-size: 26rpx;
		color: #999;
	}

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding-top: 200rpx;
	}

	.empty-icon {
		width: 200rpx;
		height: 200rpx;
		opacity: 0.3;
		margin-bottom: 40rpx;
	}

	.no-data {
		font-size: 28rpx;
		color: #999;
	}
</style>
