$(function () {
    //加载申请类型
    loadSelect(path + '/approve/loadType', 'applyTypeBorrowing', '');
})


var pageNumber;
var tabChecks;
//申请原因模板级联内容
$("#parentId").change(function(){
    $("#approveNotes").val("");
    var parentId = $("#parentId").val();
    if(parentId != '' && parentId != null){
        $.ajax({
            type:'get',
            url:path+'/annotationTemplate/getAnnoTemplateByParentId?parentId='+parentId,
            dataType:'json',
            success:function (data) {
                if(data != null){
                    $("#approveNotes").val(data);
                }
            }
        })
    }
})

//批量审批申请原因模板级联内容
$("#moreParentId").change(function(){
    $("#moreApproveNotes").val("");
    var parentId = $("#moreParentId").val();
    if(parentId != '' && parentId != null){
        $.ajax({
            type:'get',
            url:path+'/annotationTemplate/getAnnoTemplateByParentId?parentId='+parentId,
            dataType:'json',
            success:function (data) {
                if(data != null){
                    $("#moreApproveNotes").val(data);
                }
            }
        })
    }
})
$('#mytab').bootstrapTable({
    height:$(window).height,
    toolbar: '#toolbar',                //工具按钮用哪个容器
    striped: true,                      //是否显示行间隔色
    cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
    pagination: true,                   //是否显示分页（*）
    sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
    paginationPreText : '上一页',
    paginationNextText : '下一页',
    fixedColumns: true,
    fixedNumber: 4,
    pageNumber: 1,                       //初始化加载第一页，默认第一页
    pageSize: 5,                       //每页的记录行数（*）
    pageList: [5,10,15,20,30,50],//可供选择的每页的行数（*）
    height: $(window).height()-134,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
    columns:[
        {
            title:'全选',
            field:'select',
            checkbox:true,
            width:25,
            align:'center',
            valign:'middle'
        },
        {
            field: 'no',
            title: '序号',
            sortable: true,
            formatter: function (value, row, index) {
                //获取每页显示的数量
                var pageSize=$('#mytab').bootstrapTable('getOptions').pageSize;
                //获取当前是第几页
                var pageNumber=$('#mytab').bootstrapTable('getOptions').pageNumber;
                //返回序号，注意index是从0开始的，所以要加上1
                return pageSize * (pageNumber - 1) + index + 1;
            }
        },
        {
            title:'申请人',
            field:'applyer',
        },
        {
            title:'申请科室',
            field:'deptName',
        },
        {
            title:'申请日期',
            field:'applyTime',
        },
        {
            title:'有效日期',
            field:'effeTime',
        },
        {
            title:'有效天数',
            field:'effeDays',
        },
        {
            title:'审批状态',
            field:'approveState',
            formatter: function (value, row, index) {
                var returnState = row.returnState;
                var spanValue;
                if (returnState == '1') {
                    spanValue = '<p class="text-success">已归还</p>';
                    return spanValue;
                }
                if(value == '已过期'){
                    spanValue = '<p class="text-danger">已过期</p>';
                }else if(value == '待审批'){
                    spanValue = '<p style="color:grey">待审批</p>';
                }else if(value == '审核通过'){
                    spanValue = '<p class="text-success">审核通过</p>';
                }else if(value == '审核不通过'){
                    spanValue = '<p class="text-danger">审核不通过</p>';
                }
                return spanValue;
            }
        },
        {
            title:'姓名',
            field:'name',
        },
        {
            title:'病案号',
            field:'inpatientNo',
        },
        {
            title:'住院次数',
            field:'admissTimes',
        },
        {
            title:'出院日期',
            field:'disDate',
            formatter: crtTimeFtt
        },
        {
            title:'申请原因',
            field:'applyReason',
        },
        {
            title:'申请类型',
            field:'applyType',
        },
        {
            title:'审批时间',
            field:'approveTime',
        },
        {
            title:'审批人',
            field:'approver',
        },
        {
            title: '归还人',
            field: 'returnNameString',
        },
        {
            title: '归还时间',
            field: 'returnTime',
        },
        {
            title:'批注内容',
            field:'approveNotes',
        },
        {
            title:'操作',
            formatter: function(value,row,index){
                var editanddrop = '';
                var updateOper = row.updateOper;
                if(row.lockStatus == 0){
                    editanddrop += '<a type="button" href="'+path+'/commom/showRecord174?patientId='+row.patientId+'" class="btn btn-danger TableView btn-sm" onclick="showDetail('+row.patientId+')" target="_blank">查看详情</a>';
                }
                if(row.approveState == '待审批' && updateOper == 1 && row.lockStatus == 0){
                    editanddrop += '<button type="button" onclick="showApprove('+row.id+')" class="btn btn-sm btn-warning" data-toggle="modal" data-target="#myModal1">借阅审批</button>';
                }
                if(row.approveState != '待审批' && updateOper == 1 && row.lockStatus == 0){
                    editanddrop += '<button type="button" onclick="updateApprove('+row.id+')" class="btn btn-sm btn-primary"  data-toggle="modal" data-target="#myModal1">修改批注</button>';
                }
                return editanddrop;
            }
        }
    ],
    locale:'zh-CN',//中文支持,
    url:path+'/approve/getApproveManageList',//排序方式
    queryParams: function (params) {
        return{
            limit : params.limit, // 每页显示数量
            offset : params.offset, // SQL语句起始索引
            page : (params.offset / params.limit) + 1, //当前页码,
            applyer:$("#applyerSearch").val(),
            startTime1:$("#startTime1").val(),
            endTime1:$("#endTime1").val(),
            effeDays:$("#effeDaysSearch").val(),
            name:$("#searchName").val(),
            approveState:$("#searchApproveState").val(),
            startTime2:$("#startTime2").val(),
            endTime2:$("#endTime2").val(),
            approver:$("#approver").val()
        }
    },
    responseHandler:function(res){
        //在ajax获取到数据，渲染表格之前，修改数据源
        var nres = [];
        nres.push({total:res.total,rows:res.list});
        return nres[0];
    },
    onLoadSuccess:function(){
        $(".page-list").show();
        $(".fixed-table-body").css("overflow","auto");
    },
    //监听分页点击事件
    onPageChange: function(num, type) {
        pageNumber = num;
    },
    //选中单个复选框
    onCheck:function(row){
        var checks = $("#checks").val();
        $("#checks").val(checks+="'"+row.id + "',");
    },
    //取消单个复选框
    onUncheck:function(row){
        var checks = $("#checks").val();
        checks = checks.replace("'"+row.id + "',","");
        $("#checks").val(checks);
    },
    //全选
    onCheckAll:function(rows){
        $("#checks").val("");
        var checks = '';
        for(var i=0;i<rows.length;i++)
        {
            checks += "'"+rows[i].id + "',"
        }
        $("#checks").val(checks);
    },
    //全不选
    onUncheckAll: function (rows) {
        $("#checks").val("");
    }
})
function crtTimeFtt(val) {
    if (val != null) {
        var date = new Date(val);
        return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
    }
}
//查询按钮
function refreshTable(){
    $("#checks").val("");
    $('#mytab').bootstrapTable('refresh',{
        url : path+'/approve/getApproveManageList'
    })
}

//定义临时接收申请者的申请天数，用于判断是否申请天数有改动
var applyDay = 0;
var applyDate = '';
//借阅审批
function showApprove(id){
    //加载申请类型
    loadSelect(path+ '/approve/loadType','applyType','');
    //加载批注类别
    loadSelect(path+ '/approve/loadAnnoModle','parentId','');
    $("#parentId").val("");
    $("#approveNotes").val("");
    $.ajax({
        type:'get',
        url:path+'/approve/getApproveById',
        data:{id:id},
        dataType:'json',
        success:function(data){
            if(null != data){
                $("#approveId").val(data.id);
                $("#applyer").val(data.applyer);
                $("#effeTime").val(data.effeTime);
                $("#effeDays").val(data.effeDays);
                $("#applyType").val(data.applyType);
                $("#parentId").val(data.parentId);
                $("#applyReason").val(data.applyReason);
                $("#inpatientNo").val(data.inpatientNo);
                $("#admissTimes").val(data.admissTimes);
                $("#name").val(data.name);
                pickTime("effeTime",data.effeTime);
                applyDay = data.effeDays;
                applyDate = data.effeTime;
            }
        }
    })
}

//修改批注
function updateApprove(id){
    //加载申请类型
    loadSelect(path+ '/approve/loadType','applyType','');
    //加载批注类别
    loadSelect(path+ '/approve/loadAnnoModle','parentId','');
    $.ajax({
        type:'get',
        url:path+'/approve/getApproveById',
        data:{id:id},
        dataType:'json',
        success:function(data){
            if(null != data){
                $("#approveId").val(data.id);
                $("#applyer").val(data.applyer);
                $("#effeTime").val(data.effeTime);
                $("#effeDays").val(data.effeDays);
                $("#applyType").val(data.applyType);
                $("#parentId").val(data.annoParentId);
                $("#applyReason").val(data.applyReason);
                $("#inpatientNo").val(data.inpatientNo);
                $("#admissTimes").val(data.admissTimes);
                $("#name").val(data.name);
                $("#approveNotes").val(data.approveNotes);
                pickTime("effeTime",data.effeTime);
                applyDay = data.effeDays;
                applyDate = data.effeTime;
            }
        }
    })
}

//封装模态框保存公共方法，applyState:提交状态1保存未提交2已提交.msg:操作后提示信息
function add(flag){
    //判断是否有
    if(flag == 1){
        $("#approveState").val(1);
    }else if(flag == 2){
        $("#approveState").val(2);
    }
    //判断申请天数是否有修改
    var effeDays = $("#effeDays").val();
    if(applyDay != effeDays){
        //有改动弹窗确认是否修改有效日期
        $('.approveBtns').attr("data-toggle", "modal");
        $('.approveBtns').attr("data-target", "#myModal3");
    }else{
        //未改动直接提交
        saveMethod('y');
        $('.approveBtns').removeAttr("data-toggle", "modal");
        $('.approveBtns').removeAttr("data-target", "#myModal3");
    }
}

//封装提交审批方法
function saveMethod(flag){
    if(flag == 'n'){
        $("#effeTime").val(applyDate);
        $("#effeDays").val(applyDay);
    }
    var approveState = $("#approveState").val();
    $.ajax({
        type:'post',
        url:path+'/approve/updateApprove',
        data:$("#form1").serialize(),
        dataType:'json',
        success:function(data){
            if(data!=null && data.code == 0){
                if(approveState == 1){
                    toastr.success("批准成功!");
                }else{
                    toastr.success("驳回成功!");
                }
                refreshTable();
                $('#myModal1').modal('hide');
                $('#mytab').bootstrapTable('selectPage', pageNumber);
                $('#myModal3').modal('hide');
            }else{
                toastr.warning(data.msg);
            }
        }
    })
}

//批量审批
function addApprovesMore() {
    clearContent();
    tabChecks = getChecked();
    if (tabChecks.length > 0){
        //加载批注类别
        loadSelect(path+ '/approve/loadAnnoModle','moreParentId','');
        $('#addApprovesMore').attr("data-toggle", "modal");
        $('#addApprovesMore').attr("data-target", "#myModal2");
        $("#form2")[0].reset();
    } else {
        toastr.warning("至少选中一条!");
    }

}

//获取选中行
function getChecked(){
    tabChecks = "";
    var inpatientNoArray = new Array();
    var admissTimesArray = new Array();
    var nameArray = new Array();
    var applyerArray = new Array();
    var idlist = $('#mytab').bootstrapTable('getAllSelections');
    if(idlist.length > 0){
        for (var i = 0; i < idlist.length; i++) {
            tabChecks += idlist[i].id + ",";
            inpatientNoArray.push(idlist[i].inpatientNo);
            admissTimesArray.push(idlist[i].admissTimes);
            nameArray.push(idlist[i].name);
            applyerArray.push(idlist[i].applyer);
        }
        $("#checks").val(checks);
    }
    insertContent(inpatientNoArray, admissTimesArray, nameArray, applyerArray);
    if (null != tabChecks){
        tabChecks = tabChecks.substring(0,tabChecks.length-1);
    }
    return tabChecks;
}

//添加内容，tr td
function insertContent(inpatientNoArray, admissTimesArray, nameArray, applyerArray) {
    for (var i = 0 ; i < inpatientNoArray.length; i++){
        var tr = document.createElement("tr");
        var td1 = document.createElement("td");
        var td2 = document.createElement("td");
        var td3 = document.createElement("td");
        var td4 = document.createElement("td");
        td1.innerHTML = inpatientNoArray[i];
        td2.innerHTML = nameArray[i];
        td3.innerHTML = admissTimesArray[i];
        td4.innerHTML = applyerArray[i];
        tr.appendChild(td1);
        tr.appendChild(td2);
        tr.appendChild(td3);
        tr.appendChild(td4);
        document.getElementById("moreApproveBody").appendChild(tr);
    }
}

//清楚内容方法
function clearContent() {
    $('#addApprovesMore').removeAttr("data-toggle", "modal");
    $('#addApprovesMore').removeAttr("data-target", "#myModal2");
    var table = document.getElementById("moreApproveBody");
    var len = table.childNodes.length;
    for (var i = len - 1; i >= 0; i--) {
        table.removeChild(table.childNodes[i]);
    }
}

//批量审核
function moreAdd(flag){
    var approve = $("#moreApproveNotes").val();
    $.ajax({
        type:'post',
        url:path+'/approve/updateApproves',
        data:{ids:tabChecks,state:flag,note:approve},
        dataType:'json',
        success:function(data){
            if(data!=null && data.code == 0){
                if(flag == 1){
                    toastr.success("批准成功!");
                }else{
                    toastr.success("驳回成功!");
                }
                refreshTable();
                $('#myModal2').modal('hide');
                $('#mytab').bootstrapTable('selectPage', pageNumber);
            }else{
                toastr.warning(data.msg);
            }
        }
    })
}

//导出excel功能
function exportExcel(){
    var checks = $("#checks").val();
    if(checks != '') {
        checks = checks.substring(0, checks.length - 1);
        var url = path+"/approve/exportExcelApproveList?checks="+checks;
        window.location.href = url;
    }else{
        Common.confirm({
            title: "提示",
            message: "没有选中，您确定要按搜索栏条件导出?",
            operate: function (reselt) {
                if (reselt) {
                    var url = path+"/approve/exportExcelApproveList?startTime1="+$("#startTime1").val()+"&endTime1="+$("#endTime1").val()+"&startTime2="+$("#startTime2").val()+"&endTime2="+$("#endTime2").val()+"&name="+$("#searchName").val()+"&effeDays="+$("#effeDaysSearch").val()+"&applyer="+$("#applyerSearch").val()+"&approveState="+$("#searchApproveState").val()+"&approver="+$("#approver").val();
                    window.location.href = url;
                }
            }
        })
    }

}

$(function () {
	initDateInput(1);
	initDateInput(2);
})



//清空快速归还、快速借阅表单
function  emptyForm(){
    $('#barCodeReturnTable')[0].reset();
    $('#borrowingTable')[0].reset();
}


//清空快速归还、快速借阅表单
function  emptyBorrowingForm(){
    $('#borrowingTable')[0].reset();
}



//快速归还
function updateReturn() {
    var barCode = $("#barCodeReturn").val();
    var barCodeName = $("#barCodeName").val();
    $.ajax({
        type: 'post',
        url: path + '/applyDetails/updateReturn',
        data: {barCode: barCode,barCodeName:barCodeName},
        dataType: 'json',
        success: function (data) {
            if (data == 0) {
                refreshTable();
                document.getElementById("barCodeReturn").value = "";
                return toastr.warning("归还失败,查询不到病历!");
            }
            if (data == 2) {
                refreshTable();
                document.getElementById("barCodeReturn").value = "";
                return toastr.warning("查询不到需要归还病历!");
            }
            if (data == 1) {
                refreshTable();
                document.getElementById("barCodeReturn").value = "";
                return toastr.success("归还成功!");
            }
        }
    })
}




//监听回车立即搜索
//键盘回车查询
$("#barCodeReturnTable").bind("keypress", function (e) {
    // 兼容FF和IE和Opera
    var theEvent = e || window.event;
    var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code == 13) {
        e.preventDefault();
        //回车执行查询
        updateReturn();
    }
});


//快速借阅
function fastBorrowing() {
    var effeDays = $("#effeDaysBorrowing").val()
    var applyType = $("#applyTypeBorrowing").val()
    var applyReason = $("#applyReasonBorrowing").val()
    var barCode = $("#barCodeBorrowing").val()
    var applyUserName = $("#applyUserName").val()
    if (applyUserName == "") {
        return toastr.warning("申请人工号不能为空");
    }
    $.ajax({
        type: 'post',
        url: path + '/applyDetails/fastBorrowing',
        data: {
            effeDays: effeDays,
            applyType: applyType,
            applyReason: applyReason,
            barCode: barCode,
            userName: applyUserName
        },
        dataType: 'json',
        success: function (data) {
            if (data.code == 100) {
                document.getElementById("barCodeBorrowing").value = "";
                refreshTable();
                return toastr.warning(data.msg);
            }
            if (data.code == 200) {
                document.getElementById("barCodeBorrowing").value = "";
                refreshTable();
                return toastr.success(data.msg)
            }
        }
    })

}



//监听回车立即搜索
//键盘回车查询
$("#borrowingTable").bind("keypress", function (e) {
    // 兼容FF和IE和Opera
    var theEvent = e || window.event;
    var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code == 13) {
        e.preventDefault();
        //回车执行查询
        fastBorrowing();
    }
});
