<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 { mapState, mapActions } from 'vuex'
  import { myCache } from '@/utils/utils.js';
  import * as wsApi from './common/wssocket';
  import chatStore from "./store/chatStore";
  import * as enums from "./common/enums";
  import * as msgType from "./common/messageType";
	//#ifdef APP-PLUS
    const jpushModule = uni.requireNativePlugin('JG-JPush');
	//#endif

	export default {
		data() {
			return {
				userid:"",
				userName:"",
				userheadimg:"",
        isInit: false, // 是否已经初始化
        isExit: false, // 是否已退出
        audioTip: null,
        reconnecting: false // 正在重连标志

			}
		},
		computed: {
		  ...mapState('chatStore', ['chats'])
		}, 
		onLaunch() {
			// 判断版本更新 需要真机进行测试
			//checkupdate();

			// 极光推送start------------------------------
			//#ifdef APP-PLUS
			// 消息推送
			jpushModule.setLoggerEnable(true);
			jpushModule.initJPushService()
			jpushModule.addConnectEventListener(result=>{
				let connectEnable = result.connectEnable
				console.log("极光推送--jpush连接", connectEnable)
			});

			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);
				console.log("极光推送--消息通知extras", extras);
				// 点击事件
				if (notificationEventType == 'notificationOpened') {
					if(extras && extras.type &&  extras.type == 'bookCourses') {
						var bookId=extras.bookId?extras.bookId:'';
						if(bookId){
							// 预约课程详情
							uni.navigateTo({
								url: `/pages/book/bookinfo?id=${bookId}`
							});
						}
						else{
							// 预约课程列表
							uni.reLaunch({
								url: `/pages/book/booklist`
							});
						}
					}
					if(extras && extras.type &&  extras.type == 'groupMessage') {
						// 群聊消息
						// let chat = {
						//   type: 'GROUP',
						//   targetId: extras.groupId,
						//   showName: '加载中...',
						//   headImage: '/static/image/kf.png',
						// };
						// this.$store.dispatch('chatStore/openChat', chat);
						// let chatIdx = this.$store.getters['chatStore/findChatIdx'](chat);
						// uni.reLaunch({
						// 	url: `/pages/chatbox/chat-box?chatIdx=${chatIdx}`
						// });
						uni.reLaunch({
							url: `/pages/chatbox/chat`
						});
					}
					if(extras && extras.type &&  extras.type == 'privateMessage') {
						// 私信消息
						// let chat = {
						//   type: 'PRIVATE',
						//   targetId: extras.senderId,
						//   showName: '加载中...',
						//   headImage: '/static/image/kf.png',
						// };
						// this.$store.dispatch('chatStore/openChat', chat);
						// let chatIdx = this.$store.getters['chatStore/findChatIdx'](chat)
						// uni.reLaunch({
						// 	url: `/pages/chatbox/chat-box?chatIdx=${chatIdx}`
						// });
						uni.reLaunch({
							url: `/pages/chatbox/chat`
						});
					}
					
					if(!extras){
						uni.reLaunch({
							url: `/pages/chatbox/chat`
						});
					}
				}
			});
			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
			// 极光推送end--------------

			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();
			// }
//---------------------------------------------------

      // 登录状态校验
      let token =uni.getStorageSync("token");
      if(token){
        this.init(this.userId);
      }else {
        // 跳转到登录页
        uni.navigateTo({
          url: "/pages/login/login"
        })
      } 
	  
	  // 未读消息总数（用于角标）
	  let count = 0
	  myCache("this.chats",this.chats);
	  this.chats.forEach(chat => {
	    if (!chat.delete) {
	      count += chat.unreadCount
	    }
	  });
	  myCache("massageCount",count);
	  console.log("massageCountmassageCount",count);
	  
//---------------------------------------------------
		}, 
		methods: {
			 ...mapActions('chatStore'),
//---------------------------------------------------
      init(userId) {

        if (!this.userId && userId){
          this.userId=userId;
        }
        this.reconnecting = false;
        this.isExit = false;
        // 加载数据
        this.loadStore().then(() => {
          // 初始化websocket
          this.initWebSocket();
          this.isInit = true;
        }).catch((e) => {
          console.log(e);
          this.exit();
        })
      },
      // ws接收消息
      initWebSocket(){
        let token = uni.getStorageSync("token");
        wsApi.connect(this.$wsUrl, token);
        wsApi.onConnect(() => {
          if (this.reconnecting) {
            // 重连成功
            this.onReconnectWs();
          } else {
            // 加载离线消息
            this.pullPrivateOfflineMessage(this.$store.state.chatStore.privateMsgMaxId);
            this.pullGroupOfflineMessage(this.$store.state.chatStore.groupMsgMaxId);

          }
        });
        wsApi.onMessage((cmd, msgInfo) => {
          if (cmd == 2) {
            // 异地登录，强制下线
            uni.showModal({
              content: '您已在其他地方登录，将被强制下线',
              showCancel: false,
            })
            this.exit();
          } else if (cmd == 3) {
            // 私聊消息
            this.handlePrivateMessage(msgInfo);
          } else if (cmd == 4) {
            // 群聊消息
            this.handleGroupMessage(msgInfo);
          } else if (cmd == 5) {
            // 系统消息
            this.handleSystemMessage(msgInfo);
          }
        });
        wsApi.onClose((res) => {
          console.log("ws断开", res);
          // 重新连接
          this.reconnectWs();

        })

      },
      loadStore() {
        const promises = [];
        promises.push(this.$store.dispatch('chatStore/loadChat'));
        promises.push(this.$store.dispatch('groupStore/loadGroup'));
        promises.push(this.$store.dispatch('friendStore/loadFriend'));
        return Promise.all(promises);
      },
      reconnectWs() {
        // 已退出则不再重连
        if (this.isExit) {
          return;
        }
        // 记录标志
        this.reconnecting = true;
        // 重新加载一次个人信息，目的是为了保证网络已经正常且token有效
        uni.$http.get('/api/getInfo').then((res) => {
          // uni.showToast({
          //   title: '连接已断开，尝试重新连接...',
          //   icon: 'none'
          // })
          // 重新连接
          let token = uni.getStorageSync("token");
          wsApi.reconnect(this.$wsUrl, token);
        }).catch(() => {
          // 5s后重试
          setTimeout(() => {
            this.reconnectWs();
          }, 5000)
        })
      },
      exit() {
        console.log("exit");
        this.isExit = true;
        wsApi.close(3099);
        uni.removeStorageSync("token");
        uni.reLaunch({
          url: "/pages/login/login"
        })
        this.unloadStore();
      },
      unloadStore() {
        this.$store.dispatch('chatStore/clear')
      },
      async pullPrivateOfflineMessage(minId) {
        this.$store.dispatch('chatStore/setLoadingPrivateMsg',true)
        try {
          console.log("拉取私信")
          await uni.$http.get("/api/message/private/pullOfflineMessage", { minId:minId });
        } catch (error) {
          console.error("pullPrivateOfflineMessage error", error);
        } finally {
          this.$store.dispatch('chatStore/setLoadingPrivateMsg',false)
        }
      },
      async pullGroupOfflineMessage(minId) {
        this.$store.dispatch('chatStore/setLoadingGroupMsg',true)
        try {
          console.log("拉取群聊")
          await uni.$http.get('/api/message/group/pullOfflineMessage',{minId:minId});
        } catch (error) {
          console.error("pullGroupOfflineMessage error", error);
        } finally {
          this.$store.dispatch('chatStore/setLoadingGroupMsg',false)
        }
      },
      handlePrivateMessage(msg) {
        msg.selfSend = msg.sendId === this.userId;
        const friendId = msg.selfSend ? msg.recvId : msg.sendId;
        const chatInfo = { type: 'PRIVATE', targetId: friendId };
        const type=Number(msg.type)
        if (type === enums.MESSAGE_TYPE.LOADING) {
          this.$store.dispatch('chatStore/setLoadingPrivateMsg', JSON.parse(msg.content));
          return;
        }

        if (type === enums.MESSAGE_TYPE.READED) {
          this.$store.dispatch('chatStore/resetUnreadCount', chatInfo);
          return;
        }
        // 消息回执处理,改消息状态为已读
        if (type === enums.MESSAGE_TYPE.RECEIPT) {
          console.log("消息回执处理")
          this.$store.dispatch('chatStore/readedMessage', { friendId: msg.sendId });
          return;
        }
        if (type === enums.MESSAGE_TYPE.RECALL) {
          this.$store.dispatch('chatStore/recallMessage', { msgInfo: msg, chatInfo });
          return;
        }
        if (type === enums.MESSAGE_TYPE.FRIEND_NEW) {
          this.$store.dispatch('friendStore/addFriend', JSON.parse(msg.content));
            // this.friendStore.addFriend(JSON.parse(msg.content));
            return;
        }
        // if (msg.type === enums.MESSAGE_TYPE.FRIEND_DEL) {
        //     this.friendStore.removeFriend(friendId);
        //     return;
        // }

        // 视频信令处理
        // if (msgType.isRtcPrivate(msg.type)) {
        //     this.handleRtcPrivate(msg);
        //     return;
        // }

        // 普通消息插入
        if (msgType.isNormal(type) || msgType.isTip(type) || msgType.isAction(type)) {
          const friend = this.loadFriendInfo(friendId);

          this.insertPrivateMessage(friend, msg);
        }
      },

      handleGroupMessage(msg) {
        msg.selfSend = msg.sendId === this.userId;
        const chatInfo = { type: 'GROUP', targetId: msg.groupId };
        const type=Number(msg.type)
        if (type === enums.MESSAGE_TYPE.LOADING) {
          console.log("收到setLoadingGroupMsg")
          this.$store.dispatch('chatStore/setLoadingGroupMsg', JSON.parse(msg.content));
          return;
        }
        if (type === enums.MESSAGE_TYPE.READED) {
          this.$store.dispatch('chatStore/resetUnreadCount', chatInfo);
          return;
        }
        if (type === enums.MESSAGE_TYPE.RECEIPT) {
          this.$store.dispatch('chatStore/updateMessage', {
            msgInfo: {
              id: msg.id,
              groupId: msg.groupId,
              readedCount: msg.readedCount,
              receiptOk: msg.receiptOk,
            },
            chatInfo
          });
          return;
        }
        if (type === enums.MESSAGE_TYPE.RECALL) {
          this.$store.dispatch('chatStore/recallMessage', { msgInfo: msg, chatInfo });
          return;
        }
        if (type === enums.MESSAGE_TYPE.GROUP_NEW) {
          this.$store.dispatch('groupStore/addGroup', JSON.parse(msg.content));
          return;
        }
        if (type === enums.MESSAGE_TYPE.GROUP_DEL) {
          this.$store.dispatch('groupStore/removeGroup', msg.groupId);
          return;
        }

        // 群组视频信令
        // if (msgType.isRtcGroup(msg.type)) {
        //   this.handleRtcGroup(msg);
        //   return;
        // }

        if (msgType.isNormal(type) || msgType.isTip(type) || msgType.isAction(type)) {
          const group = this.loadGroupInfo(msg.groupId);
          this.insertGroupMessage(group, msg);
        }
      },

      handleSystemMessage(msg) {
        if (msg.type === enums.MESSAGE_TYPE.USER_BANNED) {
          wsApi.close(3099);
          uni.showModal({
            content: `您的账号已被管理员封禁，原因:${msg.content}`,
            showCancel: false,
          });
          this.exit();
        }
      },
      insertPrivateMessage(friend,msg) {
        const chatInfo = {
          type: 'PRIVATE',
          targetId: msg.sendId,
          showName: friend.nickName,
          headImage: friend.headImage,
        };
        this.$store.dispatch('chatStore/openChat', chatInfo);
        this.$store.dispatch('chatStore/insertMessage', { msgInfo: msg, chatInfo });
        this.playAudioTip();
      },

      insertGroupMessage(group, msg) {
        const chatInfo = {
          type: 'GROUP',
          targetId: group.id,
          showName: group.name,
          headImage: group.headImageThumb,
        };
        this.$store.dispatch('chatStore/openChat', chatInfo);
        this.$store.dispatch('chatStore/insertMessage', { msgInfo: msg, chatInfo });
        this.playAudioTip();
      },
      onReconnectWs() {
        this.reconnecting = false;
        Promise.all([
          this.$store.dispatch('friendStore/loadFriend'),
          this.$store.dispatch('groupStore/loadGroup')
        ]).then(() => {
          // uni.showToast({
          //   title: "已重新连接",
          //   icon: 'none'
          // });
          // 加载离线消息
          const chatState = this.$store.state.chatStore;
          this.pullPrivateOfflineMessage(chatState.privateMsgMaxId);
          this.pullGroupOfflineMessage(chatState.groupMsgMaxId);
        }).catch((e) => {
          console.log(e);
          this.exit();
        })
      },
      loadFriendInfo(id, callback) {
        let friend = this.$store.getters['friendStore/findFriend'](id)
        if (!friend) {
          this.$store.dispatch('friendStore/loadFriend')
           friend = this.$store.getters['friendStore/findFriend'](id)
        }
        if (!friend) {
          console.log("未知用户:", id)
          friend = {
            id: id,
            nickName: "未知用户",
            headImage: ""
          }
        }
        return friend;
      },
      loadGroupInfo(id) {
        let group = this.$store.getters['groupStore/findGroup'](id)
        if (!group) {
          group = {
            id: id,
            showGroupName: "未知群聊",
            headImageThumb: ""
          }
        }
        return group;
      },
      playAudioTip() {
        // 音频播放实现（如需）
        // this.audioTip = uni.createInnerAudioContext();
        // this.audioTip.src = "/static/audio/tip.wav";
        // this.audioTip.play();
      },
//---------------------------------------------------

			// 定时心跳包
      /**
			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';
  @import "/im.scss";
  @import url('./static/icon/iconfont.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>
