<script>
	let WebIM = (wx.WebIM = require("./utils/WebIM")["default"]);
	let msgStorage = require("./components/chat/msgstorage");
	let msgType = require("./components/chat/msgtype");
	let disp = require("./utils/broadcast");
	let logout = false;
	// let emedia = uni.emedia = require("./emediaSDK/webrtc/src/entry")
	// let emedia = (uni.emedia = require("./emediaSDK/emedia_for_miniProgram"));
	// emedia.config({ useUniappPlugin: true });
	function ack(receiveMsg) {
	  // 处理未读消息回执
	  var bodyId = receiveMsg.id; // 需要发送已读回执的消息id
	
	  var ackMsg = new WebIM.message("read", WebIM.conn.getUniqueId());
	  ackMsg.set({
	    id: bodyId,
	    to: receiveMsg.from,
	  });
	  WebIM.conn.send(ackMsg.body);
	}
	function onMessageError(err) {
	  if (err.type === "error") {
	    uni.showToast({
	      title: err.errorText,
	    });
	    return false;
	  }
	
	  return true;
	}
	function getCurrentRoute() {
	  let pages = getCurrentPages();
	  if (pages.length > 0) {
	    let currentPage = pages[pages.length - 1];
	    return currentPage.route;
	  }
	  return "/";
	}
	
	
	// 包含陌生人版本
	function calcUnReadSpot(message) {
	  let myName = uni.getStorageSync("myUsername");
	  uni.getStorageInfo({
	    success: function (res) {
	      let storageKeys = res.keys;
	      let newChatMsgKeys = [];
	      let historyChatMsgKeys = [];
	      storageKeys.forEach((item) => {
	        if (item.indexOf(myName) > -1 && item.indexOf("rendered_") == -1) {
	          newChatMsgKeys.push(item);
	        }
	      });
	      let count = newChatMsgKeys.reduce(function (result, curMember, idx) {
	        let chatMsgs;
	        chatMsgs = uni.getStorageSync(curMember) || [];
	        return result + chatMsgs.length;
	      }, 0);
	
	      getApp().globalData.unReadMessageNum = count;
	      disp.fire("em.unreadspot", message);
	    },
	  });
	}
	
	function saveGroups() {
	  var me = this;
	  return WebIM.conn.getGroup({
	    limit: 50,
	    success: function (res) {
	      uni.setStorage({
	        key: "listGroup",
	        data: res.data,
	      });
	    },
	    error: function (err) {
	      console.log(err);
	    },
	  });
	}
	
	// var jpushModule = uni.requireNativePlugin("JG-JPush");
	import webIM from './utils/WebIM.js'
	var that = ''
	export default {
		globalData: {
			unReadMessageNum: 0,
			userInfo: null,
			saveFriendList: [],
			saveGroupInvitedList: [],
			isIPX: false, //是否为iphone X
			conn: {
				closed: false,
				curOpenOpt: {},
		
				open(opt) {
					uni.showLoading({
						title: "正在初始化客户端..",
						mask: true,
					});
					this.curOpenOpt = opt;
					WebIM.conn.open(opt);
					this.closed = false;
				},
		
				reopen() {
					if (this.closed) {
						//this.open(this.curOpenOpt);
						WebIM.conn.open(this.curOpenOpt);
						this.closed = false;
					}
				},
			},
			onLoginSuccess: function(myName) {
				uni.hideLoading();
				uni.redirectTo({
					url: "../chat/chat?myName=" + myName,
				});
			},
		
			getUserInfo(cb) {
				var me = this;
		
				if (this.userInfo) {
					typeof cb == "function" && cb(this.userInfo);
				} else {
					// 调用登录接口
					uni.login({
						success() {
							uni.getUserInfo({
								success(res) {
									me.userInfo = res.userInfo;
									typeof cb == "function" && cb(me.userInfo);
								},
							});
						},
					});
				}
			},
		
			checkIsIPhoneX: function() {
				const me = this;
				uni.getSystemInfo({
					success: function(res) {
						// 根据 model 进行判断
						if (res.model && res.model.search("iPhone X") != -1) {
							me.isIPX = true;
						}
					},
				});
			},
		},
		
		onLaunch: function() {
			this.HXlogin()
			console.log('App Launch')
			var me = this;
			var logs = uni.getStorageSync("logs") || [];
			logs.unshift(Date.now());
			uni.setStorageSync("logs", logs); //
			
			disp.on("em.main.ready", function() {
				calcUnReadSpot();
			});
			disp.on("em.chatroom.leave", function() {
				calcUnReadSpot();
			});
			disp.on("em.chat.session.remove", function() {
				calcUnReadSpot();
			});
			disp.on("em.chat.audio.fileLoaded", function() {
				calcUnReadSpot();
			});
			disp.on("em.main.deleteFriend", function() {
				calcUnReadSpot();
			});
			disp.on("em.chat.audio.fileLoaded", function() {
				calcUnReadSpot();
			}); //
			
			WebIM.conn.listen({
				onOpened(message) {
					console.log('>>>>>>环信登录成功啦')
				},
			
				onReconnect() {
					uni.showToast({
						title: "重连中...",
						duration: 2000,
					});
				},
			
				onSocketConnected() {
					uni.showToast({
						title: "socket连接成功",
						duration: 2000,
					});
				},
			
				onClosed() {
					/* uni.showToast({
						title: "网络已断开",
						icon: "none",
						duration: 2000,
					});
					uni.redirectTo({
						url: "/pages/login/codeLogin/codeLogin",
					}); */
					me.globalData.conn.closed = true;
					WebIM.conn.close();
				},
			
				onInviteMessage(message) {
					me.globalData.saveGroupInvitedList.push(message);
					disp.fire("em.invite.joingroup", message); // uni.showModal({
					// 	title: message.from + " 已邀你入群 " + message.roomid,
					// 	success(){
					// 		disp.fire("em.invite.joingroup", message);
					// 	},
					// 	error(){
					// 		disp.fire("em.invite.joingroup", message);
					// 	}
					// });
				},
			
				onReadMessage(message) {
					//console.log('已读', message)
				},
			
				//onPresence为旧版 ，建议参考最新增删好友api文档 ：http://docs-im.easemob.com/im/web/basics/buddy
				onPresence(message) {
			
					switch (message.type) {
						case "unsubscribe":
							break;
							// 好友邀请列表
						case "subscribe":
							for (let i = 0; i < me.globalData.saveFriendList.length; i++) {
								if (me.globalData.saveFriendList[i].from === message.from) {
									me.globalData.saveFriendList[i] = message;
									disp.fire("em.subscribe");
									return;
								}
							}
							msgStorage.saveReceiveMsg(message, 'INFORM'); //存添加好友消息，方便展示通知
							me.globalData.saveFriendList.push(message);
							disp.fire("em.subscribe");
			
							break;
			
						case "subscribed":
							uni.showToast({
								title: "添加成功",
								duration: 1000,
							});
							disp.fire("em.subscribed");
							break;
			
						case "unsubscribed":
							disp.fire("em.unsubscribed");
							break;
						case "direct_joined":
							saveGroups();
							uni.showToast({
								title: "已进群",
								duration: 1000,
							});
							break;
						case "memberJoinPublicGroupSuccess":
							saveGroups();
							uni.showToast({
								title: "已进群",
								duration: 1000,
							});
							break;
						case "invite":
							// 防止重复添加
							for (let i = 0; i < me.globalData.saveGroupInvitedList.length; i++) {
								if (me.globalData.saveGroupInvitedList[i].from === message.from) {
									me.globalData.saveGroupInvitedList[i] = message;
									disp.fire("em.invite.joingroup")
									return;
								}
							}
							me.globalData.saveGroupInvitedList.push(message);
							disp.fire("em.invite.joingroup");
							msgStorage.saveReceiveMsg(message, 'INFORM'); //存添加好友消息，方便展示通知
							break;
						case "unavailable":
							disp.fire("em.contacts.remove");
							disp.fire("em.group.leaveGroup", message);
							break;
			
						case "deleteGroupChat":
							disp.fire("em.invite.deleteGroup", message);
							break;
			
						case "leaveGroup":
							disp.fire("em.group.leaveGroup", message);
							break;
			
						case "removedFromGroup":
							disp.fire("em.group.leaveGroup", message);
							break;
			
						default:
							break;
					}
				},
			
				onRoster(message) {
					// let pages = getCurrentPages();
					// if(pages[0]){
					// 	pages[0].onShow();
					// }
				},
			
				onVideoMessage(message) {
					console.log("onVideoMessage: ", message);
			
					if (message) {
						msgStorage.saveReceiveMsg(message, msgType.VIDEO);
					}
			
					calcUnReadSpot(message);
					ack(message);
				},
			
				onAudioMessage(message) {
					console.log("onAudioMessage", message);
			
					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.AUDIO);
						}
			
						calcUnReadSpot(message);
						ack(message);
					}
				},
			
				onCmdMessage(message) {
					console.log("onCmdMessage", message);
			
					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.CMD);
						}
			
						calcUnReadSpot(message);
						ack(message);
					}
				},
			
				// onLocationMessage(message){
				// 	console.log("Location message: ", message);
				// 	if(message){
				// 		msgStorage.saveReceiveMsg(message, msgType.LOCATION);
				// 	}
				// },
				onTextMessage(message) {
					console.log("收到消息", message);
			
					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.TEXT);
						}
			
						calcUnReadSpot(message);
						ack(message);
					}
				},
			
				onEmojiMessage(message) {
					console.log("onEmojiMessage", message);
			
					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.EMOJI);
						}
			
						calcUnReadSpot(message);
						ack(message);
					}
				},
			
				onPictureMessage(message) {
					console.log("onPictureMessage", message);
			
					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.IMAGE);
						}
			
						calcUnReadSpot(message);
						ack(message);
					}
				},
			
				onFileMessage(message) {
					console.log("onFileMessage", message);
			
					if (message) {
						if (onMessageError(message)) {
							msgStorage.saveReceiveMsg(message, msgType.FILE);
						}
			
						calcUnReadSpot(message);
						ack(message);
					}
				},
			
				// 各种异常
				onError(error) {
					console.log(error); // 16: server-side close the websocket connection
					// if (error.type == WebIM.statusCode.WEBIM_CONNCTION_DISCONNECTED) {
					//   // if(error.type == WebIM.statusCode.WEBIM_CONNCTION_DISCONNECTED && !logout){
					//   // if(WebIM.conn.autoReconnectNumTotal < WebIM.conn.autoReconnectNumMax){
					//   // 	return;
					//   // }
					//   uni.showToast({
					//     title: "websocket 断开",
					//     duration: 1000
					//   });
					//   uni.redirectTo({
					//     url: "../login/login"
					//   });
					//   logout = true;
					//   return;
					// } // 8: offline by multi login
			
					// if (error.type == WebIM.statusCode.WEBIM_CONNCTION_SERVER_ERROR) {
					//   uni.showToast({
					//     title: "offline by multi login",
					//     duration: 1000
					//   });
					//   uni.redirectTo({
					//     url: "../login/login"
					//   });
					// }
			
					if (error.type == WebIM.statusCode.WEBIM_CONNCTION_OPEN_ERROR) {
						uni.hideLoading();
						disp.fire("em.error.passwordErr"); // uni.showModal({
						// 	title: "用户名或密码错误",
						// 	confirmText: "OK",
						// 	showCancel: false
						// });
					}
			
					if (error.type == WebIM.statusCode.WEBIM_CONNCTION_AUTH_ERROR) {
						uni.hideLoading();
						disp.fire("em.error.tokenErr");
					}
			
					if (error.type == "socket_error") {
						///sendMsgError
						console.log("socket_errorsocket_error", error);
						/* uni.showToast({
							title: "网络已断开",
							icon: "none",
							duration: 2000,
						}); */
						disp.fire("em.error.sendMsgErr", error);
					}
				},
			});
			this.globalData.checkIsIPhoneX();
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods: {
			HXlogin() {
				var userId = uni.getStorageSync('myUsername')
				var options = {
					user: userId,
					pwd	: '12345678',
					appKey: uni.WebIM.config.appkey,
					success: function() {
						// var lianjie = uni.WebIM.conn.isOpened()
						var my = uni.getStorageSync("myUsername");
						console.log('登录成功');
						// uni.setStorageSync('myUsername',my)
					},
					error: function() {
						
					}
				}
				uni.WebIM.conn.open(options);
			}
		}
	}
</script>
<style lang="scss">
	/*每个页面公共css */
	@import "colorui/main.css";
	@import "colorui/icon.css";
	@import "uview-ui/index.scss";
	.content {
		background-color: #ffffff;
		width: 100%;
		min-height: 100vh;
		display: flex;
		flex-direction: column;
		font-size: 28rpx;
		color: #333;
		box-sizing: border-box;
	}
	.hflex {
		display: flex;
		flex-direction: row;
		flex-wrap: nowrap;
	}
	.vflex {
		display: flex;
		flex-direction: column;
		flex-wrap: nowrap;
	}
	.jbetween {
		justify-content: space-between;
	}
	.jaround {
		justify-content: space-around;
	}
	.jend {
		justify-content: flex-end;
	}
	.jcenter {
		justify-content: center;
	}
	.acenter {
		align-items: center;
	}
	.abetween {
		align-content: space-between;
	}
	.astart {
		align-items: flex-start;
	}
	.aend {
		align-items: flex-end;
	}
	.fwrap {
		flex-wrap: wrap;
	}
	.text_hide {
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}
	.text_hide2 {
		text-overflow: -o-ellipsis-lastline;
		overflow: hidden;				//溢出内容隐藏
		text-overflow: ellipsis;		//文本溢出部分用省略号表示
		display: -webkit-box;			//特别显示模式
		-webkit-line-clamp: 2;			//行数
		line-clamp: 2;					
		-webkit-box-orient: vertical;	//盒子中内容竖直排列
	}
</style>
