"use strict";
import {config} from "../../config.js";
import {fullMap} from "../../fullMap.js";
import {util} from "../../util/util.js";
import {khcToastr} from "../alert/khcToastr.js";

class websocket{
    constructor(data) {
        this.khcWS=null;
        this.khcWSFuncMap=new Map();
        this.lockReconnect=false;//防止重复连接
    }
    init(){
        let that=this;
        that.createWebsocket=function (){
            if('WebSocket' in window){
                that.khcWS=new WebSocket(that._getWsUrl())
                that.khcWS.onopen = function (evt) {
                    if(config.getConfigJson().logLevel=='debug') console.log('khcWS 服务已连接')
                };
                that.khcWS.onclose = function (evt) {
                    if(config.getConfigJson().logLevel=='debug') console.log('khcWS 连接关闭');
                    that.reconnect();
                    if(config.getConfigJson().logLevel=='debug') console.log('khcWS 正在重连');
                };
                that.khcWS.onmessage = function (evt) {
                    if(config.getConfigJson().logLevel=='debug') console.log('（WS）收到消息：'+evt.data)
                    let dataJson=JSON.parse(evt.data);
                    that.refresh(dataJson);
                }
                that.khcWS.onerror = function () {
                    if(config.getConfigJson().logLevel=='debug') console.log('websocket通信异常');
                }
                that.khcWS.onbeforeunload=function (){
                    that.khcWS.close();
                }
            }else{
                if(config.getConfigJson().logLevel=='debug') console.log('此游览器版本不支持websocket，请升级或更换其他游览器')
            }
        }
        that.createWebsocket();
        that.reconnect=function (){
            if(that.lockReconnect){
                return ;
            }
            that.lockReconnect = true;
            setTimeout(function () {
                that.createWebsocket();
                that.lockReconnect = false;
            }, 4000);
        }
    }
    _initWsUrl(){
        let that=this;
        let userId=util.getLocalStorageItem('userId')
        that.wsUrl=config.getWebsocketUrl()+'/'+userId+'?token='+config.getToken();
    }
    _getWsUrl(){
        let that=this;
        that._initWsUrl();//每次get之前都执行initUrl，获取最新的token和userId
        return that.wsUrl;
    }

    /**
     *
     * @param data.wsCode 根据不同code调用不同方法
     * @returns {*}
     */
    refresh(data){
        let that=this;
        let func=that.khcWSFuncMap.get(data.wsCode)
        if(func){
            return func(data)
        }else{
            if(config.getConfigJson().logLevel=='debug') console.log( '未实现的ws代码：'+data.wsCode)
        }
    }
}
export {websocket}