const SocketConfig = {
	retry: 20,
	timeout: 10000,
	timeHandler: null,

	reset: function() {
		clearTimeout(this.timeHandler);
		this.timeHandler = null;
		return this;
	},
	start: function(send) {
		this.timeHandler = setTimeout(() => {
			send && send();
			this.reset().start(send);
		}, this.timeout);
	}
};
class SocketUtil {
	constructor({ url, onOpen, onMessage, onClose, onError }) {
		this.url = url || "api.shop.huaml.com:8282";
		this.socket = this.connectSocket(this.url);
		this.onOpenCall = onOpen;
		this.onMessageCall = onMessage;
		this.onCloseCall = onClose;
		this.onErrorCall = onError;
		this.retryTime = 0;
		this.reconnectHandler = null;
		this.lockReconnect = false;

		this.bindHandlerEvent();

		// uni.onSocketOpen(function(res) {
		// 	console.log("WebSocket连接已打开！");
		// });
		// uni.onSocketMessage(function(res) {
		// 	console.log("收到服务器内容：" + res.data);
		// });
		// uni.onSocketOpen(function() {
		// 	uni.closeSocket();
		// });
	}
	bindHandlerEvent() {
		this.socket.onOpen(this.openSocket);
		// 监听消息

		this.socket.onMessage(this.onMessageSocket);

		// 监听Socket的关闭
		this.socket.onClose(this.closeSocket);

		this.socket.onError(this.errorSocket);
	}
	connectSocket(url) {
		let path = `ws://${url}`;
		// #ifdef  MP-WEIXIN
		path = `wss://${url}`;
		// #endif

		const task = uni.connectSocket({
			url: path,
			complete: () => {}
		});
		return task;
	}
	openSocket = event => {
		console.log("contact ok", event);

		SocketConfig.reset().start(() => {
			this.send("ping");
		});

		this.onOpenCall && this.onOpenCall(event);
	};

	onMessageSocket = data => {
		console.log("Client received a message", data);
		SocketConfig.reset().start(() => {
			this.send("ping");
		});

		try {
			let info = JSON.parse(data.data);
			this.onMessageCall && this.onMessageCall(info);
		} catch (error) {}
	};
	errorSocket(err) {
		console.log("contact error", err);
		this.onErrorCall && this.onErrorCall(err);
	}

	closeSocket() {
		console.log("Client notified socket has closed");
		this.onCloseCall && this.onCloseCall();
	}
	send(data) {
		this.socket.send({
			data: JSON.stringify(data)
		});
	}
	colse() {
		this.socket.close();
	}
	reconnect() {
		if (this.lockReconnect) return;
		this.lockReconnect = true;
		clearTimeout(this.reconnectHandler);
		if (this.retryTime < SocketConfig.retry) {
			this.reconnectHandler = setTimeout(() => {
				this.socket = this.connectSocket(this.url);
				this.bindHandlerEvent();
				this.lockReconnect = false;
			}, 5000);
			this.retryTime++;
		}
	}
}

export default SocketUtil;
