/**
 * Created by Zhang Haijun on 2017/11/27.
 */
let SocketInstance = function (onMessage) {
    this.retryCount = 1;
};
SocketInstance.prototype = {
    Init: function (commonFun) {
        let that = this;
        if ('WebSocket' in window) {
            let url = 'ws://' + location.host + '/messageService';
            this.socket = new WebSocket(url);
            this.socket.onopen = function (data) {
                console.log('websocket connect');
                that.retryCount = 1;
            };
            this.socket.onmessage = function (event) {
                let data = JSON.parse(JSON.parse(event.data).content);
                console.log(data);
                if (commonFun && typeof commonFun === 'function') commonFun(data);// 公共方法
                if (that.OnMessage) that.OnMessage(data);// 每个组件实例的特定方法
            };
            this.socket.onclose = function (data) {
                console.log('websocket close');
            };
            this.socket.onerror = function (e) {
                if (that.retryCount < 7) that.ResetConnect();
                console.log('websocket连接异常', e);
            };
        } else {
            console.log('Websocket not supported');
        }
    },
    ResetConnect: function () {
        let that = this;
        setTimeout(function () {
            that.retryCount++;
            that.Init();
        }, 6 * 1000);
    },
    Destroy: function () {
        this.socket.close();
    }
};
export default new SocketInstance();
