//# sourceURL=socket-com.js
var prescriptionPrintWebsocket = null;
var lockReconnect = false; //避免ws重复连接
function openSocket(type) {
//判断当前浏览器是否支持WebSocket
    try {
        if ('WebSocket' in window) {
            prescriptionPrintWebsocket = new WebSocket("ws://" + window.location.host + "/thmz/prescriptionPrintSocket/" + type);
        } else {
            alert('当前浏览器不支持WebSocket，请更换浏览器');
        }
    }catch (e) {
        reconnect(type);
        console.log(e);
    }

//连接发生错误的回调方法
    prescriptionPrintWebsocket.onerror = function () {
        console.log(type+"连接prescriptionPrintSocket发生错误")
    };

//连接成功建立的回调方法
    prescriptionPrintWebsocket.onopen = function (event) {
        console.log(type+"连接prescriptionPrintSocket连接成功");
    };

//接收到消息的回调方法
    prescriptionPrintWebsocket.onmessage = function (event) {
        if (type == 'PY') {
            dispensingMessage(JSON.parse(event.data));
        }else if(type == 'FY'){
            sendMedicineMessage(JSON.parse(event.data));
        }else if(type == 'JH'){
            cellNumberMessage(JSON.parse(event.data));
        }
    };

//连接关闭的回调方法
    prescriptionPrintWebsocket.onclose = function (event) {
        console.log(type+"连接prescriptionPrintSocket连接关闭 code:"+event.code+",原因："+event.reason+"，是否正常关闭："+event.wasClean);
        if(event.code == '1001' || event.code == '1006'){//1001：终端离开, 可能因为服务端错误 1006：没有发送关闭帧
            reconnect(type);
        }
    };

//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        prescriptionPrintWebsocket.close();
    }
}

//重新连接
function reconnect(type) {
    if(lockReconnect) return;
    lockReconnect = true;
    //没连接上会一直重连，设置延迟避免请求过多
    setTimeout(function () {
        openSocket(type);
        lockReconnect = false;
    }, 500);
}

/**
 * 接收到配药完成消息回调方法
 * @param data
 */
function dispensingMessage(data) {
    var dispensingStatus = $("#dispensingStatusSearch").val();
    if (data.type == 'JF') {//来自缴费成功后的消息
        if (dispensingStatus == 0) {
            initTable();
        }
        if ($("#aotuPrint").is(':checked')) {//自动打印
            for (var i = 0; i < data.orderNos.length; i++) {
                printPrescription(data.patient_id, data.times,data.orderNos[i]);
            }
        }
    }
}

/**
 * 接收到发药完成消息回调方法
 * @param data
 */
function sendMedicineMessage(data){
    var confirmFlag = $("#confirmFlagSearch").val();
    if (data.type == 'PY' && confirmFlag == 0) {//来自配药处理成功后的消息,未发药列表刷新
        initTbTable();
    }
}

/**
 * 接收到叫号消息回调方法
 * @param data
 */
function cellNumberMessage(data){
    if(data.type == 'JF'){//来自缴费后的消息
        dispenseListClear(data);
        //添加正在配药列表
        dispenseList[dispenseList.length] = {name: data.name, patient_id: data.patient_id};
    }else if (data.type == 'PY') {//来自配药处理成功后的消息
        dispenseListClear(data);
        currentListClear(data);
        //添加等待取药列表
        currentList[currentList.length] = {name: data.name, patient_id: data.patient_id};
    } else if (data.type == 'JH') {//来自发药叫号的消息
        //判断正在取药是否为空，不为空将上一位放入过号队列
        if ($('#rightPerson').text() != "") {
            pastList[pastList.length] = {name: rightPerson.name, patient_id: rightPerson.patient_id};
        }
        //设置正在取药，清除过号队列
        $('#rightPerson').text(data.name);
        rightPerson = data;
        dispenseListClear(data);
        currentListClear(data);
        pastListClear(data);
        //生成语音
        $.ajax({
            type: "GET",
            url: 'http://webhis.thyy.cn:8706/voice/textToSpeech?text='+"请"+data.name+"到四号窗口取药",
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
            success: function (res) {
                if (res.code == 200) {
                    //播放后台生成的叫号语音
                    var mp3 = new Audio(res.data);
                    mp3.play();
                }
            }
        });
    } else if (data.type == 'FY') {//来自发药处理后的消息
        //将该用户叫号列表清除
        if(rightPerson != '' && rightPerson != null && rightPerson.patient_id == data.patient_id){
            rightPerson = null;
            $('#rightPerson').text("");
        }
        dispenseListClear(data);
        currentListClear(data);
        pastListClear(data);
    }
}