import  global from '@/utils/global.js'
const baseSocketUrl=global.WebSocketUrl
class socket {
	constructor(options) {
		//用户id
		this.sid=options.sid
		this.socketUrl=baseSocketUrl+options.sid
		this.socketStart = false;
		this.enableHeartbeat=true
		this.monitorSocketClose();
		this.socketReceive();
		this.monitorSocketError();
	}
	init(callback) {
		const _this = this;
		if (this.socketUrl) {
			if (this.socketStart) {
				console.log('webSocket已经启动了');
			} else {
				uni.connectSocket({
					url: this.socketUrl,
					method: 'GET'
				});
				uni.onSocketOpen((res) => {
					this.socketStart = true;
					callback && callback();
					console.log('WebSocket连接已打开！');
				});
				setTimeout(() => {
					_this.getHeartbeat();
				}, 5000);
			}
		} else {
			console.log('socketUrl为空');
		}
	}
	//Socket给服务器发送消息
	send(data, callback) {
		const _this = this;
		uni.sendSocketMessage({
			data: JSON.stringify(data),
			success: () => {
				callback && callback(true);
			},
			fail: () => {
				callback && callback(false);
			}
		});
	}
	//Socket接收服务器发送过来的消息
	socketReceive() {
		const _this = this;
		uni.onSocketMessage(function(res) {
			let data = JSON.parse(res.data);
			console.log('收到服务器内容：', data);
			_this.acceptMessage && _this.acceptMessage(data);
		});
	}
	//关闭Socket
	closeSocket() {
		const _this = this;
		uni.closeSocket();
		_this.socketStart = false;
		//关闭心跳
		_this.enableHeartbeat = false
	}
	//监听Socket关闭
	monitorSocketClose() {
		const _this = this;
		uni.onSocketClose(function(res) {
			console.log('WebSocket 已关闭！');
			_this.socketStart = false;
			if (_this.enableHeartbeat) {
				//开启心跳就自动重连
				setTimeout(()=>{
					_this.init()
				},3000)
			}
		});
	}
	//监听Socket错误
	monitorSocketError() {
		const _this = this;
		uni.onSocketError(function(res) {
			_this.socketStart = false;
			console.log('WebSocket连接打开失败，请检查！');
			_this.error && _this.error(res);
		});
	}
	//心跳
	getHeartbeat() {
		const _this = this;
		if (!this.enableHeartbeat) {
			//未开启心跳
			return
		}
		//开启心跳
		this.send({
			content: "心跳",
			sid:this.sid
		}, (val) => {
			setTimeout(() => {
				if (val) {
					_this.getHeartbeat();
				} else {
					_this.init();
				}
			}, 10000);
		});
	}
}
export default socket
