
// import { ipcApiRoute, specialIpcRoute } from "@/api/main";

// import vueMain from '../main'
import { ipc } from '@/utils/ipcRenderer';
import { ipcApiRoute } from '@/api/main';
import { webSocketUrl } from '@/utils/api'
var isOpen = false;
var authKey = ''
var socket = undefined
var socketHeartTimer = undefined
// 定时更新设备信息
var socketHeartTimer2 = undefined
// 用变量标记是否更新设备信息
var socketUpdateInfoCount = 0;
// 设备信息
var deviceInfo = {
    volume: 0,
    hostname: ''

};
var configJSON = null;
// 发送设备信息的间隔时间 s
const timerInterval = 10;
//屏幕设备类型IcbcDeviceType,1反诈屏  2互动屏  3弧形屏  4科技之眼  5光电玻璃  6 logo 设备类型 7 VR眼睛电脑
function initWebSocket(config) {
    configJSON = config;
    
    const wsUri = webSocketUrl+'/client/websocketServer' + '?deviceKey=' + configJSON.deviceId;
    // const wsUri = 'ws://127.0.0.1:8080/resource/websocket' + '?deviceKey=' + e;
    close();
    socket = new WebSocket(wsUri)//这里面的this都指向vue
    socket.onerror = webSocketOnError;
    socket.onmessage = webSocketOnMessage;
    socket.onclose = closeWebsocket;
    socket.onopen = openWebSocket;

    if (socketHeartTimer != undefined) {
        clearInterval(socketHeartTimer);
    }
    if (socketHeartTimer2 != undefined){
        clearInterval(socketHeartTimer2);
    }

    socketHeartTimer = setInterval(() => {
        if (isOpen == false) {
            console.log('重新连接' + isOpen)
            initWebSocket(configJSON);
        } else {
            console.log('socket 心跳' + isOpen);
            const msg = {
                type: "heartbeat",// 心跳
                content: "心跳",
                deviceKey: configJSON.deviceId,
                deviceType: configJSON.deviceType,
            }
            socket.send(JSON.stringify(msg));
        }

    }, 6000);

    
    socketHeartTimer2 =  setInterval(() => {
        ipc.invoke(ipcApiRoute.getOSMessage, {}).then(res => {
            // 判断数据不相同 提前更新掉
            if ( deviceInfo.volume != res.volume || deviceInfo.hostname != res.hostname){
                deviceInfo = res;
                sendDeviceInfo();
                socketUpdateInfoCount = 0;
                return;
            }
            deviceInfo = res;
            socketUpdateInfoCount = socketUpdateInfoCount+1;
            if (socketUpdateInfoCount >= timerInterval){
                sendDeviceInfo();
                socketUpdateInfoCount = 0;
            }
            
        }) 
    }, 1000);
    
    

}
// 发送设备信息
function sendDeviceInfo(){
    const msg = {
        type: "device_info_update",// 设备信息更新
        content: deviceInfo,
        deviceKey: configJSON.deviceId,
        deviceType: configJSON.deviceType,
        deptId: configJSON.deptId
    }
    socket.send(JSON.stringify(msg));
}

function webSocketOnError(e) {
    // ElementUI.Notification({
    //     title: '',
    //     message: "WebSocket连接发生错误" + e,
    //     type: 'error',
    //     duration: 0,
    // });

}
// socket 连接打开
function openWebSocket(e) {
    console.log('socket 连接')
    isOpen = true;
}
function webSocketOnMessage(e) {
    const data = JSON.parse(e.data);
    console.log('收到socket 消息')
    console.log(data);
    // 抛出消息, 全局控制消息直接处理
    switch(data.type){
        case 'heartbeat':
            return;
        case 'serve_heartbeat':
            break
        case 'device_shutdown':
            ipc.invoke(ipcApiRoute.deviceShutdown, {}).then(res => {

            })
            return;
        case 'device_restart':
            ipc.invoke(ipcApiRoute.deviceRestart, {}).then(res => {

            })
            return;
        case 'device_play_video':
            break;
        case 'device_update_data':
            break;
        case 'scan_qr_game_start':
            break;
        case 'game_start_ok':
            break;
        case 'game_progress':
            break;
        case 'game_result_post':
            break;
        case 'device_info_update':
            break;
        case 'device_volume_update':
            console.log("声音设置")
            console.log(data.content);
            ipc.invoke(ipcApiRoute.deviceLoudness, {value:data.content}).then(res => {
                console.log('返回声音设置结果'+res);
            })
            return;
        default:
            break
    }
    
    window.dispatchEvent(new CustomEvent('onMessageWS', {
        detail: {
            data: data
        }
    }))

    // var event = document.createEvent("HTMLEvents");
    // event.initEvent("onMessageWS", true, true);
    // window.dispatchEvent(event);


}
// 关闭websiocket
function closeWebsocket() {
    console.log('连接已关闭...')

    // clearTimeout(socketHeartTimer);
    isOpen = false;
}
function close() {

    if (socket != undefined) {
        socket.close() // 关闭 websocket
        socket.onclose = function (e) {
            console.log(e)//监听关闭事件
            console.log('关闭')
        }
    }
    socket = undefined;
    isOpen = false;

}
function webSocketSend(agentData) {
    socket.send(agentData);
}
export default {
    initWebSocket, close, webSocketSend
}
