$(function () {
    //加载时间
    initDateInput(1);
    //加载时间
    initDateInput(2);
    //加载申请类型
    loadSelect(path + '/approve/loadType', 'searchApplyType', 'applyType');
    //加载申请类型
    loadSelect(path + '/approve/loadType', 'applyType5', '');
    //加载申请类型
    loadSelect(path + '/approve/loadType', 'applyTypeBorrowing', '');
})

var pageNumber;
//申请原因模板级联内容
$("#parentId").change(function () {
    $("#applyReason").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 && data != '') {
                    $("#applyReason").val(data);
                }
            }
        })
    }
})
/**
 * 加载数据表格
 */
$('#mytab').bootstrapTable({
    height: 5000,
    toolbar: '#toolbar',                //工具按钮用哪个容器
    striped: true,                      //是否显示行间隔色
    cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
    pagination: true,                   //是否显示分页（*）
    sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
    paginationPreText: '上一页',
    paginationNextText: '下一页',
    pageNumber: 1,                       //初始化加载第一页，默认第一页
    pageSize: 10,                       //每页的记录行数（*）
    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: 'applyTime',
        },
        {
            title: '有效日期',
            field: 'effeTime',
        },
        {
            title: '有效天数',
            field: 'effeDays',

        },
        {
            title: '姓名',
            field: 'name',
        },
        {
            title: '病案号',
            field: 'inpatientNo',
        },
        {
            title: '住院次数',
            field: 'admissTimes',
        },
        {
            title: '出院日期',
            field: 'disDate',
            formatter: crtTimeFtt
        },
        {
            title: '申请原因',
            field: 'applyReason',
        },
        {
            title: '申请类型',
            field: 'applyType',
        },
        {
            title: '申请状态',
            field: 'applyState',
            formatter: function (value, row, index) {
                var 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>';
                }
                return spanValue;
            }
        },
        {
            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: 'approveNotes',
        },
        {
            title: '归还人',
            field: 'returnNameString',
        },
        {
            title: '归还时间',
            field: 'returnTime',
        },
        {
            title: '操作',
            formatter: function (value, row, index) {
                var returnState = row.returnState;
                var editanddrop = '';
                var addOper = row.addOper;
                var updateOper = row.updateOper;
                var deleteOper = row.deleteOper;
                if (row.lockStatus == 0) {
                    if (row.applyState != '已提交') {
                        if (row.approveState != '已过期') {
                            //非已提交，提供申请，编辑，删除
                            if (addOper == 1) {
                                editanddrop += '<button type="button" onclick="updateThenAdd(' + row.id + ')" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#myModal3">提交申请</button>';
                            }
                        }
                        if (updateOper == 1) {
                            //非已提交，提供申请，编辑，删除
                            editanddrop += '<button type="button" onclick="updateApprove(' + row.id + ')" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#myModal3">编辑</button>';
                        }
                    }
                    if (row.applyState == '已提交') {
                        if (row.approveState == '审核通过' && returnState !== "1") {
                            editanddrop += '<a type="button" href="' + path + '/commom/showRecord174?patientId=' + row.patientId + '" class="btn btn-danger TableView btn-sm" target="_blank">查看详情</a>';
                        } else {
                            //已提交，提供查看
                            editanddrop += '<button type="button" onclick="showApprove(' + row.id + ')" class="btn btn-sm btn-success" data-toggle="modal" data-target="#myModal4">查看历史</button>';
                        }
                    }
                }
                if (deleteOper == 1) {
                    editanddrop += '<button type="button" onclick="deleteApprove(' + row.id + ')" class="btn btn-sm btn-danger">删除</button>';
                }
                return editanddrop;
            }
        }
    ],
    locale: 'zh-CN',//中文支持,
    url: path + '/approve/getApproveList',//排序方式
    queryParams: function (params) {
        return {
            limit: params.limit, // 每页显示数量
            offset: params.offset, // SQL语句起始索引
            page: (params.offset / params.limit) + 1, //当前页码,
            startTime1: $("#startTime1").val(),
            endTime1: $("#endTime1").val(),
            applyer: $("#applyerSearch").val(),
            name: $("#searchName").val(),
            applyType: $("#searchApplyType").val(),
            applyState: $("#searchApplyState").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/getApproveList'
    })
}

/**
 * 批量添加按钮
 */
function addApproves() {
    pickTime("effeTime5", null);
    form5.reset();
    //加载申请原因模板
    loadSelect(path + '/approve/loadReasonModle', 'parentId5', '');
}

/**
 * 添加按钮
 */
function addApprove() {
    pickTime("effeTime", null);
    setFormToken();
    $("#inpatientNo").removeAttr("readonly");
    $("#name").removeAttr("readonly");
    $("#admissTimes").removeAttr("readonly");
    $("#approveId").val("");
    form3.reset();
    //加载申请原因模板
    loadSelect(path + '/approve/loadReasonModle', 'parentId', '');
}

/**
 * 批量申请保存
 * @returns {boolean}
 */
function addSimple() {
    if ($("#effeTime5").val() != '') {
        if ($("#applyType5").val() != '') {
            var url = "/approve/simpleAddApprove174";
            var fileDir = $("#upfile").val();
            var suffix = fileDir.substr(fileDir.lastIndexOf("."));
            if ("" == fileDir) {
                toastr.warning("选择需要导入的Excel文件!")
                return false;
            }
            if (".xls" != suffix && ".xlsx" != suffix) {
                toastr.warning("文件格式有误!选择Excel格式的文件导入!")
                return false;
            }
            $("#form5").attr('disabled', 'disabled');
            var url = path + url;
            $('#loadingModel').modal('show');
            $("#loading").css("background", "url(" + path + "/static/img/load.gif) no-repeat 10px 50%");
            $('#form5').ajaxSubmit({
                type: 'POST',
                url: url,
                dataType: 'text',//服务器返回的数据类型 可选XML ,Json jsonp script html text等
                data: {upfile: $("#upfile").val()},
                error: function () {
                    $("#form5").removeAttr('disabled');
                    toastr.warning("导入excel出错!")
                },
                success: function (data) {
                    $('#loadingModel').modal('hide');
                    if (data == null || data == '') {
                        toastr.success("全部导入成功!");
                        setTimeout(function () {
                            window.location.reload();
                        }, 1000)
                    } else {
                        if (data.indexOf("@") != -1) {
                            var datas = data.split("@");
                            var workBookKey = datas[0];
                            data = datas[1];
                            Common.confirm({
                                title: "提示",
                                message: data,
                                operate: function (reselt) {
                                    if (reselt) {
                                        var url = path + "/exportWrongExcel?fileName=批量申请&workBookKey=" + workBookKey;
                                        window.location.href = url;
                                    }
                                }
                            })
                        } else {
                            toastr.error(data);
                        }
                    }
                    $("#upfile5").val("");
                    $("#form5").removeAttr('disabled');
                }
            });
        } else {
            toastr.warning("申请类型不能为空!");
            $("#applyType5").focus();
        }
    } else {
        toastr.warning("有效时间不能为空!");
        $("#effeTime5").focus();
    }
}

/**
 * 编辑
 * @param id
 */
function updateApprove(id) {
    pickTime("effeTime", null);
    //加载申请原因模板
    loadSelect(path + '/approve/loadReasonModle', 'parentId', '');
    $("#inpatientNo").prop("readonly", true);
    $("#name").prop("readonly", true);
    $("#admissTimes").prop("readonly", true);
    $("#startTime2").prop("readonly", true);
    $("#endTime2").prop("readonly", true);
    $.ajax({
        type: 'get',
        url: path + '/approve/getApproveById',
        data: {id: id},
        dataType: 'json',
        success: function (data) {
            if (null != data) {
                $("#approveId").val(data.id);
                $("#effeTime").val(data.effeTime);
                $("#effeDays").val(data.effeDays);
                $("#applyType").val(data.applyType);
                $("#parentId").val(data.reasonParentId);
                $("#applyReason").val(data.applyReason);
                $("#inpatientNo").val(data.inpatientNo);
                $("#admissTimes").val(data.admissTimes);
                $("#name").val(data.name);
                var disDate = data.disTime;
                $("#startTime2").val(disDate);
                $("#endTime2").val(disDate);
                $("#startTime3").val(disDate);
                $("#endTime3").val(disDate);
            }
        }
    })
}

/**
 * 病案預覽
 * 查看详情
 * @param patientId
 */
function showDetail(patientId) {
    //隐藏模板选项
    window.location.href = path + "/commom/showRecord174?patientId=" + patientId;
}

/**
 * 显示申请信息详情
 * @param id
 */
function showApprove(id) {
    loadSelect(path + '/approve/loadType', null, 'applyType1');
    //加载申请原因模板
    loadSelect(path + '/approve/loadReasonModle', null, 'parentId1');
    $.ajax({
        type: 'get',
        url: path + '/approve/getApproveById',
        data: {id: id},
        dataType: 'json',
        success: function (data) {
            if (null != data) {
                $("#approveId1").val(data.id);
                $("#effeTime1").val(data.effeTime);
                $("#effeDays1").val(data.effeDays);
                $("#applyType1").val(data.applyType);
                $("#parentId1").val(data.reasonParentId);
                $("#applyReason1").val(data.applyReason);
                $("#inpatientNo1").val(data.inpatientNo);
                $("#admissTimes1").val(data.admissTimes);
                $("#name1").val(data.name);
                $("#startTime3").val(data.disTime);
            }
        }
    })
}

/**
 * 提交申请按钮功能
 * @param id
 */
function updateThenAdd(id) {
    updateApprove(id);
    setTimeout(function () {
        add();
    }, 1000)
    $('#mytab').bootstrapTable('selectPage', pageNumber);
}

/**
 * 删除
 * @param id
 */
function deleteApprove(id) {
    Common.confirm({
        title: "提示",
        message: "请确认是否删除该对象?",
        operate: function (reselt) {
            if (reselt) {
                $.ajax({
                    type: 'post',
                    url: path + '/approve/deleteApproveById/' + id,
                    dataType: 'json',
                    success: function (data) {
                        if (data.code == 0) {
                            toastr.success("删除成功!");
                            refreshTable();
                            $('#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/exportExcelApplyList?checks=" + checks;
        window.location.href = url;
    } else {
        Common.confirm({
            title: "提示",
            message: "没有选中，您确定要按搜索栏条件导出?",
            operate: function (reselt) {
                if (reselt) {
                    var url = path + "/approve/exportExcelApplyList?startTime=" + $("#startTime1").val() + "&endTime=" + $("#endTime1").val() + "&name=" + $("#searchName").val() + "&applyer=" + $("#applyerSearch").val() + "&applyType=" + $("#searchApplyType").val() + "&applyState=" + $("#searchApplyState").val();
                    window.location.href = url;
                }
            }
        })
    }
}

//快速归还
function updateReturn() {
    var barCode = $("#barCodeReturn").val();
    $.ajax({
        type: 'post',
        url: path + '/applyDetails/updateReturn',
        data: {barCode: barCode},
        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("归还成功!");
            }
        }
    })
}
//清空快速归还、快速借阅表单
function  emptyForm(){
    $('#barCodeReturnTable')[0].reset();
    $('#borrowingTable')[0].reset();
}


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

//快速借阅
function fastBorrowing() {
    var effeDays = $("#effeDaysBorrowing").val()
    var applyType = $("#applyTypeBorrowing").val()
    var applyReason = $("#applyReasonBorrowing").val()
    var barCode = $("#barCodeBorrowing").val()
    $.ajax({
        type: 'post',
        url: path + '/applyDetails/fastBorrowing',
        data: {effeDays: effeDays, applyType: applyType, applyReason: applyReason, barCode: barCode},
        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)
            }
        }
    })

}


//监听回车立即搜索
//键盘回车查询
$("#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();
    }
});




//监听回车立即搜索
//键盘回车查询
$("#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();
    }
});




