//@ sourceURL=to-medicine.js
//待取药队列
var currentList = null;
//过号名单队列
var pastList = null;
//临时待取药队列
var tempCurrentList = null;
//临时过号名单
var tempPastList = null;
//待取药队列是否已经加载完成
var currentListHadDone = true;
//过号名单队列是否已经加载完成
var pastListHadDone = true;
//药房编号
var groupNo = null;
$(function () {
    $(".selectpicker").selectpicker({
        dropuAuto: false
    });

    var yesNo = '<option value="71">门诊西药房</option><option value="81">门诊中药房</option><option value="82">颗粒剂药房</option>';
    $('#fyClass').html(yesNo);
    $('#fyClass').selectpicker('refresh');
    $("#editModal").modal("show");
    //
    // //查询已经设置好的结果，回显
    // $.ajax({
    //     type: "GET",
    //     url: '/thmz/getConfigByKey?key=weekend_fee',
    //     dataType: "json",
    //     headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
    //     success: function (res) {
    //         if (res == '401' || res == 401) {
    //             window.location.href = '/thmz/login/view'
    //             return;
    //         }
    //         if(res.data.configValue=='0'){
    //             setSwitchery(false);
    //         }else {
    //             setSwitchery(true);
    //         }
    //     }
    // });
    //进入页面就加载一次
    CurentTime();
    intClock();
    //每秒获取当前时间
    setInterval(CurentTime, 1000);
    //10秒刷新一次队列里面的数据，应对数据很多，一页展示不完的情况
    setInterval(refeshTable, 10000);
    //三十秒从后台拉一次数据
    setInterval(getTableDate, 30000);
    //设置页面宽度
    setHeightForTable();
    $(window).resize(function () {
        //设置页面宽度
        setHeightForTable();
    });

    $(document).keyup(function(event){
        if(event.keyCode ==13){
            initTable();
        }
    });

});


/**
 * 设置页面宽度
 */
function setHeightForTable() {
    var height = $(window).height() - 320;
    var realHeigt = height / 7;
    if (realHeigt < 100) {
        realHeigt = 100;
    }
    $("#tableList tr").css("height", realHeigt + "px");
}


/**
 * 取当前时间 格式 yyyy年mm月dd日 hh:mm:ss weekday
 * @constructor
 */
function CurentTime() {
    var now = new Date();
    var year = now.getFullYear();       //年
    var month = now.getMonth() + 1;     //月
    var day = now.getDate();            //日
    var hh = now.getHours();            //时
    var mm = now.getMinutes();          //分
    // var ss=now.getSeconds();            //秒
    var weekday = new Array(7)			//周
    weekday[0] = "星期日"
    weekday[1] = "星期一"
    weekday[2] = "星期二"
    weekday[3] = "星期三"
    weekday[4] = "星期四"
    weekday[5] = "星期五"
    weekday[6] = "星期六"
    var date = year + "年";
    if (month < 10) date += "0";
    date += month + "月";
    if (day < 10) date += "0";
    date += day + "日 ";
    date += "  " + weekday[now.getDay()];
    $("#dateNow").html(date);
    var time = "";
    if (hh < 10) time += "0";
    time += hh + ":";
    if (mm < 10) time += '0';
    time += mm;
    $("#timeNow").html(time)
}


/**
 * 初始化时钟
 */
function intClock() {
    var audioElement = new Audio("");
    //clock plugin constructor
    $('#myclock').thooClock({
        //size:$(document).height()/1.4,
        size: 80,
        onAlarm: function () {
            //all that happens onAlarm
            //$('#alarm1').show();
            // alarmBackground(0);
            //audio element just for alarm sound
            document.body.appendChild(audioElement);
            var canPlayType = audioElement.canPlayType("audio/ogg");
            if (canPlayType.match(/maybe|probably/i)) {
                audioElement.src = 'alarm.ogg';
            } else {
                audioElement.src = 'alarm.mp3';
            }
            // erst abspielen wenn genug vom mp3 geladen wurde
            audioElement.addEventListener('canplay', function () {
                audioElement.loop = true;
                audioElement.play();
            }, false);
        },
        showNumerals: true,
        brandText: 'THOOYORK',
        brandText2: 'Germany',
        onEverySecond: function () {
            //callback that should be fired every second
        },
        //alarmTime:'15:10',
        offAlarm: function () {
            //$('#alarm1').hide();
            audioElement.pause();
            clearTimeout(intVal);
            $('body').css('background-color', '#FCFCFC');
        }
    });
}


/**
 * 实例化列表
 */
function initTable() {
    var winNo = $("#winNo").val();
    groupNo = $("#fyClass").val();
    if (groupNo == null || groupNo == "") {
        alert("未选择药房！");
        return;
    }
    if (winNo == null || winNo == "") {
        alert("窗口号未录入！");
        return;
    }
    var yfName = "门诊西药房";
    if (groupNo == 81) {
        yfName = "门诊中药房";
    } else if (groupNo == 82) {
        yfName = "颗粒剂药房";
    }
    $("#yfName").html(yfName);
    $("#winNum").text(winNo);
    $("#editModal").modal("hide");
    getTableDate();
}


/**
 * 获取后台最新数据
 */
function getTableDate() {
    //如果过号列表还没有加载完，不发起新的请求
    if (!pastListHadDone) {
        return;
    }
    //如果等待取药列表还没有加载完，不发起新的请求
    if (!currentListHadDone) {
        return;
    }
    $.ajax({
        type: "GET",
        contentType: "application/json;charset=UTF-8",
        url: "/thmz/getToMedicine?groupNo=" + groupNo,
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        dataType: 'json',
        success: function (result) {
            if (result == '401' || result == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (result.code == 0) {
                pastList = result.pastList;
                currentList = result.currentList;
                //深度拷贝数组
                tempPastList = $.extend(true, [], pastList);
                tempCurrentList = $.extend(true, [], currentList);
                if (currentList != null && currentList.length > 0) {
                    var rightPerson = currentList[0];
                    $("#rightPerson").text(rightPerson == null ? "" : rightPerson);
                    //重置标志
                    currentListHadDone = false;
                } else {
                    //重置标志
                    currentListHadDone = true;
                    $("#rightPerson").text("");
                }

                if (pastList == null || pastList.length == 0) {
                    pastListHadDone = true;
                } else {
                    //重置标志
                    pastListHadDone = false;
                }
                refeshTable();
            } else {
                errorMesage(result);
            }
        }
    });
}

/**
 * 刷新列表
 */
function refeshTable() {
    //清空表格
    clear();
    for (var i = 1; i < 7; i++) {
        if (tempPastList == null || tempPastList.length == 0) {
            break;
        }
        //当遍历完成而且总长度小于等于6 时，不需要轮询
        if (pastListHadDone && pastList.length <= 6) {
            break;
        }
        //删除并返回数组的第一个元素
        var name = tempPastList.shift();
        $("#past" + i).text(name);
        if (tempPastList.length == 0) {
            pastListHadDone = true;
            //如果待取药列表也遍历完成，将过号列表置空,否责重新遍历过号列表
            if (currentListHadDone) {
                tempPastList == null;
            } else {
                //深度拷贝数组
                tempPastList = $.extend(true, [], pastList);
            }
        }
    }
    for (var i = 1; i < 13; i++) {
        if (tempCurrentList == null || tempCurrentList.length == 0) {
            break;
        }
        //当遍历完成而且总长度小于等于12 时，不需要轮询
        if (currentListHadDone && currentList.length <= 12) {
            break;
        }
        //删除并返回数组的第一个元素
        var name = tempCurrentList.shift();
        $("#current" + i).text(name);
        if (tempCurrentList.length == 0) {
            currentListHadDone = true;
            //如果过号列表也遍历完成，将待取药列表置空,否责重新遍历待取药列表
            if (pastListHadDone) {
                tempCurrentList == null;
            } else {
                //深度拷贝数组
                tempCurrentList = $.extend(true, [], currentList);
            }
        }
    }
}


/**
 * 清空表格
 */
function clear() {
    //重新加载的数据，清空
    if ((pastList.length <= 6 && !pastListHadDone) || pastList.length==0) {
        for (var i = 1; i < 7; i++) {
            $("#past" + i).text("");
        }
    }
    //重新加载的数据，清空
    if ((currentList.length <= 12 && !currentListHadDone) || currentList.length==0) {
        for (var i = 1; i < 13; i++) {
            $("#current" + i).text("");
        }
    }

}

// /**
//  * 全屏方法
//  */
// function fullscreenOwn(){
//     var  elem=document.body;
//     if(elem.webkitRequestFullScreen){
//         elem.webkitRequestFullScreen();
//     }else if(elem.mozRequestFullScreen){
//         elem.mozRequestFullScreen();
//     }else if(elem.requestFullScreen){
//         elem.requestFullscreen();
//     }else{
//         //浏览器不支持全屏API或已被禁用
//     }
// }
//
// /**
//  * 退出全屏
//  */
// function exitFullscreen(){
//     var elem=document;
//     if(elem.webkitCancelFullScreen){
//         elem.webkitCancelFullScreen();
//     }else if(elem.mozCancelFullScreen){
//         elem.mozCancelFullScreen();
//     }else if(elem.cancelFullScreen){
//         elem.cancelFullScreen();
//     }else if(elem.exitFullscreen){
//         elem.exitFullscreen();
//     }else{
//         //浏览器不支持全屏API或已被禁用
//     }
// }
//
//
//
// var intVal;
//





