//@ sourceURL=schedule-of-medical.js
var checkState = '';

$(function () {
    daterangepickerWithIdAndCallBack('sourceRange', dateChange);
    //initList();
    //  initFeeTable();
    //重置查询参数
    $('#btn_clean').click(function () {
        cleanParams();
    });


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

    $("#btn_add").click(function (t) {
        $("#editModal").modal();
        $("#classTitle").text("新增");
        clearInput();
        $("#roomNum").val(1);
        $("#totalNum").val(1);
        $("#totalNumDiv").removeClass("hide").addClass("in");
    });


    $("#saveEdit").click(function (t) {
        saveScheduleOfMedical();
    });




    $("#editDay").change(function (e) {
        var editDay = $("#editDay").val();
        if (editDay.length == 8 && editDay.indexOf("-") <= 0) {
            if (editDay.substring(4, 6) > 12) {
                new PNotify({
                    title: '错误提示',
                    text: '号表日期错误,月份不能大于12',
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
                $("#editDay").val(null);
                return;
            }
            if (editDay.substring(6) > 31) {
                new PNotify({
                    title: '错误提示',
                    text: '号表日期错误,天数不能大于31',
                    type: 'error',
                    hide: true,
                    styling: 'bootstrap3'
                });
                $("#editDay").val(null);
                return;
            }
            editDay = editDay.substring(0, 4) + "-" + editDay.substring(4, 6) + "-" + editDay.substring(6);
            $("#editDay").val(editDay);
        }
        var dateFormat = /^(\d{4})-(\d{2})-(\d{2})$/;
        if (!dateFormat.test(editDay)) {
            new PNotify({
                title: '错误提示',
                text: '号表日期错误',
                type: 'error',
                hide: true,
                styling: 'bootstrap3'
            });
        }
        var arr = editDay.split("-");
        if (!checkDate(arr[0], arr[1], arr[2])) {
            new PNotify({
                title: '错误提示',
                text: '表表日期错误',
                type: 'error',
                hide: true,
                styling: 'bootstrap3'
            });
        }
    });
    initFullDeptSelect();



    $("#beginTime").change(function (e) {
        var beginTime = $("#beginTime").val();
        if (beginTime.length == 2 && beginTime.indexOf(":") <= 0) {
            beginTime+=":";
        }else if (beginTime.length == 2 && beginTime.indexOf(":") > 0) {
            beginTime="0"+beginTime;
        }
        $("#beginTime").val(beginTime);
    });


    $("#endTime").change(function (e) {
        var endTime = $("#endTime").val();
        if (endTime.length == 2 && endTime.indexOf(":") <= 0) {
            endTime+=":";
        }else if (beginTime.length == 2 && beginTime.indexOf(":") > 0) {
            endTime="0"+endTime;
        }
        $("#endTime").val(endTime);
    });



    $("#isNoticeRoomNum").change(function() {
        if($("#isNoticeRoomNum").is(':checked')){
            $("#roomNum").val(1);
        }else {
            $("#roomNum").val(null);
        }
    });


});

/**
 * 清空输入框
 */
function clearInput() {
    $("#editDay").val(null);
    $('#deptNo').selectpicker('val', null);
    $("#jcxm").val(null);
    $('#deptNo').selectpicker('refresh');
    $("#roomNum").val(null);
    $("#beginTime").val(null);
    $("#endTime").val(null);
    $("#requestId").val(null);
    $("#totalNum").val(null);
    $("#isNoticeRoomNum").prop('checked',true);
}






/**
 * 查询排班信息
 */
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-primary  btn-sm" onclick="updateRequest(' + row.id + ')">编辑</button>';
                        str += '<button type="button" class="btn btn-danger  btn-sm" onclick="removeRequest(' + row.id + ')">删除</button>';
                    }else  if(row.status==1){
                        str += '<button type="button" class="btn btn-success  btn-sm" onclick="confirmRequest(' + row.id + ')">确认</button>';
                        str += '<button type="button" class="btn btn-warning  btn-sm" onclick="rejectApplyRequest(' + row.id + ')">驳回</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',
                formatter: function (value, row, index) {
                    return value==0?"":value;
                }
            }, {
                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 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(),
        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 saveScheduleOfMedical() {
    var beginTime = $("#beginTime").val();
    var endTime = $("#endTime").val();
    if(beginTime==null || beginTime.length<5){
        new PNotify({
            title: '错误提示',
            text: "开始时间格式错误!",
            type: 'error',
            hide: false,
            styling: 'bootstrap3'
        });
        return;
    }
    if(endTime==null || endTime.length<5){
        new PNotify({
            title: '错误提示',
            text: "结束时间格式错误!",
            type: 'error',
            hide: false,
            styling: 'bootstrap3'
        });
        return;
    }
    $.ajax({
        type: "POST",
        url: '/thmz/saveScheduleOfMedical',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        data: JSON.stringify({"id":$("#requestId").val(),"recordDate":$("#editDay").val(),"depNo":$("#deptNo").val(),"jcxm":$("#jcxm option:selected").text(),"roomNum":$("#roomNum").val(),"beginTime":$("#beginTime").val(),"endTime":$("#endTime").val(),"totalNum":$("#totalNum").val()}),
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                $("#editModal").modal("hide");
                clearInput();
                $('#tb_table').bootstrapTable('refresh');
                successMesage(res);
            } else {
                errorMesage(res);
            }
        }
    });
}





/**
 * 列表中的科室列表
 */
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 initFullDeptSelect() {
    //科室列表
    $.ajax({
        type: "GET",
        url: '/thmz/allMzUnitCode',
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        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');
        }
    });
}


/**
 * 修改信息
 * @param id
 */
function updateRequest(id) {
    clearInput();
    $("#totalNumDiv").removeClass("in").addClass("hide");
    $("#requestId").val(id);
    $.ajax({
        type: "GET",
        url: '/thmz/getScheduleOfMedicalById?id=' + 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) {
                $("#classTitle").text("修改");
                $("#editDay").val(res.data.recordDate);
                $('#deptNo').selectpicker('val', res.data.depNo);
                $('#deptNo').selectpicker('refresh');
                if(res.data.roomNum!=null && res.data.roomNum>0){
                    $("#roomNum").val(res.data.roomNum);
                }else {
                    $("#isNoticeRoomNum").prop('checked',false);
                }
                $("#beginTime").val(res.data.beginTime);
                $("#endTime").val(res.data.endTime);
                $("#editModal").modal();
            }
        }
    });
}





/**
 * 删除信息
 * @param id
 */
function removeRequest(id) {
    if (!confirm("确认要删除当前操作的排班信息吗？")) {
        return;
    }
    $.ajax({
        type: "GET",
        url: '/thmz/removeScheduleOfMedicalById?id=' + 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) {
                initList();
                successMesage(res);
            }else {
                errorMesage(res);
            }
        }
    });
}





/**
 * 确认排班预约
 * @param id
 */
function confirmRequest(id) {
    $.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) {
                var confirmMessage="确定需要通过此次医技申请吗？";
                if(res.data.createDeptName!=null && res.data.createDeptName!=""){
                    confirmMessage+="\u000d 申请科室【"+res.data.createDeptName+"】";
                }
                if(res.data.createName!=null && res.data.createName!=""){
                    confirmMessage+="\u000d 申请人【"+res.data.createName+"】";
                }
                if(res.yshYjReq!=undefined && res.yshYjReq!=null){
                    if(res.yshYjReq.pname!=null && res.yshYjReq.pname!=""){
                        confirmMessage+="\u000d 病人姓名【"+res.yshYjReq.pname+"】";
                    }
                    if(res.yshYjReq.gender!=null && res.yshYjReq.gender!=""){
                        confirmMessage+="\u000d 病人性别【"+res.yshYjReq.gender+"】";
                    }
                    if(res.yshYjReq.inpatientNo!=null && res.yshYjReq.inpatientNo!=""){
                        confirmMessage+="\u000d 住院号【"+res.yshYjReq.inpatientNo+"】";
                    }
                }else if(res.mzYjReq!=undefined && res.mzYjReq!=null){
                    if(res.mzYjReq.patientName!=null && res.mzYjReq.patientName!=""){
                        confirmMessage+="\u000d 病人姓名【"+res.mzYjReq.patientName+"】";
                    }
                    if(res.gender!=null && res.gender!=""){
                        confirmMessage+="\u000d 病人性别【"+res.gender+"】";
                    }
                    if(res.mzYjReq.patientId!=null && res.mzYjReq.patientId!=""){
                        confirmMessage+="\u000d 门诊ID【"+res.mzYjReq.patientId+"】";
                    }
                }
                if(res.scheduleOfMedical.jcxm!=null && res.scheduleOfMedical.jcxm!=""){
                    confirmMessage+="\u000d 检查项目【"+res.scheduleOfMedical.jcxm+"】";
                }
                if(res.data.xdtjcjg!=null){
                    if(res.data.xdtjcjg==0){
                        confirmMessage+="\u000d 心电图检查结果【正常】";
                    }else if(res.data.xdtjcjg==1){
                        confirmMessage+="\u000d 心电图检查结果【不正常】";
                    }
                }
                if (!confirm(confirmMessage)) {
                    return;
                }
                $.ajax({
                    type: "POST",
                    url: '/thmz/confirmApplyScheduleOfMedical',
                    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);
                        }
                    }
                });
            }
        }
    });
}


/**
 * 驳回排班预约
 * @param id
 */
function rejectApplyRequest(id) {
    $.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) {
                var confirmMessage="确认要驳回当前操作的预约请求吗？";
                if(res.data.createDeptName!=null && res.data.createDeptName!=""){
                    confirmMessage+="\u000d 申请科室【"+res.data.createDeptName+"】";
                }
                if(res.data.createName!=null && res.data.createName!=""){
                    confirmMessage+="\u000d 申请人【"+res.data.createName+"】";
                }
                if(res.yshYjReq!=undefined && res.yshYjReq!=null){
                    if(res.yshYjReq.pname!=null && res.yshYjReq.pname!=""){
                        confirmMessage+="\u000d 病人姓名【"+res.yshYjReq.pname+"】";
                    }
                    if(res.yshYjReq.gender!=null && res.yshYjReq.gender!=""){
                        confirmMessage+="\u000d 病人性别【"+res.yshYjReq.gender+"】";
                    }
                    if(res.yshYjReq.inpatientNo!=null && res.yshYjReq.inpatientNo!=""){
                        confirmMessage+="\u000d 住院号【"+res.yshYjReq.inpatientNo+"】";
                    }
                }else if(res.mzYjReq!=undefined && res.mzYjReq!=null){
                    if(res.mzYjReq.patientName!=null && res.mzYjReq.patientName!=""){
                        confirmMessage+="\u000d 病人姓名【"+res.mzYjReq.patientName+"】";
                    }
                    if(res.gender!=null && res.gender!=""){
                        confirmMessage+="\u000d 病人性别【"+res.gender+"】";
                    }
                    if(res.mzYjReq.patientId!=null && res.mzYjReq.patientId!=""){
                        confirmMessage+="\u000d 门诊ID【"+res.mzYjReq.patientId+"】";
                    }
                }
                if(res.scheduleOfMedical.jcxm!=null && res.scheduleOfMedical.jcxm!=""){
                    confirmMessage+="\u000d 检查项目【"+res.scheduleOfMedical.jcxm+"】";
                }
                if(res.data.xdtjcjg!=null){
                    if(res.data.xdtjcjg==0){
                        confirmMessage+="\u000d 心电图检查结果【正常】";
                    }else if(res.data.xdtjcjg==1){
                        confirmMessage+="\u000d 心电图检查结果【不正常】";
                    }
                }
                if (!confirm(confirmMessage)) {
                    return;
                }
                $.ajax({
                    type: "POST",
                    url: '/thmz/rejectApplyScheduleOfMedical',
                    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 showJcxm() {
    //消化内镜中心
    if($("#deptNo").val()=="1020201"){
        $("#jcxmDiv").removeClass("hide").addClass("in");
    }else {
        $("#jcxmDiv").removeClass("in").addClass("hide");
    }
}


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