function getRandomString(len = 10) {
    const chars =
        "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678"; /** **默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    const maxPos = chars.length;
    let randomString = "";
    for (let i = 0; i < len; i++) {
        randomString += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return randomString;
}
class InitWebSocketClass {
    // console.log(1111);
    // 为了防止user获取不到，从外面调用ras/user/info接口传入userCode，不要从cookie读，否则可能第一次出现读取不到的状况
    constructor(
        userCode = localStorage.getItem("userId"),
        token = localStorage.getItem("token"),
        options,
        socketCode = getRandomString()
    ) {
        this.websocket = null; // 初始化websocket
        this.socketCode = socketCode;
        this.defaults = {
            // 默认配置，可以通过option覆盖
            protocol: defaultConfig.protocol, // 协议
            letLoginIp: defaultConfig.loginIp, // 环境配置
            letPort: defaultConfig.port, // 端口配置
            letUserCode: userCode, // 用户code
            letUserName: "system", // 环境登陆账号
            wsUri: "ws://localhost:1234",
            token: token, // token
            getVersion: null, // option里面的获取版本信息的回调函数通知
            loginSuccess: null, // 登陆成功会调通知
            errorInfo: null, // 异常回调通知
            onCreateVideoSuccess: false, // 客户端被拉起通知
            oncheckSocket: null,
            onCreateGroupChatSuccess: null, // 群聊创建成功通知
            onSocketBackInfos: null // 客户端返回信息
        };
        this.settings = Object.assign({}, this.defaults, options); // 覆盖默认配置操作
        this.websocketOnerror = false;
        this.ClientLocalVersion = 0; // 获取本地版本号
        this.timeId = null;
    }
    getSettings() {
        return this.settings;
    }
    webSocketSend(data) {
        // console.log(data);
        // console.log(this.websocket);
        if (this.websocket == null) {
            return;
        }
        if (this.websocket.readyState === 1) {
            // console.log(this.websocket.readyState)
            this.websocket.send(data);
        } else {
            setTimeout(() => {
                this.webSocketSend(data);
            }, 1000);
        }
    }

    initWebSocket() {
        // 初始化WebSocket
        return new Promise((resolve, reject) => {
            try {
                if (typeof WebSocket === "function") {
                    this.WebSocket = WebSocket;
                }
                if (this.websocket && this.websocket.readyState === 1) {
                    this.websocket.close();
                }
                const settings = this.settings;
                window.initWebSocket = this.websocket = new WebSocket(
                    settings.wsUri
                );
                this.websocket.onopen = () => {
                    this.login();
                };
                this.websocket.onclose = () => {
                    // DISCONNECTED
                };
                this.websocket.onmessage = evt => {
                    // console.log(evt);
                    if (evt && evt.data) {
                        if (evt.data === "client is runing!") {
                            // 用隐藏方法，只断连接去拉视频后的返回
                            this.startNotice();
                            this.settings.loginSuccess &&
                                this.settings.loginSuccess("success");
                            resolve("success");
                            return;
                        }
                        const data = JSON.parse(evt.data);
                        // console.log(data);
                        if (
                            data &&
                            data.params &&
                            data.params.loginResult === 0
                        ) {
                            this.startNotice(); // 去获取本地版本号
                            this.settings.loginSuccess &&
                                this.settings.loginSuccess("success");
                            resolve("success");
                        } else if (
                            data &&
                            data.method === "notifyClientLocalVersion"
                        ) {
                            this.ClientLocalVersion = Number(
                                JSON.parse(evt.data).params.clientVersion
                            );
                            this.settings.getVersion &&
                                this.settings.getVersion(
                                    Number(
                                        JSON.parse(evt.data).params
                                        .clientVersion
                                    )
                                );
                        } else if (
                            data &&
                            data.method === "createVideoDialogReuslt"
                        ) {
                            // 客户端被拉起通知
                            const createVideoReuslt = Number(
                                JSON.parse(evt.data).params.result
                            );
                            const flag = createVideoReuslt === 0;
                            this.settings.onCreateVideoSuccess &&
                                this.settings.onCreateVideoSuccess(flag);
                        } else if (data && data.method === "runinfo") {
                            // 运行异常状态通知
                            this.settings.errorInfo &&
                                this.settings.errorInfo(data.params.info);
                        } else {
                            //
                        }
                        // 重点:统一分发客户端ws消息
                        this.settings.onSocketBackInfos &&
                            this.settings.onSocketBackInfos(data);
                    }
                };
                this.websocket.onerror = () => {
                    this.websocketOnerror = true;
                    reject("error");
                };
            } catch (exception) {
                // this.debug('ERROR: ' + exception);
            }
        });
    }
    login() {
        this.checkSocket();
        const params = {
            loginIp: this.settings.letLoginIp,
            method: "login",
            params: {
                loginPort: 8314,
                protocol: this.settings.protocol,
                token: this.settings.token,
                userName: this.settings.letUserName
            },
            userCode: this.settings.letUserCode,
            socketCode: this.socketCode,
            webTitle: document.title // 视频存在的tab业标题不能重复
        };
        console.log(params);
        this.webSocketSend(JSON.stringify(params));
        this.timer();
    }
    UpdateWebTitle() {
            //切换路由的的时候需要调用此方法更新页面标题。路由标题名不能重复。
            // this.checkSocket();
            const params = {
                loginIp: this.settings.letLoginIp,
                method: "UpdateWebTitle",
                params: {
                    webTitle: document.title
                },
                userCode: this.settings.letUserCode,
                socketCode: this.socketCode
            };
            this.webSocketSend(JSON.stringify(params));
        }
        // 客户端心跳
    timer() {
            this.timeId = setInterval(() => {
                const params = {
                    loginIp: this.settings.letLoginIp,
                    method: "heartbeat",
                    userCode: this.settings.letUserCode,
                    socketCode: this.socketCode
                };
                if (this.websocket) {
                    this.webSocketSend(JSON.stringify(params));
                }
            }, 10000);
        }
        // 停止socket连接
    stopWebSocket() {
            if (this.websocket) {
                this.websocket.close();
            }
            this.websocket = null;
            this.timeId && clearInterval(this.timeId);
        }
        //检查socket状态，通过oncheckSocket回调参数，可以判断本地有木有安装客户端
    checkSocket() {
            if (this.websocket != null) {
                let stateStr;
                // console.log(this.websocket.readyState);
                switch (this.websocket.readyState) {
                    case 0:
                        {
                            stateStr = "CONNECTING";
                            break;
                        }
                    case 1:
                        {
                            stateStr = "OPEN";
                            break;
                        }
                    case 2:
                        {
                            stateStr = "CLOSING";
                            break;
                        }
                    case 3:
                        {
                            stateStr = "CLOSED";
                            break;
                        }
                    default:
                        {
                            stateStr = "UNKNOW";
                            break;
                        }
                }
                this.settings.oncheckSocket &&
                    this.settings.oncheckSocket(stateStr === "OPEN");
            } else {
                //
            }
        }
        //获取本地客户端版本号
    startNotice() {
            const params = JSON.stringify({
                loginIp: this.settings.letLoginIp,
                method: "getClientVersion",
                userCode: this.settings.letUserCode,
                socketCode: this.socketCode
            });
            this.webSocketSend(params);
        }
        // 升级客户端方法
    setClientDownInfo() {
        const origin = location.origin;
        const params = JSON.stringify({
            loginIp: this.settings.letLoginIp,
            method: "setClientDownInfo",
            params: {
                newClientVersion: this.ClientLocalVersion, // 获取的本地版本号
                clientDownUrl: `${origin}/data/VSL/DSSEnterpriseClient/DSS_LightWeight_Client.zip` // 客户端在服务器上的地址,本地调试放开下面你的getCookie("ip")
                    // "clientDownUrl": `http://${getCookie("ip")}:8314/TheNextWebApp/resources/DSS_LightWeight_Client.zip` // 客户端在服务器上的地址文件
            },
            userCode: this.settings.letUserCode,
            socketCode: this.socketCode
        });
        this.webSocketSend(params);
    }
    closeClient() {
            const params = {
                loginIp: this.settings.letLoginIp,
                method: "logout",
                userCode: this.settings.letUserCode,
                socketCode: this.socketCode
            };
            this.webSocketSend(JSON.stringify(params));
            this.stopWebSocket();
            this.websocket = null;
        }
        // 通用方法第三方传方法名和参数体
    commonUse(method, paramsObj) {
            const params = JSON.stringify({
                loginIp: this.settings.letLoginIp,
                method: method,
                userCode: this.settings.letUserCode,
                params: paramsObj,
                socketCode: this.socketCode
            });
            this.webSocketSend(params);
        }
        // 创建群聊界面
    openCreateGroupChatDlg() {
            const params = JSON.stringify({
                loginIp: this.settings.letLoginIp,
                method: "openCreateGroupChatDlg",
                userCode: this.settings.letUserCode,
                socketCode: this.socketCode
            });
            this.webSocketSend(params);
        }
        // 创建群聊会商-邀请一个用户进去会商
    createGroupChat(obj) {
            const params = JSON.stringify({
                loginIp: this.settings.letLoginIp,
                method: "createGroupChat",
                userCode: this.settings.letUserCode,
                socketCode: this.socketCode,
                params: {
                    chatName: obj.chatName,
                    bOpenDirect: obj.bOpenDirect, // 是否打开音视频通话标志，true 创建成功后打开音视频通话，false 创建成功后不打开音视频通话
                    memberInfo: [
                        // 成员信息
                        {
                            memberId: obj.memberId, // 成员id
                            memberName: obj.memberName, // 成员名称
                            regionId: obj.regionId, // 成员的pass域id
                            memberType: obj.memberType, // 成员类型，Integer ,1 单兵；2 普通电话；3 对讲机；4 app|客户端；6 可是话机； 7 汇接话机（PSTN、手机号码等）； 8 车载；9 无人机喊话云台； 10 无人机地面站对讲平台； 11 ipc; 12 NVR
                            memberCode: obj.memberCode, // 成员设备编码
                            memberNumber: obj.memberNumber // 成员号码
                        }
                    ]
                }
            });
            this.webSocketSend(params);
        }
        // 打开客户端指定模块
    openClientModule(moduleID) {
        const params = JSON.stringify({
            loginIp: this.settings.letLoginIp,
            method: "openClientModule",
            userCode: this.settings.letUserCode,
            params: {
                moduleID: moduleID // 模块ID,0 视频监控；1 录像回放；2 视频上墙；3 下载中心
            },
            socketCode: this.socketCode
        });
        this.webSocketSend(params);
    }
}

window.InitWebSocketClass = InitWebSocketClass;