export default {
	data() {
		return {
			userInfo: {
				alias: '',
				avatar: '',
				city: '',
				uid: '',
				count: 0,
				isAdmin: ''
			},
			unreadMessage: 0,	// 心跳检测接受消息失败次数
			sendFailCount: 0,	// 心跳检测发送消息失败次数
			sendData: {
				fromUid: '',
				context: '测试心跳'
			},
			uid: '',
			SocketTask: {},
			lockReconnect: false,	// 避免重复连接
		}
	},
	methods: {
		// 创建连接
		createWebSocket(uid) {
			try {
				this.uid = uid
				this.sendData.fromUid = uid
				this.SocketTask = wx.connectSocket({
					url: `${uni.$wsLocation}/education/chat?uid=`+uid,
					success: res => {
						// console.log('websocket连接成功')
						if (this.userInfo.count == 0) {
							uni.removeTabBarBadge({
								index: 2
							})
						} else {
							// 调用 uni.setTabBarBadge() 方法，为购物车设置右上角的徽标
							uni.setTabBarBadge({
								index: 2,
								text: this.userInfo.count + '', // 注意：text 的值必须是字符串，不能是数字
							})
						}
					},
					fail: e => {
						this.reconnect()
					}
				})
				
				uni.$SocketTask = this.SocketTask
				// 监听打开事件
				this.startWebSocket()
			} catch(e) {
				this.reconnect()
			}
		},
		
		// 监听开始事件
		startWebSocket() {
			// console.log('websock监听开启')
			this.SocketTask.onOpen(() => {
				this.heartCheck()
				this.receiveMessage()
			})
		},
		
		// 重连操作
		reconnect() {
			// console.log('重连')
			if (this.lockReconnect) {
				return;
			}
			this.lockReconnect = true
			//没连接上会一直重连，设置延迟避免请求过多
			tt && clearTimeout(tt)
			let tt = setTimeout(() => {
				this.createWebSocket(this.uid)
				this.lockReconnect = false
			}, 4000)
		},
		
		// 心跳检测
		heartCheck() {
			send && clearInterval(send)
			let send = setInterval(() => { 
				this.SocketTask.send({
					data: JSON.stringify(this.sendData),
					success: () => {
						// console.log('发送成功')
						if (this.unreadMessage < 2) {
							this.unreadMessage++
						} else {
							clearInterval(send)
							this.SocketTask.close()
							this.reconnect()
						}
					},
					fail: () => {
						// console.log('发送失败')
						if (this.sendFailCount < 2) {
							// 发送数据失败,失败次数+1
							this.sendFailCount++
						} else {
							// 发送数据失败次数大于等于2,销毁重连
							clearInterval(send)
							this.SocketTask.close()
							this.reconnect()
						}
					}
				})
			}, 60*1000);
		},
		
		// 接受服务端消息
		receiveMessage() {
			this.SocketTask.onMessage( res => {
				if (res.data !== '测试心跳') {
					// console.log('监听',res.data)
					this.userInfo.count++;
					this.updateUserInfo(this.userInfo)
				} else {
					// 测试心跳
					this.unreadMessage--
					// console.log('收到消息',res.data)
				}
			})
		}
	}
	
}