<template>
	<view class="content">
		
		<!-- <z-paging :height="msgListHeight + 'px'" ref="paging" v-model="dataList" use-chat-record-mode :fixed="false" > -->
			<!-- 聊天item -->
			<scroll-view :style="{ height: msgListHeight + 'px' }" scroll-y :scroll-top="scrollTop" scroll-with-animation>
				<view class="tips">
					小红娘提醒：任何涉及投资、理财、邮寄包裹等信息都存在诈骗嫌疑，请及时举报！
					<text class="link" @click.stop="$push('pages/article/detail/detail?id=461')">安全指南</text>
				</view>
				<view id="msg-box">
					<view :id="`z-paging-${index}`" v-for="(item, index) in dataList" :key="index">
						<chat-item @onImageClick="onImageClick(index)" :prevMsgTime="index>0?dataList[index - 1].createTime: null" :friendInfo="friendInfo" :item="item"></chat-item>
					</view>
				</view>
			</scroll-view>
		<!-- </z-paging> -->
		<view  id="chat-input-bar">
			<chat-input-bar @heightChange="resetMsgListHeight" @send="doSend" />
		</view>
		
	</view>
</template>

<script>
	import ChatInputBar from "@/components/chat-input-bar/chat-input-bar.vue"
	import ChatItem from "@/components/chat-item/chat-item.vue"
	import { mapGetters,mapActions} from 'vuex'
	import {
		USER_ID,
		USER_INFO
	} from '@/store/mutation-types'
	import storage from '@/utils/storage'
	import * as UserProfileApi from '@/api/love-user-profile.js'
	import ZPMixin from '@/uni_modules/z-paging/components/z-paging/js/z-paging-mixin'
	export default {
		mixins: [ZPMixin],
		components: {
			ChatInputBar,
			ChatItem
		},
		computed: {
			...mapGetters(['conversations'])
		},
		data() {
			return {
				friendId: 1,
				dataList: [],
				friendInfo: {},
				keyboardHeight: 0,
				screenHeight: 0,
				msgListHeight: 0,
				inputHeight: 0,
				scrollTop: 0
			}
		},
		onLoad(options) {
			this.friendId = options.friendId
			this.MarkRead(this.friendId)
			// this.friendInfo = this.$store.getters.friends.find(item=> item.userId = options.friendId)
		
			
			
			
		},
		async onReady() {
			// 获取屏幕高度
			uni.getSystemInfo({
				success: res => {
					console.log(res);
					this.screenHeight = res.windowHeight
					this.resetMsgListHeight()
				}
			})
			
			// 监听键盘高度变化
			uni.onKeyboardHeightChange(res => {
				this.keyboardHeight = res.height
				// this.resetMsgListHeight()
			})
			
			// 获取消息
			await this.LoadFriendMessage(this.friendId)
			const messages = this.conversations[this.friendId].messages || []
			this.friendInfo = this.conversations[this.friendId].friendInfo || {}
			uni.setNavigationBarTitle({
				title: this.friendInfo.nickname
			})
			const list = JSON.parse(JSON.stringify(messages))
			this.dataList = list
			setTimeout(()=>{
				this.toMsgListBottom()
			}, 1000)
			// this.$nextTick(()=>{
			// 	this.toMsgListBottom()
			// })
			// this.$refs.paging.complete(list);
			// 第一次聊天 发打招呼的卡牌
			if(list.length == 0){
				const userId = uni.getStorageSync('userId')
				const res = await UserProfileApi.getUserProfile(userId)
				console.log("第一次聊天 发打招呼的卡牌 ",res.data);
				console.log(res.data.images);
				const images = JSON.parse(res.data.images) || []
				if(images.length > 3){
					images.splice(3, images.length - 3)
				}
				this.SendMessage({
					type: 'card',
					content: JSON.stringify({
						age: res.data.age,
						city: res.data.city,
						height: res.data.height,
						yearlyPay: res.data.yearlyPay,
						position: res.data.position,
						files: images.map(d => {
							return {
								thumb: d.url,
								url: d.url
							}
						})
					}),
					toUserId: this.friendId,
					formUserId: this.$store.getters.userId
				})
			}
			// 收到新消息
			uni.$on('message' + this.friendId, (data)=>{
				this.dataList.push(data)
				this.MarkRead(this.friendId)
				
			})
		},
		onUnload() {
			uni.$off('message' + this.friendId)
		},
		onPageScroll(e) {
			//如果滚动到顶部，触发加载更多聊天记录
			if (e.scrollTop < 10) {
			}
		},
		methods: {
			...mapActions(['SendMessage','LoadFriendMessage','MarkRead']),
			/**
			 * 消息列表高度
			 */
			resetMsgListHeight(){
				
				const query = uni.createSelectorQuery().in(this);
				query.select('#chat-input-bar').boundingClientRect(data => {
					this.msgListHeight = this.screenHeight - data.height - this.keyboardHeight
					uni.$u.debounce(this.toMsgListBottom, 300)
				}).exec();
			},
			/**
			 * 滚动到最后一条消息
			 */
			toMsgListBottom() {
				this.scrollTop += 9999
			},
			async doSend(msg){
				await this.SendMessage({
					type: msg.type,
					content: msg.content,
					toUserId: this.friendId,
					formUserId: this.$store.getters.userId
				})
				this.toMsgListBottom()
				
				
			},
			onImageClick(index){
				console.log("onImageClick", index);
				const arr = []
				let current = 0
				this.dataList.forEach((item, i)=>{
					if(item.type == 'image'){
						arr.push(item.content)
						if(index == i){
							current = arr.length - 1
						}
					}
				})
				uni.previewImage({
					urls: arr,
					current
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content{
		height: 100vh;
		.tips{
			width: 660rpx;
			margin: 20rpx auto;
			color: #818284;
			font-size: 26rpx;
			padding: 20rpx;
			text-align: center;
			line-height: 1.3rem;
			background-color: #ffffff;
			border-radius: 10rpx;
			box-shadow: 0px 2px 5px 0px rgba(0, 0, 0, 0.1);
			.link{
				color: #681752;
				text-decoration: underline;
			}
		}
	}
</style>
