<template>
	<view class="fe-page fe-page--tab msg-page">
		<scroll-view
			scroll-y
			class="page-scroll"
			:show-scrollbar="false"
			@scrolltolower="loadMore"
		>
			<view class="page-body">
				<view v-if="loading && !inbox.length" class="msg-empty">
					<text class="msg-empty__text">加载中...</text>
				</view>
				<view v-else-if="loadError && !inbox.length" class="msg-empty">
					<text class="msg-empty__text">{{ loadError }}</text>
					<view class="fe-btn fe-btn--primary fe-btn--sm msg-empty__btn" @tap="reload">重新加载</view>
				</view>
				<view v-else-if="!inbox.length" class="msg-empty">
					<text class="msg-empty__text">暂无消息</text>
				</view>
				<view
					v-for="(m, idx) in inbox"
					:key="m.msgKey"
					class="msg-card"
					:class="m.itemClass"
					@tap="onItemByIndex(idx)"
				>
					<view class="msg-card__top">
						<text class="fe-msg-type" :class="'fe-msg-type--' + m.typeClass">{{ m.typeLabel }}</text>
						<text class="msg-card__time">{{ m.timeText }}</text>
					</view>
					<text class="msg-card__title">{{ m.title }}</text>
					<text class="msg-card__desc">{{ m.desc }}</text>
					<view v-if="m.handledFlag" class="msg-card__handled">已处理</view>
				</view>
				<view v-if="inbox.length && loadingMore" class="msg-footer-tip">
					<text class="msg-footer-tip__text">加载更多...</text>
				</view>
				<view v-else-if="inbox.length && !hasMore" class="msg-footer-tip">
					<text class="msg-footer-tip__text">没有更多了</text>
				</view>
			</view>
		</scroll-view>

		<FeBottomNav current="message" role="enterprise" />
	</view>
</template>

<script>
import FeBottomNav from '@/packageA/components/FeBottomNav.vue'
import store from '@/common/store.js'
import { getToken } from '@/utils/request.js'
import { showToast } from '@/common/chat-data.js'
import { listMyNotifications } from '@/api/notification.js'
import { mapNotificationPage } from '@/utils/notification.js'

const PAGE_SIZE = 20

export default {
	components: { FeBottomNav },
	data() {
		return {
			inbox: [],
			loading: false,
			loadingMore: false,
			loadError: '',
			page: 1,
			hasMore: false,
			pendingCount: 0,
			unreadCount: 0
		}
	},
	onShow() {
		if (!this.ensureEnterpriseAccess()) return
		this.reload()
	},
	methods: {
		ensureEnterpriseAccess() {
			if (!getToken()) {
				uni.reLaunch({ url: '/packageA/auth/login' })
				return false
			}
			const s = store.getState()
			if (s.role === 'worker') {
				uni.reLaunch({ url: '/packageA/home/index' })
				return false
			}
			return true
		},
		reload() {
			this.page = 1
			this.hasMore = false
			this.loadError = ''
			this.fetchPage(true)
		},
		loadMore() {
			if (!this.hasMore || this.loading || this.loadingMore) return
			this.page += 1
			this.fetchPage(false)
		},
		async fetchPage(reset) {
			if (reset) this.loading = true
			else this.loadingMore = true
			try {
				const raw = await listMyNotifications(
					{ page: this.page, size: PAGE_SIZE },
					{ showError: false }
				)
				const pageData = mapNotificationPage(raw || {})
				this.pendingCount = pageData.pendingCount
				this.unreadCount = pageData.unreadCount
				this.hasMore = pageData.hasMore
				if (reset) {
					this.inbox = pageData.items
				} else {
					this.inbox = this.inbox.concat(pageData.items)
				}
				this.loadError = ''
			} catch (e) {
				if (reset) {
					this.inbox = []
					this.loadError = (e && (e.msg || e.message)) || '消息加载失败'
					showToast(this.loadError)
				} else {
					this.page = Math.max(1, this.page - 1)
					showToast((e && (e.msg || e.message)) || '加载更多失败')
				}
			} finally {
				this.loading = false
				this.loadingMore = false
			}
		},
		onItemByIndex(idx) {
			const item = this.inbox[idx]
			if (!item) return
			const url = item.actionUrl
			if (!url || typeof url !== 'string' || url.indexOf('/packageA/') !== 0) {
				showToast(item.title || '消息详情')
				return
			}
			const path = url.split('?')[0]
			if (path === '/packageA/home/index') {
				uni.reLaunch({ url })
				return
			}
			uni.navigateTo({
				url,
				fail: (err) => {
					console.error('notification navigate fail', url, err)
					uni.reLaunch({ url })
				}
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.msg-page {
	display: flex;
	flex-direction: column;
	height: 100vh;
	overflow: hidden;
	background: $fe-bg;
}

.page-scroll {
	flex: 1;
	height: 0;
}

.page-body {
	padding: 24rpx 32rpx calc(32rpx + 120rpx + #{$fe-h-safe-bottom});
}

.msg-empty {
	padding: 120rpx 0;
	text-align: center;
}

.msg-empty__text {
	display: block;
	font-size: 28rpx;
	color: $fe-muted;
}

.msg-empty__btn {
	margin: 28rpx auto 0;
	display: inline-flex;
}

.msg-card {
	position: relative;
	background: $fe-surface;
	border-radius: $fe-radius-lg;
	padding: 28rpx 32rpx;
	margin-bottom: 20rpx;
	border: 1rpx solid $fe-border-light;
}

.msg-card--unread {
	border-color: rgba(124, 58, 237, 0.28);
	background: #FBF9FF;
}

.msg-card--todo {
	box-shadow: inset 6rpx 0 0 $fe-warning;
}

.msg-card--handled {
	opacity: 0.72;
}

.msg-card__top {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 12rpx;
}

.msg-card__time {
	font-size: 22rpx;
	color: $fe-gray-400;
}

.msg-card__title {
	display: block;
	font-size: 28rpx;
	font-weight: 600;
	color: $fe-foreground;
}

.msg-card__desc {
	display: block;
	margin-top: 8rpx;
	font-size: 24rpx;
	color: $fe-muted;
	line-height: 1.5;
}

.msg-card__handled {
	margin-top: 12rpx;
	font-size: 22rpx;
	color: $fe-gray-400;
}

.msg-footer-tip {
	padding: 16rpx 0 8rpx;
	text-align: center;
}

.msg-footer-tip__text {
	font-size: 24rpx;
	color: $fe-gray-400;
}

.fe-msg-type--info {
	background: $fe-info-light;
	color: #1E40AF;
}

.fe-msg-type--success {
	background: $fe-success-light;
	color: #065F46;
}
</style>
