// 1:启动webSocket
var root = this;
var upperEntity, sessionID, overtime, timer, overTimer
var socket = null;
var url = "";
var callbacksuccess = []
var variableMsg //保存最后一次的 读取变量的msg
var wsMethod = (function() {
console.log('wsbsocket.js')
    function connect(wsurl) {
        if ('WebSocket' in root) {
            socket = new WebSocket(wsurl);
        } else if ('MozWebSocket' in root) {
            socket = new MozWebSocket(wsurl);
        } else {
            alert("您的浏览器版本过低，将不能接收系统消息");
        }
    }

    function onOpen() {
        postMessage({ code: "open" });

        overTimer = setInterval(() => {
            callbacksuccess.forEach((item, index) => {
                item.overCount++
                    if (item.overCount >= overtime) {
                        postMessage({ code: 'error', data: { name: item.name, MessageGuid: item.id, Message: '超时' } })
                        callbacksuccess.splice(index, 1)
                    }
            })
        }, 1000)
        if (variableMsg != null) {
            var wscomSIM = {
                Name: "SIMDATAINPIPE",
                SessionID: sessionID,
                Arguments: [{
                    Variables: variableMsg.Arguments[0].Variables,
                    MessageGuid: variableMsg.Arguments[0].MessageGuid,
                    PK_UPPER_ENTITY: upperEntity,
                    IsCalcValue: true,
                    // SessionID: sessionID
                }]
            }
            console.log('重新发送断开之前的请求')
            sendMessage(wscomSIM)
        }
    }

    function onClose(isActive) {
        postMessage({ code: "close" });
        //断线重连
        if (isActive == true) return
        timer = setTimeout(function() {
            connect(url);
            initMessageEvent();
        }, 3000);
    }

    function onMessaage(event) {
        let data = JSON.parse(event.data)

        // 清除存储发送命令
        if (data.Value.Result == 1) {  //sessionID错误 清除所有
            callbacksuccess = []
            console.log('清空')
        }
        clearCallBack(data)
        if (data.Value.Ex) { // 如果返回有错误
            //错误时 也要处理messageguid  知道那条发送失败  并在callbacksuccess删除错误发送的messageguid
            let postdata = data.Value.Ex
            postdata.name = data.CommandName
            postdata.MessageGuid = data.Value.Guid
            postdata.Result = data.Value.Result
            postMessage({ code: "error", data: postdata });
        } else {
            switch (data.CommandName) {
                case "SQL":
                case "SIMDATA": // 新加 单次
                case 'SIMDATAINPIPE': // 多次
                case 'SIMDATA': // 一次
                case 'BATCHWRITE':
                case 'CONNECTION': // 多次
                case 'STATUS':
                case 'ARCHIVEDATA':
                case 'SIMDEVICE':
                case 'ALARMDATA': // 报警归档 返回需要20+秒
                case 'DEPLOY': // 下发数据
                case 'RESTART': // 重启
                    postMessage({ code: data.CommandName, data: data.Value });
                    break
                
                default:
                    postMessage({ code: 'wsReceive', data: data });
            }
        }
    }

    function onError(event) {
        socket = null;
        if (event.target.readyState == 3) {
            //断线重连
            setTimeout(function() {
                connect(event.target.url);
                initMessageEvent();
            }, 3000);
        }
    }

    function sendMessage(msg) {
        if (socket == null) return;
        callbacksuccess.push({
            name: msg.Name,
            id: msg.Arguments[0] ? msg.Arguments[0].MessageGuid : '',
            overCount: 0
        })
        try {
            //保存最后一次发送的variableMsg
            if (msg.Name == 'SIMDATAINPIPE') {
                variableMsg = msg
                    // msg.Arguments[0].Variables.forEach((item) => {
                    //     let index = variableList.findIndex(o => o.PK == item.PK)
                    //     if (index == -1) {
                    //         variableList.push(item)
                    //     }
                    // })
                    // msg.Arguments[0].Variables = variableList
            }
            socket.send(JSON.stringify(msg));
        } catch (error) {
            let data = {
                Message: JSON.stringify(error),
                name: msg.Name,
                MessageGuid: msg.Arguments[0].MessageGuid
            }
            let errData = {
                CommandName: msg.Name,
                Value:{
                    Guid: msg.Arguments[0].MessageGuid
                }
            }
            clearCallBack(errData)
            postMessage({ code: 'error', data: data })
        }

    }

    function sendvariableMsg() {
        if (socket == null) return;
        callbacksuccess.push({
            name: 'SIMDATAINPIPE',
            id: variableMsg.Arguments[0] ? variableMsg.Arguments[0].MessageGuid : '',
            overCount: 0
        })
        try {
            socket.send(JSON.stringify(variableMsg));
        } catch (error) {
            let data = JSON.stringify(error)
            data.name = 'SIMDATAINPIPE'
            // data.MessageGuid = msg.Arguments[0].MessageGuid
            postMessage({ code: 'error', data: JSON.stringify(error) })
        }

    }

    function initMessageEvent() {
        clearTimeout(timer)
        socket.onopen = onOpen;
        socket.onclose = onClose;
        socket.onmessage = onMessaage;
        socket.onerror = onError;
        //重连后发送sendvariableMsg 信息
        if (this.variableMsg != null) { sendvariableMsg(); }
    }
    function clearCallBack(data) {
        // 清除存储发送命令
        let index = -1
        if (data.CommandName == 'STATUS' || data.CommandName == 'SIMDEVICE' || data.CommandName == 'CONNECTION' || data.CommandName == 'DEPLOY' || data.CommandName == 'RESTART') {
            index = callbacksuccess.findIndex(o => o.name == data.CommandName)
        } else {
            let Guid = data.Value.Guid ? data.Value.Guid : data.Value.MessageGuid
            index = callbacksuccess.findIndex(o => o.id == Guid && o.name == data.CommandName)
        }
        if (index !== -1) {
            // console.log('已删除', callbacksuccess[index].id)
            callbacksuccess.splice(index, 1)
        }
    }
    return {
        initWsConnect: function(url) {
            connect(url);
            initMessageEvent();
        },
        sendMessage
    }
})();

self.onmessage = function(event) {
    if (event.data.code) {
        var code = event.data.code.toLowerCase();
        switch (code) {
            case "init":
                upperEntity = event.data.upperEntity;
                sessionID = event.data.sessionID;
                url = event.data.url
                overtime = event.data.overtime
                postMessage({ code: 'init'});
                break;
            case "send":
                let data = event.data.data

                //如果是老upper data.Arguments[0] = upperEntity
                data.SessionID = sessionID
                data.Arguments.forEach(item => {
                    item.PK_UPPER_ENTITY = upperEntity
                    item.SessionID = sessionID
                });
                data.PK_UPPER_ENTITY = upperEntity
                if (this.socket == null) {
                    wsMethod.initWsConnect(url)
                    this.socket.addEventListener('open', function() {
                        wsMethod.sendMessage(data)
                    });
                } else {
                  if (this.socket.readyState == 0) {
                    this.socket.addEventListener('open', function() {
                      wsMethod.sendMessage(data)
                    });
                  } else if (this.socket.readyState == 1){
                    wsMethod.sendMessage(data)
                  } else {
                    postMessage({ code: 'error', data: {Message:'websocket连接异常', name: data.Name, MessageGuid: data.Arguments[0]?data.Arguments[0].MessageGuid: ''} })
                    console.log(data.Arguments[0]?data.Arguments[0].MessageGuid: '')
                  }
                }

                break;
            case "state":
                postMessage({ code: 'state', state: socket.readyState });
                break
            case "open":
                //var url = "ws://192.168.1.198:8001";
                wsMethod.initWsConnect(url);
                break
            case "close":
                if (this.socket) {
                    // console.log(this.socket)
                    this.socket.close()
                    this.socket = null
                    this.socket.onclose(true)
                }
                break
            default:
                break;
        }
    }
}

// self.onmessage = function (event) {
//     var data = event.data;
//     if (!!data.code) {
//         if (data.code == "close") {
//             self.terminate();
//         }
//     }
// };
// self.postMessage({
//     code: "init",
//     loggedUserId: 'demo',
//     sessionid: 'demo'
// });