<template>
	<view class="container">
	
		<mescroll-body  ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback" :down="downOption" :up="upOption">
			<u-swipe-action ref="swipeWrapperRef" class="swipe_wrapper">
				<block v-if="keyword!=null && keyword.length>0">
					<conversation-item v-for="item in filteredList" :key="item.conversationID" @closeAllSwipe="closeAllSwipe" :source="item" ref="conversationItem" />
				</block>
				<block v-else>
					<conversation-item v-for="item in storeConversationList" :key="item.conversationID" @closeAllSwipe="closeAllSwipe" :source="item" ref="conversationItem" />
				</block>
				
			</u-swipe-action>
		</mescroll-body>

		<view class="loading_wrap" v-if="storeProgress > 0 && storeProgress < 100">
			<u-loading-icon :vertical="true" :text="storeProgress + '%'"></u-loading-icon>
		</view>
	</view>
</template>

<script>
import { mapGetters } from 'vuex';
// import ChatHeader from './components/ChatHeader.vue';
import ConversationItem from './components/ConversationItem.vue';
import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js';
export default {
	mixins: [MescrollMixin],
	components: {
		// ChatHeader,
		ConversationItem
	},
	data() {
		return {
			scrollTop: 0,
			old: {
				scrollTop: 0
			},
			lastClickTime: 0,
			doubleClick: 0,
			triggered: false,
			refreshing: false,
			keyword: '',
			mescroll: null,
			downOption: {
				//下拉刷新
				use: true,
				auto: false // 不自动加载 (mixin已处理第一个tab触发downCallback)
			},
			upOption: {
				onScroll: false,
				use: true, // 是否启用上拉加载; 默认true
				page: {
					pae: 0, // 当前页码,默认0,回调之前会加1,即callback(page)会从1开始
					size: 50 // 每页数据的数量,默认10
				},
				noMoreSize: 10, // 配置列表的总数量要大于等于5条才显示'-- END --'的提示
				textNoMore: '已经到底了',
				empty: {
					icon: 'https://cqtyt-2025.oss-cn-beijing.aliyuncs.com/huyi/imagesNew/cf4a86b913a04341bb44e34bb4d37aa2.png',
					tip: '暂无数据'
				}
			},
			filteredList:[],
		}
	},
	computed: {
		...mapGetters(['storeConversationList', 'storeIsSyncing', 'storeProgress'])
	},
	onReady() {
		
	},
	onShow() {
		this.$store.dispatch('conversation/getUnReadCount');
	},
	onLoad() {
		// this._freshing = false;
		// this.triggered = true;
		// this.mescroll.resetUpScroll();
	},
	onTabItemTap(item) {
		const currentTime = Date.now();
		if (item.index == 0 && currentTime - this.lastClickTime < 300) {
			this.scrollToTop();
		} else {
			this.lastClickTime = currentTime;
		}
	},
	methods: {
		scroll(e) {
			this.old.scrollTop = e.detail.scrollTop;
		},
		scrollToTop() {
			const conversationItem = this.$refs.conversationItem;
			if (conversationItem) {
				uni.createSelectorQuery()
					.in(this)
					.select(`.conversation_item`)
					.boundingClientRect(async (rect) => {
						if (rect) {
							const itemHeight = rect.height;
							const index = await this.getNextUnReadIndex(itemHeight);
							const totalHeight = itemHeight * index;
							this.scrollTop = this.old.scrollTop;
							this.$nextTick(function () {
								this.scrollTop = totalHeight;
							});
						}
					}).exec();
			}
		},
		getNextUnReadIndex(itemHeight) {
			return new Promise((resolve) => {
				uni.createSelectorQuery()
					.in(this)
					.select('.scroll-view')
					.scrollOffset((res) => {
						let start = Math.ceil(res.scrollTop / itemHeight);
						if (res.scrollTop % itemHeight === 0) {
							start++;
						}
						this.doubleClick = this.storeConversationList.slice(0, start).filter((item) => item.unreadCount > 0).length;
						const unReadList = this.storeConversationList.filter((item) => item.unreadCount > 0);
						const current = unReadList[(this.doubleClick %= unReadList.length)];
						const index = this.storeConversationList.findIndex((item) => item.conversationID === current.conversationID);
						resolve(index);
					})
					.exec();
			});
		},
		onRefresh() {
			if (this._freshing) return;
			this._freshing = true;
			this.queryList(true);
		},
		onRestore() {
			this.triggered = 'restore';
		},
		scrolltolower() {
			this.queryList();
		},
		async queryList(isFirstPage = false) {
			await this.$store.dispatch('conversation/getConversationList', isFirstPage);
			this.triggered = false;
			this._freshing = false;
		},
		async queryListNew(page) {
			const list = await this.$store.dispatch('conversation/getConversationList', page.num==1);
			if(list.length>0){
				this.mescroll.endSuccess(list.length, list.length==page.size);
			}else{
				this.mescroll.endSuccess(list.length, false);
			}
		},
		
		mescrollInit(mescroll) {
			this.mescroll = mescroll;
		},
		/*下拉刷新的回调 */
		downCallback(mescroll) {
			mescroll.resetUpScroll();
			
		},
		upCallback(page) {
			//联网加载数据
			this.queryListNew(page);
		},
		toSearch() {
			      if (!this.keyword) {
			          this.filteredList = this.storeConversationList; // 如果关键词为空，显示全部
			          return;
			      }
			      this.filteredList = this.storeConversationList.filter((item) => {
						// 检查 showName 是否包含关键词
						const showNameMatch = item.showName.toLowerCase().includes(this.keyword.toLowerCase());
						console.log(showNameMatch);
						// 检查 latestMsg 中 textElem 的 content 是否包含关键词
						const latestMsg = JSON.parse(item.latestMsg);
						const contentMatch =latestMsg.textElem && latestMsg.textElem.content.toLowerCase()
							.includes(this.keyword.toLowerCase());
						return showNameMatch || contentMatch;
			      });
			     //uni.$u.route("/pages_im/pages/common/globalSearch/index");
		},
		closeAllSwipe() {
			this.$refs.swipeWrapperRef.closeAll();
		}
	}
};
</script>

<style lang="scss" scoped>
.container {
	@include colBox(false);
	height: 100vh;
	width: 100%;
	overflow-y: hidden;
	box-sizing: border-box;
	background-repeat: no-repeat;
	background-size: 100%;
	position: relative;
	z-index: 2;
	background: #f5f7fa;
	.bg-img {
		position: absolute;
		width: 100%;
		height: 524rpx;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 0;
	}
}

.search-cont {
	padding: 16upx 30upx;
	background-color: #ffffff;
	.inner {
		box-sizing: border-box;
		width: 100%;
		height: 72upx;
		background: #f7f7f7;
		border-radius: 36upx;
		display: flex;
		align-items: center;
		padding: 0 30upx;
		.icon-search {
			width: 28upx;
			height: 28upx;
			margin-right: 20upx;
		}
		input {
			height: 60upx;
			line-height: 60upx;
			flex: 1;
		}
	}
}

.z-paging-content {
	flex: 1;
}

.swipe_wrapper {
	@include colBox(false);
	flex: 1;
	width: 100%;
	overflow-y: auto;
}

.scroll-view {
	height: 0;
	flex: 1;
	background: transparent;
}

.loading_wrap {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
}

::v-deep .u-swipe-action-item__right__button__wrapper__text {
	-webkit-line-clamp: 2 !important;
	max-width: 32px;
}
</style>
