<template>
	<view class="container">
		<TabBar :tabIndex="tabIndex"></TabBar>
		<uni-popup ref="popup" type="center">
			<Popup :content1="popup.content1" :content2="popup.content2" :tip1="popup.tip1" :tip2="popup.tip2" :btntext="popup.btntext" @closePopup="closePopup"  @toService="toService" :btnEvent="'toService'"></Popup>
		</uni-popup>
		<uni-popup ref="paypopup" type="bottom" :safe-area="false">
			<PayPopup :swiperIndex="payPopupIndex" @closePopup="closePayPopup"></PayPopup>
		</uni-popup>
		<uni-popup ref="vippopup" type="center">
			<VipPopup :swiperIndex="vipPopupIndex" @closePopup="closeVipPopup"></VipPopup>
		</uni-popup>
		<view id="topnav" class="topnav flex-start" :style="{'height':`${topbarOffsetHeight-statusBarHeight}px`,'padding-top':`${statusBarHeight}px`}" >
			<view class="nav-item font44 fw600">
				消息
			</view>
			<image :src="`${assetsUrl}message-setting.png`" mode="aspectFill" class="nav-img" @click="openSetting"></image>
		</view>
		<scroll-view class="scroll-view"
			v-if="scrollHeight>0"
			scroll-y="true" 
			lower-threshold="200"
			:style="{'height':`${scrollHeight}px`,'padding-top':`${topbarOffsetHeight}px`}" 
			>
				<!-- <view class="message-item flex-between">
					<image :src="`${assetsUrl}message-system.png`" mode="aspectFill" class="left-img"></image>
					<view class="right-info">
						<view class="ri-top flex-between">
							<view class="rit-title fw600 font32">
								系统通知
							</view>
							<view class="rit-time font22 fw400">
								2022-8-31 09:57:13
							</view>
						</view>
						<view class="ri-bottom flex-between">
							<view class="rib-text font28 fw400">
								heihei
							</view>
							<view class="rib-num font20 fw400">
								99
							</view>
						</view>
					</view>
				</view> -->
				<view class="message-item flex-between" v-for="(item,index) in messagesList" :key="index"  :data-index="index" @touchstart="touchStart" @touchend="touchEnd">
					<image :src="item.userProfile.avatar" mode="aspectFill" class="left-img" :style="{'width':`${showDelIndex===index?'0rpx':'120rpx'}`}" @click="toTalk(item.userProfile.userID)"></image>
					<view class="right-info" @click="toTalk(item.userProfile.userID)">
						<view class="ri-top flex-between">
							<view class="rit-title fw600 font32">
								{{item.userProfile.nick}}
							</view>
							<view class="rit-time font22 fw400">
								{{item.lastMessage.lastTimeStr}}
							</view>
						</view>
						<view class="ri-bottom flex-between">
							<view class="rib-text font28 fw400">
								{{item.lastMessage.payload.text}}
							</view>
							<view class="rib-num font20 fw400" v-if="item.unreadCount!==0">
								{{item.unreadCount}}
							</view>
						</view>
					</view>
					<view class="del-box font28 fw400" :style="{'width':`${showDelIndex===index?'120rpx':'0rpx'}`}" @click="delConversation">
						删除
					</view>
				</view>
			<!-- <view class="no-more font24 fw400" v-if="messagesList.length!==0&&messagesList.length>=recommendTotal">没有更多了</view> -->
			<Status type="noMsg" text="暂无消息" v-if="showNoMsg"></Status>
		</scroll-view>
	</view>
</template>

<script>
	import TabBar from '@/components/TabBar/TabBar.vue';
	import Popup from '@/components/Popup/Popup.vue';
	import VipPopup from '@/components/Popup/VipPopup.vue';
	import PayPopup from '@/components/Popup/PayPopup.vue';
	import Status from '@/components/Status/Status.vue';
	/**
	 * 腾讯位置服务，手机账号：18996226740
	 */
	import wxMap from '@/static/qqmap-wx-jssdk1.2/qqmap-wx-jssdk.min.js';
	const wxMapSdk=new wxMap({key:'E5SBZ-T2YC3-CBL3F-YGFQQ-26PP2-ERFII'})
	export default {
		components:{TabBar,Popup,VipPopup,PayPopup,Status},
		data() {
			return {
				scrollHeight:0,
				topNavAlpha:0,
				assetsUrl:this.$util.assetsUrl,
				startTime:0,
				startPosition:0,
				endPosition:0,
				showDelIndex:-1,
				tabIndex:1,
				messagesList:[],
				popup:{
					content1:'',
					content2:'',
					tip1:'',
					tip2:'',
					btntext:''
				},
				payPopupIndex:-1,
				vipPopupIndex:-1,
				userInfo:null,//会话消息用户信息
				showNoMsg:false,
				systemMsg:{},
				
			};
		},
		computed: {
			statusBarHeight() {
				return this.$store.state.statusBarHeight;
			},
			topbarOffsetHeight() {
				return this.$store.state.topbarOffsetHeight;
			},
			platform(){
				return this.$store.state.platform;
			},
			mineInfo(){
				return this.$store.state.userInfo
			}
		},
		onLoad() {
			this.computedScollviewHeight();
			if(!uni.getStorageSync('token')){
				this.showNoMsg=true;
				return;
			}
			uni.$TUIKit.on(uni.$TUIKitEvent.CONVERSATION_LIST_UPDATED, this.onConversationListUpdated);
			
		},
		onShow() {
			if(!uni.getStorageSync('token')){
				return;
			}
			this.getSystemMessages();
			this.getUserMessages();
		},
		onShareAppMessage(){
			return {
				title: '糖果公园',
				path: `/pages/login/login?share=${this.userInfo.inviteCode}`,
			}
		},
		methods:{
			/**
			 * 计算scroll高度
			 */
			computedScollviewHeight() {
				let query = uni.createSelectorQuery().in(this);
				let heightLeaf = this.$store.state.tabbarHeight/2;
				query.select('#topnav').boundingClientRect(data => {
					heightLeaf += data.height;
				}).exec(() => {
					let sysInfo = uni.getSystemInfoSync();
					this.scrollHeight = sysInfo.windowHeight - heightLeaf;
				});
			},
			toLogin(){
				uni.reLaunch({
					url:'/pages/login/login'
				})
			},
			closePopup(){
				this.$refs.popup.close();
				
			},
			closePayPopup(){
				this.payPopupIndex=-1;
				this.$refs.paypopup.close();
			},
			closeVipPopup(){
				this.vipPopupIndex=-1;
				this.$refs.vippopup.close();
			},
			touchStart(e){
				this.startTime = Date.now()
				this.startPosition = e.changedTouches[0].clientX;
			},
			touchEnd(e){
				const endTime = Date.now()
				if (endTime - this.startTime <100){
					return;
				}
				if (Math.abs(this.endPosition - this.startPosition) > 100){
					this.endPosition = e.changedTouches[0].clientX;
					let elePosition = this.endPosition - this.startPosition < 0 ? "toLeft": "toRight";
					console.log(elePosition)
					if(elePosition==='toLeft'){
						this.showDelIndex=e.currentTarget.dataset.index;
					}
					else{
						this.showDelIndex=-1;
					}
				} else {
					return;
				}
			},
			onConversationListUpdated(event){
				if(event.data.length===0){
					this.messagesList=[];
					this.showNoMsg=true;
					return;
				}
				else{
					this.getUserMessages();
				}
				
			},
			delConversation(){
				uni.$TUIKit.deleteConversation(this.messagesList[this.showDelIndex].conversationID);
				this.showDelIndex=-1;
			},
			openSetting(){
				if(!uni.getStorageSync('token')){
					this.popup={
						content1:'您还未登录',
						content2:'该功能登录后才能使用',
						tip1:'',
						tip2:'',
						btntext:'去登录'
					}
					this.$refs.popup.open();
					return;
				}
				uni.showActionSheet({
					itemList: ['全部已读', '清空消息'],
					success: (res)=>{
						if(res.tapIndex===0){
							uni.$TUIKit.setAllMessageRead({scope:uni.$TUIKitTypes.READ_ALL_MSG});
						}
						if(res.tapIndex===1){
							uni.showModal({
								title:'清空消息列表',
								content:'清空消息列表后，暂无恢复，请确认是否清空消息列表',
								success: (ress) => {
									if(ress.confirm){
										this.messagesList.forEach(item=>{
											uni.$TUIKit.deleteConversation(item.conversationID);
										})
									}
								}
							})
						}
					},
					fail: res=>{
						console.log(res.errMsg);
					}
				});
			},
			getSystemMessages(){
				let user=JSON.parse(uni.getStorageSync('user'));
				this.$api.public.notifyActive({}).then(res=>{
					this.$api.public.loadSystemMsgs({
						completeUser:user,
						onlineRecent:false,
						page:{
							index:1,
							size:20,
							sortValue:null
						}
					}).then(result=>{
						
					})
				})
			},
			getUserMessages(){
				uni.$TUIKit.getConversationList().then(res=>{
					console.log(res.data.conversationList)
					for(let i=0;i<res.data.conversationList.length;i++){
						res.data.conversationList[i].lastMessage.lastTimeStr=this.$moment(res.data.conversationList[i].lastMessage.lastTime*1000).format('YYYY-MM-DD hh:mm:ss');
						if(res.data.conversationList[i].lastMessage.type==='TIMImageElem'){
							res.data.conversationList[i].lastMessage.payload.text="[图片消息]"
						}
						if(res.data.conversationList[i].lastMessage.type==='TIMVideoFileElem'){
							res.data.conversationList[i].lastMessage.payload.text="[视频消息]"
						}
						if(res.data.conversationList[i].lastMessage.type==='TIMSoundElem'){
							res.data.conversationList[i].lastMessage.payload.text="[音频消息]"
						}
						if(res.data.conversationList[i].lastMessage.type==='TIMCustomElem'){
							let msg=JSON.parse(res.data.conversationList[i].lastMessage.payload.data);
							if(msg.type===99)
							{
								res.data.conversationList[i].lastMessage.payload.text="[系统消息]"
							}
							if(msg.type===5)
							{
								res.data.conversationList[i].lastMessage.payload.text="[图片消息]"
							}
							if(msg.type===6){
								res.data.conversationList[i].lastMessage.payload.text="[视频消息]"
							}
							if(msg.type===100){
								res.data.conversationList.splice(i,1);
								i--;
								// res.data.conversationList[i].userProfile.nick='社区动态';
								// res.data.conversationList[i].userProfile.avatar=`${this.assetsUrl}message-active.png`
								// res.data.conversationList[i].lastMessage.payload.text="[有人喜欢你]"
							}
						}
					}
					this.messagesList=res.data.conversationList;
					if(this.messagesList.length===0){
						this.showNoMsg=true;
					}
					else{
						this.showNoMsg=false;
					}
				})
			},
			toTalk(id){
				uni.showLoading({
					mask:true,
					title:'加载中'
				})
				let user=JSON.parse(uni.getStorageSync('user'));
				this.$api.public.userDetail({getAlbum:true,completeUser:user,uponUserId:id}).then(res=>{
					console.log(res);
					this.userInfo=res.data;
					let arr=[],obj={latitude:0,longitude:0};
					obj.latitude=this.userInfo.geo.lat;
					obj.longitude=this.userInfo.geo.lon;
					arr.push(obj);
					wxMapSdk.calculateDistance({
						mode:'straight',
						from:{
							latitude: this.$store.state.latitude,
							longitude: this.$store.state.longitude
						},
						to:arr,
						success:dists=>{
							uni.hideLoading();
							if(dists.message==="query ok"){
								console.log(dists,this.mineInfo)
								for(let j=0;j<dists.result.elements.length;j++){
									this.userInfo.distance=(dists.result.elements[j].distance>1000?`${Math.floor(dists.result.elements[j].distance/100)/10}km`:`${dists.result.elements[j].distance}m`)
								}
								if(this.mineInfo.sex==='Male'&&!this.mineInfo.vip){
									if(this.platform==='ios'){
										this.vipPopupIndex=0;
										this.$refs.vippopup.open();
										return;
									}
									else{
										this.payPopupIndex=0;
										this.$refs.paypopup.open();
										return;
									}
									
								}
								if(this.mineInfo.sex==='Famale'&&!this.mineInfo.realMan){
									this.popup={
										content1:'认证后才能开启私聊哦',
										content2:'给客服回复关键词「真人认证」',
										tip1:'',
										tip2:'',
										btntext:'联系客服去认证'
									}
									this.$refs.popup.open();
									return;
								}
								uni.navigateTo({
									url:`/pagesSub/chatting/chatting?conversationid=C2C${id}`
								})
							}
							else{
								uni.showToast({
									title:'计算距离失败',
									icon:'none'
								});
								uni.navigateTo({
									url:`/pagesSub/chatting/chatting?conversationid=C2C${id}`
								})
							}
							
						},
						fail:err=>{
							console.log(err)
						}
					})
					
					
				})
				
			},
		}
	}
</script>

<style lang="scss" scoped>
.container{
	width: 100vw;
	height: 100vh;
	background-color: $bgcolor1;
	position: relative;
	.topnav {
		padding: 0 10rpx;
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		z-index: 100;
		backdrop-filter: blur(10px);
		.nav-item {
			height: 56rpx;
			margin-left: 16rpx;
			color: #ffffff;
			
		}
		.nav-img{
			width: 44rpx;
			height: 44rpx;
			margin: 4rpx 0rpx 0rpx 13rpx;
		}
	}
	.scroll-view{
		.message-item{
			width: 100vw;
			box-sizing: border-box;
			padding: 24rpx 28rpx;
			.left-img{
				width: 120rpx;
				height: 120rpx;
				margin-right: 24rpx;
				border-radius: 44rpx;
				transition: all 0.3s;
			}
			.right-info{
				flex: 1;
				height: 120rpx;
				transition: all 0.3s;
				.ri-top{
					margin-top: 8rpx;
					.rit-title{
						color: $fontcolor5;
					}
					.rit-time{
						color: $fontcolor2;
					}
				}
				.ri-bottom{
					margin-top: 20rpx;
					.rib-text{
						color: $fontcolor3;
					}
					.rib-num{
						width:36rpx;
						height: 36rpx;
						border-radius: 36rpx;
						background-color: #FE3B49;
						color: #ffffff;
						line-height: 36rpx;
						text-align: center;
					}
				}
			}
			.del-box{
				background-color: #FE3B49;
				color: #ffffff;
				height: 120rpx;
				transition: all 0.3s;
				overflow: hidden;
				line-height: 120rpx;
				text-align: center;
				margin-left: 16rpx;
			}
		}
	}
}
</style>
