<template>
	<view class="page">

		<view class="page-header" :style="{ paddingTop: geStatusBarHeight()+ 8 + 'px'}">
		    <view class="text-center">消息</view>
			<uni-icons type="staff-filled" size="30" color="#ffffff" @click="$u.throttle(gotoContacts(), 2000)"></uni-icons>
		</view>

		<view class="wrapcon">

			<!-- 列表 -->
			<view v-if="grouplist.length==0 && loadStatus=='nomore'" class="nodata">暂无消息~</view>

			<view class="listcell">
				<u-swipe-action :options="options" v-for="(info, index) in grouplist" :key="index" @click="$u.throttle(actionClick(info,index), 2000)" >
						<view class="lcon"  @click="gotoGroup(info,index)">
							<view class="limg">
								<image class="img" :src="info.img" mode="aspectFill"></image>
							</view>
							<view class="lright">
								<view class="lrow">
									<view class="pname">{{info.name}}</view>
									<view class="ptime"> {{ changeTime(info.datetime)}}</view>
								</view>
								<view class="lrow">
									<view class="pnr">
										{{ info.type==0?info.content:(info.type==1?"图片":(info.type==2?"文件":(info.type==3?"语音":(info.type==4?"视频":(info.type==5||info.type==6?
										(info.chatType=='customerService'?(info.send&&info.send.type==3?'订单咨询':((info.send&&info.send.type==2?'课程咨询':'商品咨询'))):""):"")))))}}
									</view>
									<view class="lnum" v-if="info.sl>0">
										{{ info.sl}}
									</view>
								</view>
							</view>
						</view>
				</u-swipe-action>


			</view>

			<u-loadmore v-if="grouplist.length==0 && loadStatus=='loading'" :status="loadStatus" :marginTop="20"></u-loadmore>

		</view>

		<!-- 提示信息弹窗 -->
		<uni-popup ref="message" type="message">
			<uni-popup-message :type="msgType" :message="messageText" :duration="2000"></uni-popup-message>
		</uni-popup>

	</view>
</template>

<script>
	import { myCache } from '../../utils/utils.js';
	import dateTime from '@/common/dateTime.js';
	export default {
		data() {
			return {
				openId:"",
				phone:"",
				userid:"",
				userName:"",
				userheadimg:"",
				messageText:'', //错误提示框
				msgType :'error',
				loadStatus:'loadmore',
				options: [
				    {
				        text: '删除',
				        style: {
				            backgroundColor: '#ed2a28'
				        }
				    }
				], //u-swipe-action样式
				imgurl:uni.$http.baseUrl,
				grouplist:[],
				socketTask: null,
				isConnected: false, // WebSocket连接状态
				socketmsg:[],//接收信息
				heartbeatInterval: null, // 心跳包20秒连接一次
				heartbeatTimeout: 20000, // 心跳间隔时间，例如每20秒发送一次
			}
		},
		onLoad(options) {
			// socket接收信息初始化
			// this.socketinit();
		},
		onShow(){
			this.openId = myCache('openId');
			var user = myCache('user');
			this.userid = user.userid? user.userid:'';
			this.userName=user.nickName?user.nickName:"";
			this.userheadimg=user.avatar?user.avatar:require("@/static/image/girl.png");
			this.phone = user.userphone;
			// 如果心跳包在发送，先停止，再启动
			if(this.heartbeatInterval){
				clearInterval(this.heartbeatInterval); // 停止心跳包发送
			}
			// 从缓存聊天群里获取聊天群列表 chatlist
			this.loadData();
		},
		onPullDownRefresh() {
			console.log('onPullDownRefresh');
			setTimeout(()=>{
				uni.stopPullDownRefresh()
			},500);
		},
		onBackPress(options) {
			if (options.from === 'backbutton') {
		      // 来自顶部菜单的返回按钮
		      // 在这里处理你的逻辑
		      console.log('返回按钮被点击');
			  this.closeWebSocket();
		      uni.onSocketClose(function (res) {
		        console.log('WebSocket 已关闭！');
		      });
			  return false;
		    }
		},
		beforeDestroy() {
			console.log('界面关闭socket，beforeDestroy');
		    // 在组件销毁前，确保关闭 WebSocket 连接
			this.closeWebSocket();
			clearInterval(this.heartbeatInterval); // 停止心跳包发送
		},
		beforeRouteLeave(to, from, next) {
			console.log('界面关闭socket，beforeRouteLeave');
		    next();
		},
		methods: {
			// 删除
			actionClick(info,index) {
				console.log(info,index);
				var that=this;
				uni.showModal({
					title: '提示',
					content: "确定要删除此聊天记录吗？",
					cancelText: '取消',
					confirmText: '确定',
					success: ress => {
						if (ress.confirm) {
							myCache(info.id,"");
							that.grouplist.splice(index, 1);
							that.$forceUpdate();
							myCache("chatlist",that.grouplist);
						}
					}
				});
			},
			// 定时心跳包
			startHeartbeat() {
				console.log("startHeartbeat")
				this.heartbeatInterval = setInterval(() => {
				  if (this.socketTask) {
				    this.socketTask.send({
				      data: JSON.stringify({
						  'cmd': 1,//心跳
						  'data': {
							  'accessToken':uni.getStorageSync("token")
						  },
						  }) // 发送心跳包数据
				    });
				  }
				}, this.heartbeatTimeout);
			},
			// ws接收消息
			socketinit(){
				var that = this;
				// if (!that.isConnected) {

					that.socketTask=uni.connectSocket({
						url: "wss://www.sanduolantoyoga.com/yoga-imserver",
						header: {
							// 'content-type': 'application/json',
							Authorization: uni.getStorageSync("token"),
						},
						success: (res) => {
						  console.log(res, 'socket连接成功success');
						},
						fail: (res) => {
						  console.log(res, 'socket连接失败')
						},
						complete: (res) => {
							console.log(res,'socket连接成功complete');
						}
					});

					uni.onSocketOpen(resopen => {
						console.log('WebSocket连接已打开！');
						that.isConnected = true;
						that.$forceUpdate()
						uni.sendSocketMessage({
							data: JSON.stringify({
								"cmd": 0,//心跳
								"data": {
									"accessToken":uni.getStorageSync("token"),
								},
							}),  // 发送心跳包数据 // 发送的消息内容
							success(re) {
								console.log(re);
								console.log('消息发送成功！')
							},
							fail(err) {
								console.log(err);
								console.log('消息发送失败！')
							}
						});

						// 发送心跳包
						this.startHeartbeat();
					});

					uni.onSocketMessage(res => {
						console.log('收到WebSocket服务器消息：');
						if(res.data){
							var rs=JSON.parse(res.data);
							console.log(rs);
							if(rs.data){
								var data=rs.data;
								if(data){
									if(data.recvId==that.userid){
										// 是这个用户的接收的信息
										// 加入聊天记录
										// 消息类型 0:文字 1:图片 2:文件 3:语音 4:视频 10, "撤回" 11, "已读 "12, "消息已读回执 " 30,"加载中标记"
										if(data.type==0){
											data.content=decodeURIComponent(data.content);
										}
										// else if(data.type==1){
										// 	data.content="图片";
										// }
										// else if(data.type==2){
										// 	data.content="文件";
										// }
										// else if(data.type==3){
										// 	data.content="语音";
										// }
										// else if(data.type==4){
										// 	data.content="视频";
										// }
										else if(data.type==5){
											data.content="订单";
										}
										else if(data.type==6){
											data.content="商品";
										}
										if(data.type==0||data.type==1||data.type==2||data.type==3||data.type==4||data.type==5||data.type==6){
											var ifexist=0;
											that.grouplist.forEach((cell,index)=>{
												if(cell.fromuser==data.sendId&&cell.userid==data.recvId){
													ifexist=1;
													that.grouplist[index].sl=(that.grouplist[index].sl?that.grouplist[index].sl+1:1);
													that.grouplist[index].content=data.content;
													that.grouplist[index].datetime=data.sendTime;
													that.grouplist[index].type=data.type;
													that.$forceUpdate();
												}
											});

											if(ifexist==0){
												// 未保存缓存
												// 接收到socket后更新聊天列表记录
												var chatlastinfo={
													id: "privatechat-" + data.recvId +"-" + data.sendId,
													content: data.content,
													minId: data.id,
													sl:1,
													datetime: data.sendTime,
													chatType: "",
													type: data.type,
													name: "",
													userid: data.recvId,
													fromuser: data.sendId,
													img: "",
													sort:"privatechat"
												};
												that.updateChatList(chatlastinfo,ifexist);
											}
											else{
												that.updateChatList(that.grouplist[that.grouplist.length-1],ifexist);
											}
										}
										else{
											// 10, "撤回" 11, "已读 " 12, "消息已读回执 " 30,"加载中标记"
										}
									}
								}
							}
						}
					});

					uni.onSocketClose(res => {
						console.log('WebSocket连接已关闭！',res);
						that.isConnected = false;
						that.$forceUpdate();
						clearInterval(that.heartbeatInterval); // 停止心跳包发送
					});

					uni.onSocketError(err => {
						console.error('WebSocket连接打开失败，请检查：', err);
						that.isConnected = false;
						that.$forceUpdate();
						clearInterval(that.heartbeatInterval); // 停止心跳包发送
					});
				// }
			},
			// 关闭WebSocket连接
			closeWebSocket() {
				uni.closeSocket();
				this.isConnected = false;
				this.$forceUpdate()
			},

			gotoContacts(){
				uni.navigateTo({
					url: `/pages/message/contact`
				});
			},
			changeTime(date) {
				return dateTime.dateTime(date);
			},
			gotoGroup(chat,index){
				console.log("gotoGroup",chat);
				// 当前消息未读数据消除
				this.grouplist[index]["sl"]=0;
				this.$forceUpdate();
				myCache("chatlist",this.grouplist);
				// 去聊天室
				if(chat.sort=="privatechat"){
					// 私聊
					var info={
						chatId: chat.id,
						chatType: chat.chatType,
						chatName: chat.name,
						chatAvatar: chat.img,
						chatTime: chat.datetime,
						friendId: chat.fromuser,
						minId: chat.minId,
						sort:"privatechat",
						from:"message" // yh 用户咨询进入聊天框，message 从消息进入聊天框
					}
					var data=encodeURIComponent(JSON.stringify(info));
					uni.navigateTo({
						url: `/pages/chat/chat?data=${data}`
					});
				}
				else if(chat.type=="groupchat"){
					// 群聊
					var data=encodeURIComponent(JSON.stringify(info));
					uni.navigateTo({
						url: `/pages/chat/groupchat?data=${data}`
					});
				}
			},
			loadData(){
				// 信息列表加载
				this.loadStatus="loading";
				setTimeout(() => {
					this.getgroupsmembers();
				}, 300);
			},
			// 获取群聊列表
			async getgroupsmembers(){
				// 获取聊天群列表
				this.grouplist=[];
				var chatlist=myCache("chatlist")?myCache("chatlist"):[];
				chatlist.forEach(cell=>{
					if(cell.userid==this.userid){
						this.grouplist.push(cell);
					}
				});
				this.grouplist.forEach((cell,i)=>{
					if(cell.minId){
						// 通过某个会话中已读消息的最大id 获取离线消息
						 this.readUp(i,cell.minId,cell.fromuser);
					}
				});
				this.loadStatus="nomore";
				this.$forceUpdate();
				var that=this;
				setTimeout(() => {
					that.reorder();
					myCache("chatlist",that.grouplist);
				}, 300);

				// socket接收实时消息
				this.socketinit();
			},
			// 重新排序
			reorder(){
				this.grouplist.sort((a, b) => b.datetime - a.datetime);
				this.$forceUpdate();
			},
			// 已读推送
			async readUp(i,id,fromuser) {
				const {data: res} = await uni.$http.put('/api/message/private/readed?friendId='+fromuser);
				this.getgroupsnums(i,id);
			},
			// 获取群聊中离线信息
			async getgroupsnums(i,id){
				const {data: res} = await uni.$http.get("/api/message/private/pullOfflineMessage",{minId:id});
				if(res.data&&res.data.length>0){
					// 获取消息后对消息进行缓存处理
					var data=res.data;
					// 获取离线消息数量返回
					this.grouplist[i]["sl"]=res.data.length;
					var last=res.data[res.data.length-1];
					if(last.type==0){
						last.content=decodeURIComponent(last.content);
					}
					else if(last.type==1){
						last.content="图片";
					}
					else if(last.type==2){
						last.content="文件";
					}
					else if(last.type==3){
						last.content="语音";
					}
					else if(last.type==4){
						last.content="视频";
					}
					else if(last.type==5){
						last.content="订单";
					}
					else if(last.type==6){
						last.content="商品";
					}
					if(last.type==0||last.type==1||last.type==2||last.type==3||last.type==4||data.type==5||data.type==6){
						this.grouplist[i].content=last.content;
						this.grouplist[i].type=last.type;
						this.grouplist[i].datetime=last.datetime;
						this.$forceUpdate();
						// 重新排序
						this.reorder();
						myCache("chatlist",this.grouplist);
					}
				}
			},
			async updateChatList(info,ifexist){
				const {data: res} = await uni.$http.get("/api/friend/find/"+info.fromuser);
				if(res.data){
					var data=res.data;
					info.name=data.nickName?data.nickName:"匿名";
					info.img=data.headImage?data.headImage:require("@/static/image/girl.png");
					if(ifexist==0){
						this.grouplist.push(info);
						this.$forceUpdate();
					}
					// 重新排序 保存缓存
					this.reorder();
					myCache("chatlist",this.grouplist);
					// 聊天框消息缓存
					var msgchat=myCache(info.id);
					if(ifexist==0||!msgchat){
						// 第一条聊天记录保存缓存
						let firstmsg = [{
							"fromname": info.name, // 发送人
							"fromuser": info.fromuser, // 发送人
							"headimg": info.img, // 发送人
							"toname": this.userName, // 接收人
							"touser": this.userid, // 接收人姓名
							"content": info.content,
							"time": info.type==3?5:0,
							"ifaudio":info.type==3? true:false,
							"fromtime": info.datetime,
							"type": info.type==0?'txt':(info.type==1?'image':info.type==3?'audio':(info.type==4?'video':'product')),
							"id": info.id,
							"minId": info.minId,
							"recvId": info.recvId,
							"sendId": info.sendId
						}];
						myCache(info.id,firstmsg);
					}
					else{
						// 聊天框信息 保存缓存
						let firstmsg = {
							"fromname": info.name, // 发送人
							"fromuser": info.fromuser, // 发送人
							"headimg": info.img, // 发送人
							"toname": this.userName, // 接收人
							"touser": this.userid, // 接收人姓名
							"content": info.content,
							"time": info.type==3?5:0,
							"ifaudio":info.type==3? true:false,
							"fromtime": info.datetime,
							"type": info.type==0?'txt':(info.type==1?'image':info.type==3?'audio':(info.type==4?'video':'product')),
							"id": info.id,
							"minId": info.minId,
							"recvId": info.recvId,
							"sendId": info.sendId
						};
						msgchat.push(firstmsg);
						myCache(info.id,msgchat);
					}
				}
				else{
					info.name="匿名";
					info.img="../../static/image/girl.png";
					if(ifexist==0){
						this.grouplist.push(info);
						this.$forceUpdate();
					}
					// 重新排序
					this.reorder();
					myCache("chatlist",this.grouplist);
					var msgchat=myCache(info.id);
					if(ifexist==0||!msgchat){
						// 第一条聊天记录保存缓存
						let firstmsg = [{
							"fromname": info.name, // 发送人
							"fromuser": info.fromuser, // 发送人
							"headimg": info.img, // 发送人
							"toname": this.userName, // 接收人
							"touser": this.userid, // 接收人姓名
							"content": info.content,
							"time": info.type==3?5:0,
							"ifaudio":info.type==3? true:false,
							"fromtime": info.datetime,
							"type": info.type==0?'txt':(info.type==1?'image':info.type==3?'audio':(info.type==4?'video':'product')),
							"id": info.id,
							"minId": info.minId,
							"recvId": info.recvId,
							"sendId": info.sendId
						}];
						myCache(info.id,firstmsg);
					}
					else{
						// 聊天框信息 保存缓存
						let firstmsg = {
							"fromname": info.name, // 发送人
							"fromuser": info.fromuser, // 发送人
							"headimg": info.img, // 发送人
							"toname": this.userName, // 接收人
							"touser": this.userid, // 接收人姓名
							"content": info.content,
							"time": info.type==3?5:0,
							"ifaudio":info.type==3? true:false,
							"fromtime": info.datetime,
							"type": info.type==0?'txt':(info.type==1?'image':info.type==3?'audio':(info.type==4?'video':'product')),
							"id": info.id,
							"minId": info.minId,
							"recvId": info.recvId,
							"sendId": info.sendId
						};
						msgchat.push(firstmsg);
						myCache(info.id,msgchat);
					}
				}
			},
			// 获取状态栏高度
			geStatusBarHeight(){
			    return uni.getSystemInfoSync()['statusBarHeight'];
			},
			// 获取导航栏高度
			getNavBarHeight(){
				return 45+uni.getSystemInfoSync()['statusBarHeight'];
			},

		}
	}
</script>

<style lang="scss" scoped>
	.page{
		padding: 0;
		position: relative;
		background-image: url('@/static/image/bg.jpg');
		background-attachment: fixed;
		background-size: cover;
		background-position: center center;
		min-height: calc(100vh - var(--window-top) - var(--window-bottom));
	}
	.page-header {
		position: fixed;
		width: 100%;
		z-index: 999;
	    padding: 40rpx 30rpx 30rpx 30rpx;
	    display: flex;
	    color: #fff;
	    font-size: 36rpx;
	    background-color: #00a89b;
	    .text-center {
	        width: 100%;
	        text-align: center;
	    }
	    .edit {
	        position: absolute;
	        top: 50%;
	        transform: translateY(-50%);
	        right: 30rpx;
	        font-size: 32rpx;
	    }
	}
	.wrapcon{
		padding: 0;
		width: 100%;
		position: relative;
		margin: 180rpx 0 0 0;
		min-height: calc(100vh - 180rpx);
		/* #ifdef H5 */
		margin: calc( 110rpx + var(--window-top)) 0 0 0;
		min-height: calc(100vh - var(--window-top) - var(--window-bottom) - 180rpx);
		/* #endif */
		overflow-y: auto;
	}
	.listcell{
		background: #fff;
		margin: 0;
		width: 100%;
		.lcon{
			border-bottom: 1rpx solid #eee;
			padding-top: 20rpx;
			padding-bottom: 20rpx;
			opacity: 1;
			display: flex;
			flex-direction: row;
			align-items: center;
			width: 100%;
			.limg{
				width: 100rpx;
				height: 100rpx;
				margin-right: 20rpx;
				margin-left: 20rpx;
				display: flex;
				flex-direction: row;
				flex-wrap: wrap;
				align-items: center;
				justify-content: center;
				border-radius: 50%;
				.img{
					width: 100rpx;
					height: 100rpx;
				}
			}
			.lright{
				display: flex;
				flex: 1;
				flex-direction: column;
			}
			.lrow{
				display: flex;
				flex-direction: row;
				margin-bottom: 20rpx;
				margin-right: 20rpx;
			}
			.pname{
				display: flex;
				flex: 1;
				line-height: 50rpx;
				font-size: 32rpx;
				font-family: PingFang SC, PingFang SC;
				font-weight: 600;
				color: #000000;
			}
			.ptime{
				line-height: 50rpx;
				font-size: 24rpx;
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				color: #595959;
			}
			.pnr{
				display: flex;
				flex: 1;
				font-size: 24rpx;
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				color: #595959;
			}
			.lnum{
				background-color: #de0000;
				padding: 0 10rpx;
				min-width: 32rpx;
				height: 32rpx;
				line-height: 32rpx;
				color: #fff;
				font-size: 24rpx;
				border-radius: 28rpx;
			}
		}
	}
	.tips{
		margin-top: 20rpx;
		margin-bottom: 20rpx;
		width: 100%;
		line-height: 44rpx;
		font-size: 26rpx;
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		color: #595959;
		text-align: center;
	}
	.submitcon{
		margin-top: 200rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.bbtn{
		margin: 20rpx 30rpx 54rpx;
		font-size: 32rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
		color: #FCFCFD;
		width: 560rpx;
		height: 96rpx;
		line-height: 96rpx;
		background: #367FFA;
		box-shadow: 0rpx 12rpx 64rpx 2rpx rgba(67,110,255,0.4);
		border-radius: 254rpx 254rpx 254rpx 254rpx;
		opacity: 1;
		&::after{
			border:none;
		}
	}
	.nodata{
		background-image: url('../../static/image/nomsg.png');
		background-repeat: no-repeat;
		background-position: center center;
		background-size: 100%;
		height: 376rpx;
		width: 256rpx;
		color: #00a89b;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		flex-direction: column;
		padding-bottom: 40rpx;
		margin: 100rpx auto;
	}
</style>
