<template>
	<cu-custom bgColor="bg-white" :isBack="true">
		<template #backText></template>
		<template #content>消息</template>
	</cu-custom>
	<!-- #ifdef APP-PLUS -->
	<scroll-view scroll-y style="height: 88vh;" @scrolltolower="scrollbot">
	<!-- #endif -->
	<!-- #ifdef H5 -->
	<scroll-view scroll-y style="height: 93vh;" @scrolltolower="scrollbot">
	<!-- #endif -->
		<view v-for="(item,index) in filteredList" :key="index" class="flex align-center" @click="JumpDetails(item)">
			<view style="padding: 25rpx 25rpx 25rpx 20rpx;">
				<image :src="item.option_user.avatar" mode="widthFix" style="width: 80rpx;border-radius: 10rpx;"></image>
			</view>
			<view class="flex align-center" style="border-bottom: 1px solid #e7e7e7;padding: 25rpx 0px;width: 100%;margin-right: 30rpx;justify-content: space-between;">
				<view>
					<view style="color: #576b95;font-size: 16px;margin-bottom: 10rpx;">{{item.option_user.nickname}}</view>
					<view v-if="item.content">
						<mp-html container-style="overflow: hidden;display:inline;white-space: pre-wrap;font-size: 13px;line-break: anywhere;" :content="emojiToHtml(item.content)"/>
					</view>
					<view v-if="item.type==1">
						<uni-icons type="heart" size="15" color="#576b95"></uni-icons>
					</view>
					<view style="font-size: 10px;margin-top: 10rpx;">{{item.create_time}}</view>
				</view>
				<view v-if="item.file.src">
					<image :src="apiUrl+item.file.src" mode="widthFix" style="width: 80rpx;border-radius: 10rpx;margin-left: 20px;"></image>
				</view>
			</view>
		</view>
		<view v-if="!showEarlier && hasUnread"  @click="showEarlier = true" style="text-align: center; padding: 20rpx; color: #576b95;">
		  查看更早的消息...
		</view>
		<uni-load-more v-if="showEarlier" :status="status" :content-text="contentText"></uni-load-more>
	</scroll-view>
</template>

<script>
	import pinia from '@/store/index';
	import config from "@/common/config";
	import emoji from '@/utils/emoji.js';
	import { useMsgStore } from '@/store/message';
	
	const msgStore = useMsgStore(pinia)
	export default {
		data() {
			return {
				list:[],
				apiUrl:config.apiUrl,
				emojiMap:[],
				page:1,
				limit:20,
				status: 'more',//状态
				//显示的状态
				contentText: {
					contentdown: '查看更多',
					contentrefresh: '加载中....',
					contentnomore: '没有更多咯'
				},
				showEarlier: false, // 控制是否显示更早消息
				hasUnread: false    // 标记是否存在未读消息
			}
		},
		computed: {
		  filteredList() {
		    if (this.showEarlier) {
		      // 显示所有已读消息（is_read=1）
		      return this.list.sort((a, b) => new Date(b.create_time) - new Date(a.create_time))
		    } else {
		      // 优先显示未读消息（is_read=0）
		      const unread = this.list.filter(item => item.is_read === 0);
		      return unread.length ? unread : this.list;
		    }
		  }
		},
		created() {
			let emojiMap=[];
			// 解析所有表情
			emoji.forEach(function (item) {
				let child=item.children;
			  if(child.length>0){
				  child.forEach(function (val) {
					  let name=val.name;
					  let src=val.src;
					  emojiMap[name]=src;
				  })
			  }
			});
			this.emojiMap=emojiMap;
		},
		onShow() {
			this.getNoticeList()
		},
		methods: {
			getNoticeList(){
				let params = {page:this.page,limit:this.limit}
				this.status = 'loading'; // 加载中
				this.$api.compaApi.getNoticeList(params).then(res => {
					// 判断是否还有更多数据
					if (res.data.length <= res.count) {
						this.status = 'noMore'; // 没有更多数据
					} else {
						this.status = 'more'; // 还有更多数据
					}
					
					this.list = res.data
					msgStore.getCount(0);
					this.hasUnread = this.list.some(item => item.is_read === 0)
					// 默认按时间倒序排列（确保最新消息在顶部）
					this.list.sort((a, b) => new Date(b.create_time) - new Date(a.create_time))
					
					// 如果没有未读消息，直接显示所有已读
					if (!this.hasUnread) {
					  this.showEarlier = true;
					}
					
					
				})
			},
			JumpDetails(item){
				uni.navigateTo({
					url:`/pages/compass/friendscircledetails?posts_id=${item.posts_id}&userid=${item.posts_user_id}`
				})
			},
			scrollbot(){
				if (this.status == 'noMore') {
					return;
				}
				this.page++
				this.getNoticeList()
				// console.log('已触发底部事件');
			},
			// 自动解析消息中的表情
			emojiToHtml(str){
				if(!str){
					return;
				}
				let emojiMap=this.emojiMap;
				return str.replace(/\[!(\w+)\]/gi, function (str, match) {
					var file = match;
					return emojiMap[file] ? "<img class='mr-5' style=\"width:18px;height:18px\" emoji-name=\"".concat(match, "\" src=\"").concat(emojiMap[file], "\" />") : "[!".concat(match, "]");
				  });
			},
		}
	}
</script>

<style scoped lang="scss">
.load-more-button {
  font-size: 28rpx;
  color: #576b95;
  padding: 30rpx 0;
  border-top: 1px solid #e7e7e7;
}
</style>
