<template>
	<view class="session-page">
		<view class="header" :style="{ paddingTop: statusBarTop + 'px' }">
			<view class="back" @tap="back"><uni-icons type="left" size="22" color="#15362f"></uni-icons></view>
			<view class="title-row">
				<view class="title">我的咨询</view>
				<view class="read-all-btn" v-if="chatUnread + commentUnread > 0" @tap="markAllRead">一键已读</view>
			</view>
			<view class="subtitle">我咨询的和咨询我的都在这里</view>
			<view class="message-tabs">
				<view class="message-tab" :class="{ active: activeTab == 'chat' }" @tap="switchTab('chat')">
					<text>我的消息</text>
					<view class="tab-badge" v-if="chatUnread > 0">{{formatBadgeCount(chatUnread)}}</view>
				</view>
				<view class="message-tab" :class="{ active: activeTab == 'comment' }" @tap="switchTab('comment')">
					<text>我的留言</text>
					<view class="tab-badge" v-if="commentUnread > 0">{{formatBadgeCount(commentUnread)}}</view>
				</view>
			</view>
		</view>

		<scroll-view scroll-y class="session-list" @scrolltolower="loadMore">
			<view class="session-card" v-for="item in list" :key="item.id" @tap="openItem(item)">
				<image class="cover" :src="item.goodsCover || defaultCover" mode="aspectFill"></image>
				<view class="main">
					<view class="top-row">
						<view class="goods-title">{{item.goodsTitle || '校园二手商品'}}</view>
						<view class="role-tag" :class="{ seller: item.role == 'seller' }">{{item.roleText}}</view>
						<view class="card-badge" v-if="item.unreadCount > 0">{{formatBadgeCount(item.unreadCount)}}</view>
					</view>
					<view class="goods-meta">
						<text v-if="item.goodsPrice !== ''">¥{{item.goodsPrice}}</text>
						<text>{{item.displayTime}}</text>
					</view>
					<view class="session-desc">{{item.desc}}</view>
				</view>
				<view class="delete-btn" @tap.stop="deleteItem(item)">删除</view>
			</view>

			<view class="empty" v-if="!list.length && !loading">暂无咨询记录</view>
			<view class="load-more" v-if="loading">加载中...</view>
			<view class="load-more" v-else-if="list.length && pageNum >= totalPages">没有更多了</view>
			<view class="bottom-space"></view>
		</scroll-view>
	</view>
</template>

<script>
	import {
		pageMyFishSessions,
		pageMyFishMessageComments,
		deleteMyFishSessionMessage,
		deleteMyFishCommentMessage,
		getFishUnreadSummary,
		markAllFishUnreadRead
	} from '@/common/fishMarketApi.js'

	export default {
		data() {
			return {
				statusBarTop: 24,
				activeTab: 'chat',
				list: [],
				pageNum: 1,
				pageSize: 10,
				totalPages: 1,
				loading: false,
				loadedOnce: false,
				chatUnread: 0,
				commentUnread: 0,
				selfId: String(uni.getStorageSync('id') || ''),
				defaultCover: '/static/images/img/songshu.png'
			}
		},
		onLoad() {
			if (uni.getMenuButtonBoundingClientRect) {
				this.statusBarTop = uni.getMenuButtonBoundingClientRect().top || this.statusBarTop
			}
			this.load()
		},
		onShow() {
			if (!this.loadedOnce) return
			this.reload()
		},
		methods: {
			back() {
				uni.navigateBack()
			},
			reload() {
				this.pageNum = 1
				this.totalPages = 1
				this.list = []
				this.load()
			},
			loadMore() {
				if (this.loading || this.pageNum >= this.totalPages) return
				this.pageNum += 1
				this.load()
			},
			load() {
				if (this.loading) return
				this.loading = true
				this.loadUnreadSummary()
				const request = this.activeTab == 'comment' ? pageMyFishMessageComments : pageMyFishSessions
				request({
					pageNum: this.pageNum,
					pageSize: this.pageSize
				}).then(page => {
					const records = page && (page.records || page.content) ? (page.records || page.content) : []
					this.totalPages = Number(page && (page.pages || page.totalPages)) || 1
					const normalized = this.activeTab == 'comment' ? this.normalizeComments(records) : this.normalizeSessions(records)
					this.list = this.pageNum == 1 ? normalized : this.list.concat(normalized)
				}).finally(() => {
					this.loading = false
					this.loadedOnce = true
				})
			},
			switchTab(tab) {
				if (this.activeTab == tab) return
				this.activeTab = tab
				this.pageNum = 1
				this.totalPages = 1
				this.list = []
				this.load()
			},
			loadUnreadSummary() {
				getFishUnreadSummary().then(res => {
					this.chatUnread = Number(res && res.chatUnread) || 0
					this.commentUnread = Number(res && res.commentUnread) || 0
					uni.$emit('fishUnreadChange', {
						chatUnread: this.chatUnread,
						commentUnread: this.commentUnread,
						fishUnread: this.chatUnread + this.commentUnread
					})
				}).catch(() => {})
			},
			markAllRead() {
				if (this.loading) return
				uni.showModal({
					title: '一键已读',
					content: '确定将所有消息和留言标记为已读吗？',
					confirmText: '已读',
					success: (res) => {
						if (!res.confirm) return
						markAllFishUnreadRead().then(() => {
							this.chatUnread = 0
							this.commentUnread = 0
							uni.$emit('fishUnreadChange', { chatUnread: 0, commentUnread: 0, fishUnread: 0 })
							uni.showToast({ title: '已全部标记已读', icon: 'none' })
							this.reload()
						})
					}
				})
			},
			deleteItem(item) {
				if (!item || !item.id) return
				const isComment = this.activeTab == 'comment'
				uni.showModal({
					title: '删除记录',
					content: isComment ? '确定删除这条留言提醒吗？' : '确定删除这条消息记录吗？',
					confirmText: '删除',
					confirmColor: '#e34d59',
					success: (res) => {
						if (!res.confirm) return
						const request = isComment ? deleteMyFishCommentMessage : deleteMyFishSessionMessage
						request(item.id).then(() => {
							uni.showToast({ title: '删除成功', icon: 'none' })
							this.reload()
						})
					}
				})
			},
			formatBadgeCount(count) {
				const value = Number(count) || 0
				return value > 99 ? '99+' : value
			},
			normalizeSessions(records) {
				return (Array.isArray(records) ? records : []).map(session => {
					const isWant = session.bizType == 'want' || !!session.wantId
					const role = String(session.sellerId) == this.selfId ? 'seller' : 'buyer'
					return {
						...session,
						isWant,
						role,
						roleText: isWant ? (role == 'seller' ? '我供货的' : '我的求购') : (role == 'seller' ? '咨询我的' : '我咨询的'),
						goodsTitle: session.displayTitle || '',
						goodsCover: session.displayCover || '',
						goodsPrice: session.displayPrice !== undefined && session.displayPrice !== null ? session.displayPrice : '',
						displayTime: this.formatDisplayTime(session.lastChatTime || session.firstConsultTime || session.createTime),
						desc: isWant ? (role == 'seller' ? '你正在响应这条求购' : '同学正在响应你的求购') : (role == 'seller' ? '买家正在咨询这件商品' : '你正在咨询这件商品')
					}
				})
			},
			normalizeComments(records) {
				return (Array.isArray(records) ? records : []).map(comment => {
					const isMine = String(comment.userId) == this.selfId
					return {
						...comment,
						role: isMine ? 'buyer' : 'seller',
						roleText: isMine ? '我留言的' : (comment.sellerReply ? '卖家回复' : '留言我的'),
						goodsTitle: comment.displayTitle || '',
						goodsCover: comment.displayCover || '',
						goodsPrice: comment.displayPrice !== undefined && comment.displayPrice !== null ? comment.displayPrice : '',
						displayTime: this.formatDisplayTime(comment.createTime),
						desc: (comment.replyToUserName ? (comment.userName || '校园同学') + ' 回复 ' + comment.replyToUserName + '：' : '') + (comment.content || '')
					}
				})
			},
			formatDisplayTime(value) {
				if (!value) return ''
				const text = String(value).replace(/T/g, ' ')
				const match = text.match(/^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2})/)
				if (!match) return text
				return `${match[1]}-${match[2]}-${match[3]} ${match[4]}:${match[5]}`
			},
			openItem(item) {
				if (this.activeTab == 'comment') {
					if (!item.goodsId) return
					uni.navigateTo({ url: '/package2/IdleTrad/detail?id=' + item.goodsId })
					return
				}
				this.openChat(item)
			},
			openChat(item) {
				const sessionId = item.sessionId || item.id
				if (!sessionId) return
				uni.navigateTo({
					url: `/package2/IdleTrad/chat?sessionId=${sessionId}&goodsId=${item.targetGoodsId || item.goodsId || ''}&wantId=${item.targetWantId || item.wantId || ''}`
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: #f7f9f7;
	}

	.session-page {
		min-height: 100vh;
		background: linear-gradient(180deg, #e8fbf3 0%, #f7f9f7 300rpx);
		color: #15362f;
	}

	.header {
		padding: 0 28rpx 24rpx;
	}

	.back {
		width: 68rpx;
		height: 68rpx;
		display: flex;
		align-items: center;
	}

	.title-row {
		margin-top: 8rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.title {
		flex: 1;
		margin-top: 8rpx;
		font-size: 42rpx;
		font-weight: 900;
	}

	.title-row .title {
		margin-top: 0;
	}

	.read-all-btn {
		margin-left: 20rpx;
		padding: 10rpx 20rpx;
		border-radius: 24rpx;
		background: #e8fbf3;
		color: #18a878;
		font-size: 22rpx;
		font-weight: 900;
		white-space: nowrap;
	}

	.subtitle {
		margin-top: 8rpx;
		color: #71857f;
		font-size: 23rpx;
	}

	.message-tabs {
		margin-top: 24rpx;
		padding: 8rpx;
		display: flex;
		border-radius: 28rpx;
		background: rgba(255, 255, 255, .82);
		box-shadow: 0 8rpx 22rpx rgba(20, 60, 48, .06);
	}

	.message-tab {
		position: relative;
		flex: 1;
		height: 58rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 24rpx;
		color: #71857f;
		font-size: 25rpx;
		font-weight: 900;
	}

	.message-tab.active {
		background: linear-gradient(135deg, #37c990, #19af7e);
		color: #fff;
	}

	.tab-badge,
	.card-badge {
		min-width: 30rpx;
		height: 30rpx;
		padding: 0 8rpx;
		border-radius: 18rpx;
		background: #ff4d5f;
		color: #fff;
		font-size: 18rpx;
		font-weight: 900;
		line-height: 30rpx;
		text-align: center;
		box-sizing: border-box;
	}

	.tab-badge {
		margin-left: 8rpx;
	}

	.card-badge {
		margin-left: 8rpx;
		flex-shrink: 0;
	}

	.session-list {
		height: calc(100vh - 280rpx);
	}

	.session-card {
		margin: 18rpx 24rpx 0;
		padding: 18rpx;
		display: flex;
		align-items: center;
		border-radius: 26rpx;
		background: #fff;
		box-shadow: 0 10rpx 26rpx rgba(20, 60, 48, 0.06);
	}

	.cover {
		width: 132rpx;
		height: 132rpx;
		border-radius: 20rpx;
		background: #edf4f1;
		flex-shrink: 0;
	}

	.main {
		flex: 1;
		min-width: 0;
		margin-left: 18rpx;
	}

	.delete-btn {
		margin-left: 16rpx;
		padding: 12rpx 18rpx;
		border-radius: 22rpx;
		background: #fff1f2;
		color: #e34d59;
		font-size: 22rpx;
		font-weight: 900;
		flex-shrink: 0;
	}

	.top-row {
		display: flex;
		align-items: center;
	}

	.goods-title {
		flex: 1;
		overflow: hidden;
		font-size: 28rpx;
		font-weight: 900;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.role-tag {
		margin-left: 12rpx;
		padding: 6rpx 14rpx;
		border-radius: 18rpx;
		background: #e8fbf3;
		color: #18a878;
		font-size: 20rpx;
		font-weight: 900;
	}

	.role-tag.seller {
		background: #fff2df;
		color: #df8618;
	}

	.goods-meta {
		margin-top: 10rpx;
		display: flex;
		gap: 18rpx;
		color: #8a9994;
		font-size: 21rpx;
	}

	.goods-meta text:first-child {
		color: #ef4c3f;
		font-weight: 900;
	}

	.session-desc {
		margin-top: 10rpx;
		color: #61736e;
		font-size: 23rpx;
	}

	.empty,
	.load-more {
		padding: 70rpx 0;
		color: #9aa8a4;
		text-align: center;
		font-size: 24rpx;
	}

	.bottom-space {
		height: 80rpx;
	}
</style>
