<template>
	<scroll-view
		class="scroll-view"
		scroll-y="true" 
		:style="{'height': `${scrollHeight}px`,'margin-top':`${topbarOffsetHeight}px`}"
		v-if="scrollHeight>0"
		lower-threshold="200"
		:scroll-top="scrollTop"
		:scroll-into-view="scrollTo"
		scroll-with-animation="true"
		refresher-enabled="true"
		:refresher-triggered="scrollTriggered"
		:refresher-threshold="45" 
		refresher-default-style="white"
		refresher-background="#151126" 
		@refresherrefresh="scrollRefresh" 
		@refresherpulling="scrollPulling"
		@refresherrestore="scrollRestore" 
		@refresherabort="scrollAbort"
		@scrolltolower="scrollToBottom"
	>
		<view id="message-scroll" style="width:100%">
			<view class="no-message" v-if="isCompleted">没有更多啦</view>
			<view v-for="(item,index) in messageList" :key="index" class="t-message">
				<view v-if="conversation.type !== '@TIM#SYSTEM'" :id="item.ID">
					<view class="t-message-item">
						<TUI-TipMessage v-if="item.type === 'TIMGroupTipElem'" :message="item"></TUI-TipMessage>
						<view v-if="item.type !== 'TIMGroupTipElem'" :class="item.flow === 'out'||(item.flow === 'in'&&item.payload.data&&JSON.parse(item.payload.data).type===99) ? 't-self-message' : 't-recieve-message'">
							<image
								class="t-message-avatar"
								v-if="(item.flow === 'in'&&item.type !== 'TIMCustomElem')||(item.flow === 'in'&&(item.payload.data&&JSON.parse(item.payload.data).type!==99))"
								:src="item.avatar || 'https://sdk-web-1252463788.cos.ap-hongkong.myqcloud.com/component/TUIKit/assets/avatar_21.png'"
								@click="toDetail(item.from)"
							></image>
							<view class="read-receipts" v-if="conversation.type === 'C2C' && item.flow === 'out'">
								<view v-if="item.isPeerRead">已读</view>
								<view v-else>未读</view>
							</view>
							<view>
								<TUI-TextMessage v-if="item.type === 'TIMTextElem'" :message="item" :isMine="item.flow === 'out'"></TUI-TextMessage>
								<TUI-ImageMessage v-if="item.type === 'TIMImageElem'" :message="item" :isMine="item.flow === 'out'"></TUI-ImageMessage>
								<TUI-VideoMessage v-if="item.type === 'TIMVideoFileElem'" :message="item" :isMine="item.flow === 'out'"></TUI-VideoMessage>
								<TUI-AudioMessage v-if="item.type === 'TIMSoundElem'" :message="item" :isMine="item.flow === 'out'"></TUI-AudioMessage>
								<TUI-CustomMessage v-if="item.type === 'TIMCustomElem'" :message="item" :isMine="item.flow === 'out'"></TUI-CustomMessage>
								<TUI-FaceMessage v-if="item.type === 'TIMFaceElem'" :message="item" :isMine="item.flow === 'out'"></TUI-FaceMessage>
								<TUI-FileMessage v-if="item.type === 'TIMFileElem'" :message="item" :isMine="item.flow === 'out'"></TUI-FileMessage>
							</view>
							<image
								class="t-message-avatar"
								v-if="item.flow === 'out'"
								:src="item.avatar || 'https://sdk-web-1252463788.cos.ap-hongkong.myqcloud.com/component/TUIKit/assets/avatar_21.png'"
							></image>
							<!-- <image
								class="t-message-avatar"
								v-if="item.flow === 'in'&&(item.payload.data&&JSON.parse(item.payload.data).type!==99)"
								:src="mineUserInfo.icon || 'https://sdk-web-1252463788.cos.ap-hongkong.myqcloud.com/component/TUIKit/assets/avatar_21.png'"
							></image> -->
						</view>
					</view>
				</view>
				<view v-else :id="item.ID" :data-value="item.ID"><TUI-SystemMessage :message="item"></TUI-SystemMessage></view>
			</view>
		</view>
		<view :id="endItem"></view>
	</scroll-view>
</template>

<script>
import TUITextMessage from '../message-elements/text-message/index';
import TUIImageMessage from '../message-elements/image-message/index';
import TUIVideoMessage from '../message-elements/video-message/index';
import TUIAudioMessage from '../message-elements/audio-message/index';
import TUICustomMessage from '../message-elements/custom-message/index';
import TUITipMessage from '../message-elements/tip-message/index';
import TUISystemMessage from '../message-elements/system-message/index';
import TUIFaceMessage from '../message-elements/face-message/index';
import TUIFileMessage from '../message-elements/file-message/index';

export default {
	data() {
		return {
			// 当前会话
			messageList: [],
			// 自己的 ID 用于区分历史消息中，哪部分是自己发出的
			scrollView: '',
			scrollTo: '',
			endItem:'',
			scrollTop:null,
			scrollRefreshing:false,
			scrollTriggered:true,
			nextReqMessageID: '',
			isSend:false,
			// 下一条消息标志
			isCompleted: false ,// 当前会话消息是否已经请求完毕
		};
	},

	components: {
		TUITextMessage,
		TUIImageMessage,
		TUIVideoMessage,
		TUIAudioMessage,
		TUICustomMessage,
		TUITipMessage,
		TUISystemMessage,
		TUIFaceMessage,
		TUIFileMessage
	},
	props: {
		conversation: {
			type: Object,
			default: () => {}
		},
		topbarOffsetHeight:{
			type:Number,
			default:0
		},
		scrollHeight:{
			type:Number,
			default:0
		},
	},
	watch: {
		conversation: {
			handler: function(newVal) {//发送消息不进行全部拉取
				if (newVal&&newVal.conversationID&&!this.isSend) {
					console.log(newVal.conversationID)
					this.conversation=newVal;
					this.getMessageList(newVal);
				};
			},
			immediate: true,
			deep: true
		}
	},
	computed:{
		mineUserInfo(){
			return JSON.parse(uni.getStorageSync('userInfo'));
		}
	},
	mounted() {
		uni.$TUIKit.on(uni.$TUIKitEvent.MESSAGE_RECEIVED, this.$onMessageReceived, this);
		uni.$TUIKit.on(uni.$TUIKitEvent.MESSAGE_READ_BY_PEER, this.$onMessageReadByPeer, this);
		this.$EventBus.$on('sendMessage', (message)=>{
			this.isSend=true;
			this.updateMessageList(message);
		})
	},
	destroyed() {
		// 一定要解除相关的事件绑定
		uni.$TUIKit.off(uni.$TUIKitEvent.MESSAGE_RECEIVED, this.$onMessageReceived);
	},
	methods: {
		/**
		 * 推荐下拉刷新、加载更多
		 */
		scrollPulling(e) {},
		scrollRestore() {this.scrollTriggered = true;},
		scrollAbort() {},
		scrollToBottom(){},
		scrollRefresh() {
			if (this.scrollRefreshing||this.isCompleted)
			{
				this.isSend=false;
				this.isCompleted=true;
				this.scrollTriggered=false;
				this.scrollRefreshing = false;
				return;
			}
			this.scrollRefreshing = true;
			this.getMessageList(this.conversation);
			setTimeout(() => {
				this.scrollTriggered = false;
				this.scrollRefreshing = false;
			}, 1000);
		},
		toDetail(id){
			console.log(id)
			uni.showLoading({})
			let user=JSON.parse(uni.getStorageSync('user'));
			this.$api.public.userDetail({getAlbum:true,completeUser:user,uponUserId:id}).then(res=>{
				if(res.data.frozen){
					uni.showToast({
						title:'该用户已被冻结',
						icon:'none'
					});
					return;
				}
				if(res.data.sex===user.sex){
					uni.showToast({
						title:'同性用户不能查看主页',
						icon:'none'
					})
				}
				else{
					uni.setStorageSync('otherInfo',JSON.stringify(res.data));
					uni.hideLoading();
					uni.navigateTo({
						url:`/pages/friends/user?id=${id}`
					})
				}
			})
			
		},
		getMessageList(conversation) {
			if (!this.isCompleted) {
				uni.$TUIKit
					.getMessageList({
						conversationID: conversation.conversationID,
						nextReqMessageID: this.nextReqMessageID,
						count: 15
					})
					.then(res => {
						const { messageList } = res.data; // 消息列表。
						console.log(res)
						this.nextReqMessageID = res.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
						this.isCompleted = res.data.isCompleted; // 表示是否已经拉完所有消息。
						this.messageList = [...messageList, ...this.messageList];
						this.$handleMessageRender(this.messageList, messageList);
					});
			}
		},

		// 自己的消息上屏
		updateMessageList(msg) {
			this.messageList.push(msg);
			this.scrollToButtom();
		},

		// 消息已读更新
		$onMessageReadByPeer() {
			this.messageList=this.messageList
		},
		scrollToButtom() {
			const query = uni.createSelectorQuery().in(this);
			let nodesRef = query.select('#message-scroll');
			nodesRef
				.boundingClientRect(res => {
					if(res){
						this.$nextTick(() => {
							//进入页面滚动到底部
							this.scrollTop = res.height;
							// this.endItem='view_id_' + parseInt(Math.random() * 1000000)
							// this.scrollTo=this.endItem;
							console.log('滑动到底部了')
						});
					}
					
				})
				.exec();
		},
		// 收到的消息
		$onMessageReceived(value) {
			this.isSend=true;
			if(this.messageList.indexOf(value.data[0])===-1){
				this.messageList.push(value.data[0]);
			}
			
			this.scrollToButtom();
		},

		// 历史消息渲染
		$handleMessageRender(messageList) {
			if (messageList.length > 0) {
				this.messageList=messageList;
				setTimeout(()=>{
					this.$nextTick(() => {
						//进入页面滚动到底部
						this.scrollTop = 99999;
						// this.endItem='view_id_' + parseInt(Math.random() * 1000000)
						// this.scrollTo=this.endItem;
						console.log('历史消息渲染滑动到底部了')
					});
				},500)
				
			}
		}
	}
};
</script>
<style>
@import './index.css';
</style>
