/**
 * Created by Zhang Haijun on 2017/11/27.
 */
let SocketInstance = function () {
    this.interval = 1000 * 20;
    // 避免重复连接
    this.lockReconnect = false;
    // 是否手动关闭
    this.isManual = false;
};
SocketInstance.prototype = {
    Init: function (url, commonFun) {
        if ('WebSocket' in window) {
            this.socket = new WebSocket( `ws://${location.host }${url}`);
            this.wsObj = {
                url,
                commonFun
            };
            this.InitEventHandle(commonFun);
        } else {
            console.log('Websocket not supported');
        }
    },
    InitEventHandle: function (commonFun) {
        const that = this;
        this.socket.onopen = function () {
            console.log('websocket connect');
            this.isManual = false;
            that.HeartReset();
        };
        this.socket.onmessage = function (event) {
            that.HeartReset();
            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', data);
            if (!that.isManual) that.ReConnect();
        };
        this.socket.onerror = function (e) {
            console.log('websocket连接异常', e);
            that.ReConnect();
        };
    },
    ReConnect: function () {
        if(this.lockReconnect) return;
        this.lockReconnect = true;
        setTimeout(() => {
            this.Init(this.wsObj.url, this.wsObj.commonFun);
        }, 2000);
    },
    Destroy: function () {
        this.isManual = true;
        this.socket.close();
    },
    HeartCheck: function () {
        this.timer = setTimeout(() => {
            this.socket.send('HeartHeat');
            this.serverTimer = setTimeout(() => {
                this.Destroy();
            }, 60 * 1000);
        }, this.interval);
    },
    HeartReset: function () {
        clearTimeout(this.timer);
        clearTimeout(this.serverTimer);
        this.HeartCheck();
    }
};
export default new SocketInstance();
