//@ sourceURL=schedule-of-medical-apply.js
var LODOP; //声明为全局变量
//默认打印机下标
var printIndex = -1;
$(function () {
    daterangepickerWithIdAndCallBack('sourceRange', dateChange);
    //initList();
    //  initFeeTable();
    //重置查询参数
    $('#btn_clean').click(function () {
        cleanParams();
    });


    $(".selectpicker").selectpicker({
        dropuAuto: false
    });

    initDeptSelect();

    $("#saveEdit").click(function (t) {
        var scheduleId=$("#scheduleId").val();
        applyRequest(scheduleId);
    });
    setTimeout(function () {
        getLodop();
    }, 800);
});



/**
 * 查询排班信息
 */
function initList() {
    $('#tb_table').bootstrapTable("destroy");
    $('#tb_table').bootstrapTable({
        url: '/thmz/getScheduleOfMedical',         //请求后台的URL（*）
        method: 'post',                      //请求方式（*）
        toolbar: '#toolbar',                //工具按钮用哪个容器
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否显示分页（*）
        sortable: true,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        queryParams: queryParams,           //传递参数（*）
        sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 15,                       //每页的记录行数（*）
        pageList: [10, 15, 25, 50, 100],        //可供选择的每页的行数（*）
        search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
        strictSearch: true,
        showColumns: false,                  //是否显示所有的列
        showRefresh: false,                  //是否显示刷新按钮
        minimumCountColumns: 2,             //最少允许的列数
        clickToSelect: true,                //是否启用点击选中行
        uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
        showToggle: false,                    //是否显示详细视图和列表视图的切换按钮
        cardView: false,                    //是否显示详细视图
        detailView: false,
        //rowStyle:rowStyle,//通过自定义函数设置行样式
        ajaxOptions: {
            headers: {
                'Accept': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem("token")
            }
        },
        columns: [
            {
                title: '操作',
                field: 'op',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    var str = '';
                    if(row.status==0){
                        str = '<button type="button" class="btn btn-success  btn-sm" onclick="editModal(' + row.id + ',\''+row.depNo+'\')">预约</button>';
                    }else  if(row.status==1){
                        str = '<button type="button" class="btn btn-warning  btn-sm" onclick="cancelApplyRequest(' + row.id + ')">取消预约</button>';
                    }else  if(row.status==2){
                        if(row.depNo =="2020300" || row.depNo =="1020201"){
                            str = '<button type="button" class="btn btn-success  btn-sm" onclick="print(' + row.id + ',\''+row.recordDate+'\',\''+row.beginTime+'\',\''+row.endTime+'\','+row.roomNum+')">打印通知单</button>';
                        }
                    }
                    return [str].join('');
                }
            },
            {
                field: 'deptName',
                title: '科室名称',
                align: "center",
                valign: 'middle'
            },
            {
                field: 'jcxm',
                title: '检查项目',
                align: "center",
                valign: 'middle'
            }, {
                field: 'roomNum',
                title: '诊室',
                align: "center",
                valign: 'middle'
            }, {
                field: 'recordDate',
                title: '日期',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    return format(value, "yyyy-MM-dd");
                }
            }, {
                field: 'beginTime',
                title: '开始时间',
                align: "center",
                valign: 'middle'
            }, {
                field: 'endTime',
                title: '结束时间',
                align: "center",
                valign: 'middle'
            }, {
                field: 'status',
                title: '状态',
                align: "center",
                valign: 'middle',
                formatter: function (value, row, index) {
                    if(value==0){
                        return '<span style="color:#26c175">空闲</span>';
                    }
                    if(value==1){
                        return '<span style="color:#ff6b91">占用</span>';
                    }
                    if(value==2){
                        return '<span style="color:#6778ed">已预约</span>';
                    }
                }
            }
        ],
        onLoadSuccess: function () {

        },
        responseHandler: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var ress = eval(res);
            if (ress.code == -1) {
                if (ress.message != null && ress.message != '') {
                    new PNotify({
                        title: '错误提示',
                        text: ress.message,
                        type: 'error',
                        hide: true,
                        styling: 'bootstrap3'
                    });
                }
                return {
                    "total": 0,//总页数
                    "rows": {}   //数据
                };
            }
            return {
                "total": ress.count,//总页数
                "rows": ress.data   //数据
            };
        },
    });
}




/**
 * 打印排班预约
 * @param id
 */
function print(id,recordDate,beginTime,endTime,roomNum) {
    $.ajax({
        type: "GET",
        url: '/thmz/getApplyInfoByScheduleId?scheduleId=' + id,
        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.code == 0) {
                if(res.yshYjReq==null){
                    alert("该医技科室没有配置就诊通知单");
                }
                //超声影像科的指引单
                if("2020300"==res.scheduleOfMedical.depNo){
                    $("#pName").text(res.yshYjReq.pname);
                    $("#gender").text(res.yshYjReq.gender);
                    $("#inpatientNo").text(res.yshYjReq.inpatientNo);
                    $("#reqDept").text(res.yshYjReq.reqWardName);
                    $("#date").text(format(recordDate, "yyyy-MM-dd"));
                    $("#beginTime").text(beginTime);
                    $("#endTime").text(endTime);
                    if(roomNum<=0){
                        roomNum="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                    }
                    $("#roomNumPrint").html(roomNum);
                    if(res.groupNames!=null && res.groupNames.length>0){
                        var html='';
                        for(var i=0;i<res.groupNames.length;i++){
                            html+="<p style=\"margin:5px 0px\">"+(i+1)+"."+res.groupNames[i]+"</p>";
                        }
                        $("#project").html(html);
                    }
                    setPrint();
                    LODOP = getLodop();
                    LODOP.PRINT_INITA(6, 0, "210mm", "148mm", "超声影像科彩超检查告知书");
                    LODOP.SET_PRINT_STYLE("FontSize", 6); //字体大小
                    //设置默认打印机
                    LODOP.SET_PRINTER_INDEX(printIndex);
                    LODOP.SET_SHOW_MODE("BKIMG_WIDTH", "210mm");
                    LODOP.SET_SHOW_MODE("BKIMG_HEIGHT", "148mm");
                    var strStyle="<style>table{width: 96%;margin-top: 20px;margin-bottom: 10px;} table,td,th {border-width: 1px;border-style: solid;border-collapse: collapse}</style>";
                    LODOP.ADD_PRINT_HTM("0mm", "5mm", "200mm", "148mm",strStyle+ document.getElementById("report_table_1").innerHTML);
                    LODOP.PRINT();
                    //LODOP.PREVIEW();
                    return;
                }
                //消化内镜中心的指引单
                if("1020201"==res.scheduleOfMedical.depNo){
                    if("普通胃镜（胃、十二指肠镜）检查"==res.scheduleOfMedical.jcxm || "无痛胃镜"==res.scheduleOfMedical.jcxm){
                        $("#pName_wj").text(res.yshYjReq.pname);
                        $("#pName_wj_2").text(res.yshYjReq.pname);
                        setPrint();
                        LODOP = getLodop();
                        LODOP.PRINT_INITA(4, 0, "210mm", "148mm", "超声影像科彩超检查告知书");
                        LODOP.SET_PRINT_STYLE("FontSize", 4); //字体大小
                        //设置默认打印机
                        LODOP.SET_PRINTER_INDEX(printIndex);
                        LODOP.SET_SHOW_MODE("BKIMG_WIDTH", "210mm");
                        LODOP.SET_SHOW_MODE("BKIMG_HEIGHT", "148mm");
                        var strStyle="<style>table{width: 96%;margin-bottom: 10px;} table,td,th {border-width: 1px;border-style: solid;border-collapse: collapse}</style>";
                        LODOP.ADD_PRINT_HTM("0mm", "5mm", "200mm", "148mm",strStyle+ document.getElementById("report_table_2").innerHTML);
                        LODOP.NewPageA();
                        LODOP.ADD_PRINT_HTM("0mm", "5mm", "200mm", "148mm",strStyle+ document.getElementById("report_table_3").innerHTML);
                        LODOP.PRINT();
                        //LODOP.PREVIEW();
                        return;
                    }
                    if("普通肠镜"==res.scheduleOfMedical.jcxm || "无痛肠镜"==res.scheduleOfMedical.jcxm){
                        $("#pName_cj").text(res.yshYjReq.pname);
                        $("#pName_cj_4").text(res.yshYjReq.pname);
                        $("#pName_cj_5").text(res.yshYjReq.pname);
                        setPrint();
                        LODOP = getLodop();
                        LODOP.PRINT_INITA(4, 0, "210mm", "148mm", "超声影像科彩超检查告知书");
                        LODOP.SET_PRINT_STYLE("FontSize", 4); //字体大小
                        //设置默认打印机
                        LODOP.SET_PRINTER_INDEX(printIndex);
                        LODOP.SET_SHOW_MODE("BKIMG_WIDTH", "210mm");
                        LODOP.SET_SHOW_MODE("BKIMG_HEIGHT", "148mm");
                        var strStyle="<style>table{width: 96%;margin-top: 20px;margin-bottom: 10px;} table,td,th {border-width: 1px;border-style: solid;border-collapse: collapse}</style>";
                        LODOP.ADD_PRINT_HTM("0mm", "5mm", "200mm", "148mm",strStyle+ document.getElementById("report_table_4").innerHTML);
                        LODOP.NewPageA();
                        LODOP.ADD_PRINT_HTM("0mm", "5mm", "200mm", "148mm",strStyle+ document.getElementById("report_table_5").innerHTML);
                        LODOP.NewPageA();
                        LODOP.ADD_PRINT_HTM("0mm", "5mm", "200mm", "148mm",strStyle+ document.getElementById("report_table_6").innerHTML);
                        LODOP.PRINT();
                        //LODOP.PREVIEW();
                        return;
                    }

                }
                alert("当前医技科室没有配置通知单！");
            }
        }
    });
}

/**
 * 查询默认打印机
 */
function setPrint() {
    if (printIndex >= 0) {
        return;
    }
    $.ajax({
        type: "GET",
        url: '/thmz/getLastWindowsByCurrentUser',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        async: false,
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                printIndex = res.data.cgPrintIndex;
            } else {
                printIndex = -1;
            }
        }
    });
}


/**
 * 构建列表查询参数
 * @param params
 * @returns {{mzChargeDetail: {patientId: string | number | string[] | undefined | jQuery, warnDept: string | number | string[] | undefined | jQuery, doctorCode: string | number | string[] | undefined | jQuery, name: string | number | string[] | undefined | jQuery, payMark: number}, beginTime: Date, endTime: Date, pageSize: *, pageIndex: number}}
 */
function queryParams(params) {
    var rePortRangeArr = getSourceRangeArr();
    var temp = {
        beginDateParams: rePortRangeArr[0],
        endDateParams: rePortRangeArr[1],
        depNo: $("#unitCode").val(),
        roomNum: $("#roomNum").val(),
        pageSize: params.limit,
        offset: params.offset,
    };
    return temp;
};


/**
 * 获取源号表时间选择器的时间数组
 * @returns {string[]}
 */
function getSourceRangeArr() {
    var rePortRange = $('#sourceRange span').html();
    var rePortRangeArr = rePortRange.split(" - ");
    rePortRangeArr[0] = rePortRangeArr[0] + " 00:00:00"
    rePortRangeArr[1] = rePortRangeArr[1] + " 23:59:59"
    return rePortRangeArr;
}


/**
 * 清空查询条件
 */
function cleanParams() {
    $('#sourceRange span').html(moment().format('YYYY-MM-DD') + ' - ' + moment().format('YYYY-MM-DD'));
    $('#newRange span').html(moment().format('YYYY-MM-DD') + ' - ' + moment().format('YYYY-MM-DD'));
    $('#ampmParams').selectpicker('val', null);
    $('#ampmParams').selectpicker('refresh');
    $('#unitCode').selectpicker('val', null);
    $('#unitCode').selectpicker('refresh');
    initSourceList();
}



/**
 * 挂号列表中的科室列表
 */
function initDeptSelect() {
    var rePortRangeArr = getSourceRangeArr();
    //科室列表
    $.ajax({
        type: "POST",
        url: '/thmz/getDeptNos',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        data: JSON.stringify({
            "beginDateParams": rePortRangeArr[0],
            "endDateParams": rePortRangeArr[1]
        }),
        success: function (data) {
            if (data == '401' || data == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var html = '';
            $.each(data.data, function (commentIndex, comment) {
                html += '<option value="' + comment.code + '">' + comment.name + '(' + comment.pyCode + ')</option>';
            });
            $('#deptNo').empty();
            $('#deptNo').html(html);
            $('#deptNo').selectpicker('refresh');

            $('#unitCode').empty();
            $('#unitCode').html(html);
            $('#unitCode').selectpicker('refresh');
        }
    });
}


/**
 * 初始化诊室列表
 */
function initRoomSelect() {
    var rePortRangeArr = getSourceRangeArr();
    //科室列表
    $.ajax({
        type: "POST",
        url: '/thmz/getRoomNums',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        data: JSON.stringify({
            "depNo": $("#unitCode").val(),
            "beginDateParams": rePortRangeArr[0],
            "endDateParams": rePortRangeArr[1]
        }),
        success: function (data) {
            if (data == '401' || data == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var html = '';
            $.each(data.data, function (commentIndex, comment) {
                html += '<option value="' + comment + '">' + comment + '</option>';
            });
            $('#roomNum').empty();
            $('#roomNum').html(html);
            $('#roomNum').selectpicker('refresh');
        }
    });
}


/**
 * 打开预约窗口
 */
function editModal(scheduleId,depNo) {
    clearInput();
    $("#scheduleId").val(scheduleId);
    //消化内镜
    if("1020201"==depNo){
        $("#xdtjgDiv").removeClass("hide").addClass("in");
    }else {
        $("#xdtjgDiv").removeClass("in").addClass("hide");
    }
    $("#editModal").modal();
}




/**
 * 预约排班
 * @param id
 */
function applyRequest(id) {
    $.ajax({
        type: "POST",
        url: '/thmz/applyScheduleOfMedical',
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        data: JSON.stringify({
            "scheduleId": id,
            "xdtjcjg": $("input[name='xdtjg']:checked").val(),
            "actOrderNo": $("#actOrderNo").val(),
            "remark": $("#remark").val()
        }),
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                $('#tb_table').bootstrapTable("refresh");
                $("#editModal").modal("hide");
                clearInput();
                successMesage(res);
            } else {
                errorMesage(res);
            }
        }
    });
}


/**
 * 删除信息
 * @param id
 */
function cancelApplyRequest(id) {
    if (!confirm("确认要取消预约当前操作的排班信息吗？")) {
        return;
    }
    $.ajax({
        type: "POST",
        url: '/thmz/cancelApplyScheduleOfMedical',
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        data: JSON.stringify({
            "id": id
        }),
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                $('#tb_table').bootstrapTable("refresh");
                successMesage(res);
            } else {
                errorMesage(res);
            }
        }
    });
}





/**
 * 清空输入框
 */
function clearInput() {
    $("#scheduleId").val(null);
    $("#actOrderNo").val(null);
    $("[name='xdtjg']:eq(1)").attr("checked",true);
    $("#remark").val(null);
}




function dateChange() {
    initList();
    initDeptSelect();
}