<script>
	// 引入检查更新
	//import checkupdate from "@/uni_modules/uni-upgrade-center-app/utils/check-update.js"
	//引进检查版本
	// import callCheckVersion from '@/uni_modules/uni-upgrade-center-app/utils/call-check-version';
	
	import { myCache } from '@/utils/utils.js';
	
	//#ifdef APP-PLUS
    const jpushModule = uni.requireNativePlugin('JG-JPush');
	//#endif
	
	export default {
		data() {
			return {
				userid:"",
				userName:"",
				userheadimg:"",
			}
		},
		onLaunch() {
			// 判断版本更新 需要真机进行测试
			//checkupdate();
			
			//#ifdef APP-PLUS
			// 消息推送
			// jpushModule.setLoggerEnable(true);
			// jpushModule.initJPushService()
			// jpushModule.addConnectEventListener(result=>{
			// 	let connectEnable = result.connectEnable
			// 	console.log("jpush连接", connectEnable)
			// });
			
			// 设置别名 （再登录时候设置）
			// var user= JSON.parse(uni.getStorageSync("user"));
			// if(user&&user.yhdm){
			// 	jpushModule.setAlias({
			// 		'alias': user.yhdm,
			// 		'sequence': 1
			// 	})
			// }
			
			// jpushModule.addTagAliasListener(result => {
			// 	let code = result.code
			// 	let sequence = result.sequence
			// 	let tags = result.tags
			// 	let tag = result.tag
			// 	let tagEnable = result.tagEnable
			// 	let alias = result.alias
			// 	console.log(alias, '别名')
			// });
			
			// // 通知事件回调
			// jpushModule.addNotificationListener(result => {
			// 	let notificationEventType = result.notificationEventType
			// 	let messageID = result.messageID
			// 	let title = result.title
			// 	let content = result.content
			// 	let extras = result.extras
			// 	console.log("通知", result)
			// 	// 点击事件
			// 	if (notificationEventType == 'notificationOpened') {
			// 		uni.reLaunch({
			// 			url: `/pages/message/newMsg`
			// 		});
			// 	}
			// })
			// jpushModule.getRegistrationID(result => {
			// 	console.log("注册ID", result.registerID)
			// 	if (result.registerID) {
			// 		uni.setStorageSync("register_id", result.registerID)
			// 	}
			// })
			// jpushModule.addCustomMessageListener(result => {
			// 	let messageID = result.messageID
			// 	let content = result.content
			// 	let extras = result.extras
			// 	console.log("自定义消息", result)
			// })
			//#endif
			
			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");
			
			// 接收信息
			if(uni.getStorageSync("token")&&this.userid){
				this.startHeartbeat();
			}
		},
		methods: {
			// 定时心跳包
			startHeartbeat() {
				console.log("startHeartbeat");
				var that=this;
				this.heartbeatInterval = setInterval(() => {
					if(this.isConnected){
						// 如果已经连接ws
						uni.sendSocketMessage({
							data: JSON.stringify({
							  	'cmd': 1,//心跳
							  	'data': {
							  		'accessToken':uni.getStorageSync("token")
							  	},
							}), // 发送心跳包数据,
							success(re) {
								console.log(re);
								console.log('消息发送成功！')
							},
							fail(err) {
								console.log(err);
								console.log('消息发送失败！');
								that.reconnect();
							}
						});
					}
					else{
						// 重新连接
						that.reconnect();
					}
				}, this.heartbeatTimeout); // 20秒执行一次
			},
			// 开始重连
			reconnect () {
			    if (!this.isConnected) {
			        clearTimeout(this.heartbeatInterval);
					this.heartbeatInterval = setTimeout(() => {
					    console.log('开始重连...');
					    this.socketinit();
					},this.heartbeatTimeout);
			    }
			},
			// ws接收消息
			socketinit(){
				var that = this;
				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连接已打开！');
					this.isConnected = true;
					this.$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.onSocketClose(res => {
					console.log('WebSocket连接已关闭！',res);
					this.isConnected = false;
					this.$forceUpdate();
					// 重新连接socket
					this.reconnect();
				});
				// 连接失败后重新连接
				uni.onSocketError(err => {
					console.error('WebSocket连接打开失败，请检查：', err);
					this.isConnected = false;
					this.$forceUpdate();
					// 重新连接socket
					this.reconnect();
				});
				
				// 接收信息
				uni.onSocketMessage(res => {
					console.log('收到WebSocket服务器消息：');
					if(res.data){
						var rs=JSON.parse(res.data);
						console.log("onSocketMessage",rs);
						if(rs.cmd==3){
							// 私聊
							if(rs.data){
								var data=rs.data;
								if(data.recvId&&(data.recvId).toString()==(this.userid).toString()){
									// 是这个用户的接收的私聊信息
									// 加入聊天记录
									// 消息类型 0:文字 1:图片 2:文件 3:语音 4:视频 10, "撤回" 11, "已读 "12, "消息已读回执 " 30,"加载中标记"
									if(data.type==0||data.type==1||data.type==2||data.type==3||data.type==4||data.type==5||data.type==6){
										if(data.type==0){
											data.content=decodeURIComponent(data.content); 
										}
										var id="privatechat-" + data.recvId +"-" + data.sendId;
										var index=this.ifadd(id);
										var chatinfo=null;
										var grouplist=myCache("chatlist-"+this.userid)?myCache("chatlist-"+this.userid):[];
										if(index>-1){
											grouplist[index].sl=(grouplist[index].sl?grouplist[index].sl+1:1);
											grouplist[index].content=data.content;
											grouplist[index].datetime=data.sendTime;
											grouplist[index].type=data.type;
											grouplist[index].minId=data.id;
											grouplist[index].ifload=1;
											that.$forceUpdate();
											chatinfo= JSON.parse(JSON.stringify(grouplist[index]));
										}
										else{
											// 未保存缓存
											// 接收到socket后更新聊天列表记录
											chatinfo={
												id: id,
												content: data.content,
												minId: data.id,
												sl:1,
												datetime: data.sendTime,
												type: data.type,
												name: "",
												userid: data.recvId,
												fromuser: data.sendId,
												img: "",
												sort:"privatechat",
												ifload:0
											};
											grouplist.push(chatinfo);
											this.$forceUpdate();
										}
										myCache("chatlist-"+this.userid,grouplist);
										this.getPrivateInfo(chatinfo);
									}
									else{
										// 10, "撤回" 11, "已读 " 12, "消息已读回执 " 30,"加载中标记"
									}
								}
							}
						}
						else if(rs.cmd==4){
							// 群聊
							if(rs.data){
								var data=rs.data;
								if(data.atUserIds&&data.atUserIds.includes(this.userid)){
									// 是这个用户的接收的群聊信息
									// 加入聊天记录
									// 消息类型 0:文字 1:图片 2:文件 3:语音 4:视频 10, "撤回" 11, "已读 "12, "消息已读回执 " 30,"加载中标记"
									if(data.type==0||data.type==1||data.type==2||data.type==3||data.type==4||data.type==5||data.type==6){
										
										if(data.type==0){
											data.content=decodeURIComponent(data.content); 
										}
										
										var id="groupchat-" + data.groupId;
										var index=this.ifadd(id);
										var chatinfo=null;
										var grouplist=myCache("chatlist-"+this.userid)?myCache("chatlist-"+this.userid):[];
										if(index>-1){
											grouplist[index].sl=(grouplist[index].sl?grouplist[index].sl+1:1);
											grouplist[index].content=data.content;
											grouplist[index].datetime=data.sendTime;
											grouplist[index].fromuser=data.sendId;
											grouplist[index].type=data.type;
											grouplist[index].minId=data.id;
											grouplist[index].ifload=1;
											that.$forceUpdate();
											chatinfo= JSON.parse(JSON.stringify(grouplist[index]));
										}
										else{
											// 未保存缓存
											// 接收到socket后更新聊天列表记录
											chatinfo={
												id: id,
												groupId: data.groupId,
												content: data.content,
												minId: data.id,
												sl:1,
												datetime: data.sendTime,
												type: data.type,
												name: "",
												userid: this.userid,
												fromuser: data.sendId,
												img: "",
												sendId: data.sendId,
												sendNickName: data.sendNickName,
												sort:"groupchat",
												ifload:0
											};
											grouplist.push(chatinfo);
										}
										myCache("chatlist-"+this.userid,grouplist);
										this.getGroupInfo(chatinfo);
									}
									else{
										// 10, "撤回" 11, "已读 " 12, "消息已读回执 " 30,"加载中标记"
										
									}
								}
							}
						}
					}
				});
				
			},
			// 消息是否存在列表中
			ifadd(id){
				var ret=-1;
				var grouplist=myCache("chatlist-"+this.userid)?myCache("chatlist-"+this.userid):[];
				grouplist.forEach((cell,ii)=>{
					if(cell.id==id){
						ret=ii;
					}
				});
				return ret;
			},
			// 获取私聊信息
			async getPrivateInfo(info) {
				if(info.ifload==0){
					info[info.fromuser]=(info.fromuser!=this.userid? await this.getFriend(info.fromuser):{});
					this.updateChatList(info);
				}
				else{
					this.updateChatList(info);
				}
			},
			// 获取群信息
			async getGroupInfo(info) {
				if(info.ifload==0){
					const {data: res} = await uni.$http.get('/api/group/find/'+info.groupId);
					if(res.data){
						var data = res.data;
						info.name=data.name;
						info.img=data.headImage||'/static/image/qltx.png';
						info.notice=data.notice;
						info.remarkNickName=data.remarkNickName;
						info.showNickName=data.showNickName;
						info.showGroupName=data.showGroupName;
						info.remarkGroupName=data.remarkGroupName;
						info.customerService=data.customerService;
						info.instructor=data.instructor;
						info.ownerId=data.ownerId;
						info.productId=data.productId;
						info.productName=data.productName;
						info[data.ownerId]=(data.ownerId!= this.userid? await this.getFriend(data.ownerId):{});
						info[data.customerService]=(data.customerService!= this.userid? await this.getFriend(data.customerService):{});
						info[data.instructor]=(data.instructor!= this.userid? await this.getFriend(data.instructor):{});
						this.updateChatGroupList(info);
					}
				}
				else{
					this.updateChatGroupList(info);
				}
			},
			async getFriend(id){
				var name="匿名",img=require("@/static/image/girl.png");
				const {data: res} = await uni.$http.get("/api/friend/find/"+id);
				if(res.data){
					name=res.data.nickName?res.data.nickName:"匿名";
					img=res.data.headImage?res.data.headImage:require("@/static/image/girl.png");
				}
				return {
					name:name,
					img:img
				};
			},
			async updateChatGroupList(info){
				var idx=this.ifadd(info.id);
				if(idx<0){
					// 新增一条
					this.grouplist.push(info);
					this.$forceUpdate();
				}
				else{
					this.grouplist[idx].content=info.content;
					this.grouplist[idx].datetime=info.datetime;
					this.grouplist[idx].fromuser=info.fromuser;
					this.grouplist[idx].type=info.type;
					this.$forceUpdate();
				}
				// 重新排序 保存缓存
				this.reorder();
				myCache("chatlist-"+ this.userid,this.grouplist);
				
				// 聊天框消息缓存
				// 获取发送人的信息
				var name=info[info.sendId]?info[info.sendId].name:"匿名",img=info[info.sendId]?info[info.sendId].img:require("@/static/image/girl.png");
				var msgchat=myCache(info.id);
				if(!msgchat){
					// 第一条聊天记录保存缓存
					let firstmsg = [{
						"fromname": name, // 发送人
						"fromuser": info.fromuser, // 发送人
						"headimg": img, // 发送人
						"toname": userName, // 接收人
						"touser": this.userid, // 接收人姓名
						"content": info.content,
						"time": info.type==3?(info.time?info.time: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.minId,
						"minId": info.minId,
						"sendId": info.sendId,
						"send": info.type==6?await this.getProduct(info.content):(info.type==5?await this.getOrder(info.content):null)
					}];
					myCache(info.id,firstmsg);
				}
				else{
					// 是否已经加入到聊天记录中
					if(this.ifchatadd(info.id,info.minId)){
						// 聊天框信息 保存缓存
						let firstmsg = {
							"fromname": name, // 发送人
							"fromuser": info.fromuser, // 发送人
							"headimg": img, // 发送人
							"toname": this.userName, // 接收人
							"touser": this.userid, // 接收人姓名
							"content": info.content,
							"time": info.type==3?(info.time?info.time: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.minId,
							"minId": info.minId,
							"sendId": info.sendId,
							"send": info.type==6?await this.getProduct(info.content):(info.type==5?await this.getOrder(info.content):null)
						};
						msgchat.push(firstmsg);
						myCache(info.id,msgchat);
					}
					
				}
			},
			async updateChatList(info){
				// 此消息是否已经存在列表中
				var idx=this.ifadd(info.id);
				if(idx<0){
					this.grouplist.push(info);
					this.$forceUpdate();
				}
				else{
					this.grouplist[idx].content=info.content;
					this.grouplist[idx].datetime=info.datetime;
					this.grouplist[idx].fromuser=info.fromuser;
					this.grouplist[idx].type=info.type;
					this.$forceUpdate();
				}
				// 重新排序 保存缓存
				this.reorder();
				myCache("chatlist-"+this.userid,this.grouplist);
				
				// 聊天框消息缓存
				// 获取发送人的信息
				var name=info[info.fromuser]?info[info.fromuser].name:"匿名",img=info[info.fromuser]?info[info.fromuser].img:require("@/static/image/girl.png");
				var msgchat=myCache(info.id);
				if(!msgchat){
					// 第一条聊天记录保存缓存
					let firstmsg = [{
						"fromname": name, // 发送人
						"fromuser": info.fromuser, // 发送人
						"headimg": img, // 发送人
						"toname": this.userName, // 接收人
						"touser": this.userid, // 接收人姓名
						"content": info.content,
						"time": info.type==3?(info.time?info.time: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.minId,
						"minId": info.minId,
						"recvId": info.recvId,
						"sendId": info.sendId,
						"send": info.type==6?await this.getProduct(info.content):(info.type==5?await this.getOrder(info.content):null)
					}];
					myCache(info.id,firstmsg);
				}
				else{
					if(this.ifchatadd(info.id,info.minId)){
						// 聊天框信息 保存缓存
						let firstmsg = {
							"fromname": name, // 发送人
							"fromuser": info.fromuser, // 发送人
							"headimg": img, // 发送人
							"toname": this.userName, // 接收人
							"touser": this.userid, // 接收人姓名
							"content": info.content,
							"time": info.type==3?(info.time?info.time: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.minId,
							"minId": info.minId,
							"recvId": info.recvId,
							"sendId": info.sendId,
							"send": info.type==6?await this.getProduct(info.content):(info.type==5?await this.getOrder(info.content):null)
						};
						msgchat.push(firstmsg);
						myCache(info.id,msgchat);
					}
				}
				
			},
			
		},
		
	}
</script>

<style lang="scss">
	/*每个页面公共css */
	@import "uview-ui/index.scss";
	@import "common/demo.scss";
	@import 'colorui/main.css';
	@import 'colorui/icon.css';
	body{
		font-family: 'FZLTZHUNHJW--GB1-0';
	}
	.rightc {
	  height: 100%;
	  padding-right: 10rpx !important;
	  text-align: right !important;
	  display: flex;
	  flex: 1;
	  align-items: flex-end;
	  justify-content: flex-end;
	}
	.wrapnob{
		margin: 0;
		padding: 0;
		width: 100%;
		position: relative;
		height: calc(100vh);
		/* #ifdef H5 */
		height: calc(100vh - var(--window-top));
		/* #endif */
	}
	.wrap{
		margin: 0;
		padding: 0;
		width: 100%;
		position: relative;
		height: calc(100vh);
		/* #ifdef H5 */
		height: calc(100vh - var(--window-top) - var(--window-bottom));
		/* #endif */
		overflow-y: auto;
	}
	/* 基本布局 */
	.page {
	  width: 100%;
	}
	
	/* 当屏幕宽度小于600px时，调整布局 */
	@media (max-width: 600px) {
	  .page {
	    padding: 5px;
	  }
	}

	.page {
		position: relative;
		width: 100%;
		padding: 0;
		margin-top: 0;
		overflow: hidden;
		.back{
			width: 100%;
			height: calc(100vh - var(--window-top)) !important;
			position: absolute;
			top:0;
			left:0;
			background: url('@/static/image/bg.jpg') no-repeat top center;
			background-size: 100% 100%;
		}
	}
	.page-box{
		padding-bottom:20rpx;
	}
	.u-drawer{
		top:calc(var(--window-top) + 100rpx) !important;
		height: calc(100vh - var(--window-top) - 100rpx) !important;
		z-index: 92 !important;
	}
	.imgload{
		background-image: url('/static/image/nopic.png');
		background-size: 66% auto;
		background-position: center center; 
		background-repeat: no-repeat;
	}
</style>