<template>
	<view class="messages-page">
		<view class="top-safe" :style="{ height: menuButtonInfo.top + 'px' }"></view>
		<view class="float-bar">
			<view class="home-back" @tap="backHome">
				<text class="home-back-icon">‹</text>
				<text>返回首页</text>
			</view>
		</view>
		<view class="head">
			<view class="title">消息</view>
			<view class="sub">聊天列表，未完成的陪伴。</view>
		</view>
		<view class="room-card" v-for="item in requests" :key="item.id" @tap="openRecord(item)" @longpress="confirmDelete(item)">
			<view class="avatar-wrap">
				<image class="avatar-img" v-if="item.avatarUrl" :src="item.avatarUrl" mode="aspectFill"></image>
				<view class="avatar" v-else>{{ item.avatar }}</view>
				<view class="unread-badge" v-if="item.unreadCount > 0">{{ item.unreadCount > 99 ? '99+' : item.unreadCount }}</view>
			</view>
			<view class="main">
				<view class="name">{{ item.name }}</view>
				<view class="desc">{{ item.desc }}</view>
			</view>
			<view class="streak-pill" v-if="item.streakDays > 0" :class="{ expiring: item.streakExpiring }" @tap.stop="showStreakTip(item)">
				🔥x{{ item.streakDays }}
			</view>
			<view class="tag soft" v-if="item.remeet">再遇见</view>
		</view>
		<view class="empty" v-if="!loading && !requests.length">没有未完成的关系，也是一种轻松。</view>
		<view class="empty" v-else>{{ loading ? '正在加载...' : (hasMore ? '上滑加载更多' : '没有更多消息了') }}</view>

		<ie-bottom-tab active="messages" :unread-count="unreadCount"></ie-bottom-tab>

		<view class="delete-mask" v-if="deleteDialogVisible" @tap="closeDeleteDialog">
			<view class="delete-dialog" @tap.stop>
				<view class="delete-icon">!</view>
				<view class="delete-title">删除这段聊天记录？</view>
				<view class="delete-content">删除后无法找回。对方再次发来消息时，这段对话会重新出现在这里。</view>
				<view class="delete-target" v-if="deleteTarget">
					<text>将删除与「{{ deleteTarget.name }}」的聊天入口</text>
				</view>
				<view class="delete-actions">
					<view class="delete-btn cancel" @tap="closeDeleteDialog">再想想</view>
					<view class="delete-btn danger" :class="{ disabled: deleting }" @tap="deleteRecordNow">{{ deleting ? '删除中...' : '确认删除' }}</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { getIeUnreadCount, pageIeRecords, deleteIeRecord } from '@/common/ieApi.js'
	import IeBottomTab from '@/components/ie-bottom-tab/ie-bottom-tab.vue'

	export default {
		components: { IeBottomTab },
		data() {
			return {
				menuButtonInfo: { top: 44 },
				unreadCount: 0,
				unreadTimer: null,
				requests: [],
				pageNumber: 1,
				pageSize: 10,
				hasMore: true,
				loading: false,
				loadedOnce: false,
				deleteDialogVisible: false,
				deleteTarget: null,
				deleting: false
			}
		},
		onLoad(options = {}) {
			if (uni.getMenuButtonBoundingClientRect) this.menuButtonInfo = uni.getMenuButtonBoundingClientRect()
			this.unreadCount = Number(options.unreadCount) || 0
			this.loadRecords()
		},
		onReachBottom() {
			this.loadRecords()
		},
		onShow() {
			this.startUnreadTimer()
			this.refreshOnShow()
		},
		onHide() {
			this.stopUnreadTimer()
		},
		onUnload() {
			this.stopUnreadTimer()
		},
		methods: {
			startUnreadTimer() {
				if (this.unreadTimer) return
				this.unreadTimer = setInterval(() => {
					this.refreshUnreadCount()
					this.refreshRecords()
				}, 15000)
			},
			stopUnreadTimer() {
				if (!this.unreadTimer) return
				clearInterval(this.unreadTimer)
				this.unreadTimer = null
			},
			async refreshUnreadCount() {
				const count = await getIeUnreadCount()
				if (count === null || count === undefined) return
				this.unreadCount = Number(count) || 0
			},
			refreshOnShow() {
				this.refreshUnreadCount()
				if (this.loadedOnce) {
					this.refreshRecords(true)
				}
			},
			normalizeRecord(item) {
				const remeet = item.remeetAvailable === 1
				return {
					id: item.id,
					roomId: item.roomId,
					targetUserId: item.targetUserId,
					mode: item.currentMode || item.mode || 'i',
					name: item.anonymousName || '半匿名漂流者',
					avatar: item.avatarText || ((item.currentMode || item.mode) === 'e' ? '光' : '月'),
					avatarUrl: item.avatarUrl || '',
					unreadCount: Number(item.unreadCount) || 0,
					desc: (item.unreadCount > 0 ? `${item.unreadCount} 条未读 · ` : '') + (item.intro || (remeet ? '可以从聊天记录继续这段对话。' : (item.summary || '这段聊天已保留在记录里。'))),
					streakDays: Number(item.streakDays) || 0,
					streakExpiring: !!item.streakExpiring,
					streakRewardInterval: item.streakRewardInterval || 7,
					remeet
				}
			},
			// 轮询刷新第一页：更新未读数/最新摘要，新会话或有新消息的会话提到顶部，不影响已加载的分页
			async refreshRecords(force = false) {
				if ((this.loading && !force) || this.deleting) return
				try {
					const page = await pageIeRecords(1, this.pageSize)
					const list = page && page.records ? page.records.map(this.normalizeRecord) : []
					if (!list.length) {
						if (force) {
							this.requests = []
							this.pageNumber = 1
							this.hasMore = false
						}
						return
					}
					const freshIds = new Set(list.map(item => item.id))
					this.requests = list.concat(this.requests.filter(item => !freshIds.has(item.id)))
					this.hasMore = page ? (page.current || 1) < (page.pages || 1) || this.requests.length < (page.total || this.requests.length) : false
				} catch (e) {
					// 轮询失败静默，下个周期再试
				}
			},
			async loadRecords() {
				if (this.loading || !this.hasMore) return
				this.loading = true
				try {
					const page = await pageIeRecords(this.pageNumber, this.pageSize)
					const list = page && page.records ? page.records.map(this.normalizeRecord) : []
					const exists = new Set(this.requests.map(item => item.id))
					this.requests = this.requests.concat(list.filter(item => !exists.has(item.id)))
					this.hasMore = page ? (page.current || this.pageNumber) < (page.pages || this.pageNumber) : false
					this.pageNumber += 1
					this.loadedOnce = true
				} finally {
					this.loading = false
				}
			},
			backHome() { uni.switchTab({ url: '/pages/index/index' }) },
			confirmDelete(item) {
				if (!item || !item.id) return
				this.deleteTarget = item
				this.deleteDialogVisible = true
			},
			closeDeleteDialog() {
				if (this.deleting) return
				this.deleteDialogVisible = false
				this.deleteTarget = null
			},
			async deleteRecordNow() {
				if (this.deleting || !this.deleteTarget || !this.deleteTarget.id) return
				this.deleting = true
				try {
					const recordId = this.deleteTarget.id
					await deleteIeRecord(recordId)
					this.requests = this.requests.filter(record => record.id !== recordId)
					this.deleteDialogVisible = false
					this.deleteTarget = null
					uni.showToast({ title: '已删除', icon: 'none' })
				} finally {
					this.deleting = false
				}
			},
			openRecord(item) {
				if (!item || !item.roomId) return
				uni.navigateTo({
					url: '/package1/ieBrowser/chat?mode=' + item.mode +
						'&roomId=' + item.roomId +
						'&targetUserId=' + (item.targetUserId || '') +
						'&name=' + encodeURIComponent(item.name || '半匿名漂流者') +
						'&avatar=' + encodeURIComponent(item.avatar || '◌') +
						'&avatarUrl=' + encodeURIComponent(item.avatarUrl || '') +
						'&quote=' + encodeURIComponent(item.desc || '')
				})
			},
			showStreakTip(item) {
				if (!item || !item.streakDays) return
				const tip = item.streakExpiring
					? `火花 x${item.streakDays}，今天还没续上，互发一句就不会熄灭`
					: `连续 ${item.streakDays} 天互相陪伴，每满 ${item.streakRewardInterval || 7} 天双方各得一次匹配机会`
				uni.showToast({ title: tip, icon: 'none', duration: 2600 })
			}
		}
	}
</script>

<style lang="scss" scoped>
	page { background: #f7f9ff; }
	.messages-page { min-height: 100vh; padding: 0 30rpx 230rpx; box-sizing: border-box; color: #151a2d; background: radial-gradient(circle at 18% 8%, rgba(169,255,231,.42), transparent 280rpx), linear-gradient(180deg, #fbfdff, #eef4ff); }
	.float-bar { position: relative; z-index: 5; display: flex; align-items: center; justify-content: space-between; }
	.home-back { display: flex; align-items: center; height: 58rpx; padding: 0 22rpx 0 12rpx; border: 1rpx solid rgba(255,255,255,.88); border-radius: 999rpx; color: rgba(22,27,46,.66); background: rgba(255,255,255,.66); backdrop-filter: blur(20rpx); box-shadow: 0 14rpx 36rpx rgba(96,112,160,.12), inset 0 1rpx 0 rgba(255,255,255,.95); font-size: 23rpx; font-weight: 800; }
	.home-back:active { transform: scale(.95); background: rgba(169,255,231,.7); }
	.home-back-icon { margin-right: 6rpx;padding-bottom: 6rpx; font-size: 40rpx; line-height: 50rpx; font-weight: 400; }
	.head { padding-top: 10rpx; }
	.title { font-size: 52rpx; font-weight: 800; }
	.sub { margin-top: 12rpx; color: rgba(21,26,45,.5); font-size: 25rpx; }
	.room-card { display: flex; align-items: center; margin-top: 26rpx; padding: 28rpx; border-radius: 36rpx; background: rgba(255,255,255,.64); border: 1rpx solid rgba(255,255,255,.86); box-shadow: 0 22rpx 60rpx rgba(96,112,160,.12); }
	.room-card.active { background: rgba(17,22,42,.92); color: #fff; }
	.avatar-wrap { position: relative; flex-shrink: 0; width: 78rpx; height: 78rpx; margin-right: 20rpx; }
	.pulse, .avatar, .avatar-img { width: 78rpx; height: 78rpx; border-radius: 50%; }
	.avatar { text-align: center; line-height: 78rpx; background: #a9ffe7; color: #11162a; font-weight: 800; }
	.unread-badge { position: absolute; right: -8rpx; top: -8rpx; min-width: 30rpx; height: 30rpx; line-height: 30rpx; padding: 0 8rpx; border-radius: 999rpx; text-align: center; color: #fff; background: #ff8fa3; border: 3rpx solid rgba(255,255,255,.96); box-shadow: 0 8rpx 18rpx rgba(255,143,163,.26); font-size: 18rpx; font-weight: 800; box-sizing: border-box; }
	.pulse { animation: breath 2.4s ease-in-out infinite; }
	.main { flex: 1; }
	.name { font-size: 29rpx; font-weight: 800; }
	.desc { margin-top: 8rpx; color: rgba(21,26,45,.52); font-size: 23rpx; line-height: 36rpx; }
	.active .desc { color: rgba(255,255,255,.58); }
	.tag { padding: 8rpx 16rpx; border-radius: 999rpx; color: #11162a; background: #a9ffe7; font-size: 20rpx; }
	.tag.soft { color: #7771d8; background: rgba(119,113,216,.1); }
	.streak-pill { flex-shrink: 0; margin-left: 12rpx; margin-right: 10rpx; padding: 8rpx 16rpx; border-radius: 999rpx; font-size: 22rpx; font-weight: 800; color: #ff6a3c; background: rgba(255,138,84,.14); border: 1rpx solid rgba(255,138,84,.3); }
	.streak-pill.expiring { animation: streakBlink 1.2s ease-in-out infinite; }
	.empty { margin-top: 42rpx; text-align: center; color: rgba(21,26,45,.36); font-size: 23rpx; }
	.delete-mask { position: fixed; inset: 0; z-index: 99; display: flex; align-items: flex-end; justify-content: center; padding: 0 30rpx 54rpx; box-sizing: border-box; background: rgba(16,22,40,.28); backdrop-filter: blur(12rpx); }
	.delete-dialog { width: 100%; padding: 42rpx 34rpx 30rpx; border-radius: 42rpx; box-sizing: border-box; text-align: center; background: linear-gradient(180deg, rgba(255,255,255,.96), rgba(248,251,255,.92)); border: 1rpx solid rgba(255,255,255,.9); box-shadow: 0 34rpx 90rpx rgba(42,50,86,.22); animation: dialogUp .18s ease-out; }
	.delete-icon { width: 68rpx; height: 68rpx; margin: 0 auto 22rpx; border-radius: 50%; line-height: 68rpx; color: #fff; font-size: 36rpx; font-weight: 900; background: linear-gradient(135deg, #ff8ba0, #e85d75); box-shadow: 0 16rpx 34rpx rgba(232,93,117,.28); }
	.delete-title { font-size: 34rpx; font-weight: 900; color: #151a2d; }
	.delete-content { width: 86%; margin: 16rpx auto 0; color: rgba(21,26,45,.55); font-size: 25rpx; line-height: 40rpx; }
	.delete-target { margin: 26rpx 0 6rpx; padding: 20rpx 24rpx; border-radius: 26rpx; color: rgba(21,26,45,.64); font-size: 24rpx; background: rgba(169,255,231,.32); }
	.delete-actions { display: flex; gap: 18rpx; margin-top: 30rpx; }
	.delete-btn { flex: 1; height: 86rpx; border-radius: 999rpx; line-height: 86rpx; font-size: 27rpx; font-weight: 800; }
	.delete-btn.cancel { color: rgba(21,26,45,.72); background: rgba(21,26,45,.06); }
	.delete-btn.danger { color: #fff; background: linear-gradient(135deg, #ff8ba0, #e85d75); box-shadow: 0 18rpx 38rpx rgba(232,93,117,.22); }
	.delete-btn.disabled { opacity: .62; }
	@keyframes breath { 0%, 100% { transform: scale(.9); opacity: .65; } 50% { transform: scale(1.04); opacity: 1; } }
	@keyframes streakBlink { 0%, 100% { opacity: 1; } 50% { opacity: .45; } }
	@keyframes dialogUp { from { transform: translateY(36rpx); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
</style>
