import globalConfig from './global-config'

let {ip, wsip} = globalConfig;

let tempIp = ip.replace('http://', '').replace('https://', '')

function websocketFn(obj, callBackFn) {

    let lockReconnect = false;//避免重复连接
    let wsUrl = wsip + '?gId=' + obj.gId + '&cId=' + obj.cId + '&path=' + obj.path + '&from=' + tempIp;
    let ws;
    let tt;

    function createWebSocket() {
        try {
            ws = new WebSocket(wsUrl);
            init();
        } catch (e) {
            console.log('catch');
            reconnect(wsUrl);
        }
    }

    function init() {
        ws.onclose = function () {
            console.log('链接关闭');
            ws = null;
            reconnect(wsUrl);
        };
        ws.onerror = function () {
            console.log('发生异常了');
            reconnect(wsUrl);
        };
        // 监听socket连接  是否连接上
        ws.onopen = function () {
            console.log('建立连接onopen');
            //心跳检测重置
            heartCheck.start();
        };
        // 监听socket消息
        ws.onmessage = function (evt) {
            //拿到任何消息都说明当前连接是正常的
            // console.log('接收到消息onmessage', JSON.parse(evt.data));
            heartCheck.start();

            let data = evt.data;
            if (data.indexOf('10000') != -1) {
                return;
            }
            let respData = JSON.parse(data);
            // console.log('ws_data', data)
            callBackFn(respData);
        };

    }
    function reconnect(url) {
        if(lockReconnect) {
            return;
        };

        lockReconnect = true;
        //没连接上会一直重连，设置延迟避免请求过多  4秒后会重新创建一个新的websocket链接
        tt && clearTimeout(tt);
        tt = setTimeout(function () {
            createWebSocket(url);
            lockReconnect = false;
        }, 4000);
    }

    //心跳检测
    var heartCheck = {
        timeout: 5*1000, //此时间不能大于服务器设置的心跳时间
        timeoutObj: null,
        serverTimeoutObj: null,
        start: function(){
            var self = this;
            this.timeoutObj && clearTimeout(this.timeoutObj);
            this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
            this.timeoutObj = setTimeout(function(){
                //这里发送一个心跳，后端收到后，返回一个心跳消息，
                // console.log(self.timeoutObj, self.serverTimeoutObj, obj.path+'-cmd');
                // console.log('wswsws', ws)
                if(ws){
                    ws.send(obj.path+'-cmd');
                }
                self.serverTimeoutObj = setTimeout(function() {
                    ws.close();
                    // createWebSocket();
                }, self.timeout);

            }, this.timeout)
        }
    }
    createWebSocket(wsUrl);


}

export default websocketFn;