var pageNumber;
$('#mytab').bootstrapTable({
    toolbar: '#toolbar',                //工具按钮用哪个容器
    striped: true,                      //是否显示行间隔色
    cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
    pagination: true,                   //是否显示分页（*）
    sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
    paginationPreText : '上一页',
    paginationNextText : '下一页',
    pageNumber: 1,                       //初始化加载第一页，默认第一页
    pageSize: 5,                       //每页的记录行数（*）
    pageList: [5,10,15,20,30,50],//可供选择的每页的行数（*）
    height: $(window).height()-144,                        //行高，如果没有设置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:'collectTypeName',
        },
        {
            title:'收藏人',
            field:'creater',
        },
        {
            title:'收藏日期',
            field:'collectTime',
        },
        {
            title:'标题',
            field:'title',
        },
        {
            title:'内容',
            field:'content',
        },
        {
            title:'病案号',
            field:'inpatientNo',
        },
        {
            title:'患者姓名',
            field:'name',
        },
        {
            title:'住院次数',
            field:'admissTimes',
        },
        {
            title:'出院日期',
            field:'disTime',
            formatter: function(value,row,index){
                if(value != '') {
                    return covertDate(value);
                }else{
                    return value;
                }
            }
        },
        {
            title:'操作',
            formatter: function(value,row,index){
                var editanddrop = "";
                var updateOper = row.updateOper;
                var deleteOper = row.deleteOper;
                if(updateOper == 1){
                    editanddrop += '<button type="button" onclick="updateCollect('+row.id+')" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#myModal2">编辑</button>'
                }
                if(deleteOper == 1){
                    editanddrop += '&nbsp&nbsp&nbsp<button type="button" onclick="deleteCollect('+row.id+')" class="btn btn-sm  btn-danger">删除</button>';
                }
                return editanddrop;
            }
        }
    ],
    locale:'zh-CN',//中文支持,
    url:path+'/collect/getCollectList',//排序方式
    queryParams: function (params) {
        return{
            limit : params.limit, // 每页显示数量
            offset : params.offset, // SQL语句起始索引
            page : (params.offset / params.limit) + 1, //当前页码,
            startTime:$("#startTime1").val(),
            endTime:$("#endTime1").val(),
            creater:$("#creater").val(),
            inpatientNo:$("#inpatientNoSearch").val(),
            admissTimes:$("#admissTimesSearch").val(),
            name:$("#searchName").val(),
            parentId:$("#collectType").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 refreshTable(){
    $("#checks").val("");
    $('#mytab').bootstrapTable('refresh',{
        url : path+'/collect/getCollectList'
    })
}



//编辑收藏
function updateCollect(id){
    loadCollectType();
    $("#inpatientNo").prop("readonly",true);
    $("#admissTimes").prop("readonly",true);
    $("#name").prop("readonly",true);
    $("#startTime2").prop("readonly",true);
    $("#endTime2").prop("readonly",true);
    $("#approveDiv").empty();
    $.ajax({
        type:'get',
        url:path+'/collect/getCollectById',
        data:{id:id},
        dataType:'json',
        success:function(data){
            if(null != data){
                $("#collectId").val(data.id);
                $("#title").val(data.title);
                $("#collectTime").val(data.collectTime);
                $("#parentId").val(data.parentId);
                $("#content").val(data.content);
                $("#inpatientNo").val(data.inpatientNo);
                $("#inpatientNo1").val(data.inpatientNo);
                $("#name").val(data.newName);
                $("#admissTimes").val(data.admissTimes);
                $("#patientId").val(data.patientId);
                $("#startTime2").val(data.disTime);
                $("#endTime2").val(data.disTime);
                //动态添加申请和查看详情按钮
                if(data.lockStatus == 0){
                    var html = '';
                    var roleId = $("#roleId").val();
                    if(data.isShowDetail == 0 && roleId != 0){
                        html = '<button type="button" class="btn btn-primary" onclick="borrowings()" data-toggle="modal" data-target="#myModal3">重新申请</button>';
                    }else{
                        html = '<a type="button" href="'+path+'/commom/showRecord174?patientId='+$("#patientId").val()+'" class="btn btn-danger TableView btn-sm" target="_blank">查看详情</a>';
                    }
                    $("#approveDiv").append(html);
                }
            }
        }
    })
}
//删除收藏
function deleteCollect(id){
    Common.confirm({
        title: "提示",
        message: "请确认是否删除这条数据?",
        operate: function (reselt) {
            if (reselt) {
                $.ajax({
                    type: 'post',
                    url: path + '/collect/deleteCollect/' + 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+"/collect/exportExcel?checks="+checks;
        window.location.href = url;
    }else{
        Common.confirm({
            title: "提示",
            message: "没有选中，您确定要按搜索栏条件导出?",
            operate: function (reselt) {
                if (reselt) {
                    var url = path+"/collect/exportExcel?startTime="+$("#startTime1").val()+"&endTime="+$("#endTime1").val()+"&creater="
                        +$("#creater").val()+"&inpatientNo="+$("#inpatientNoSearch").val()+"&admissTimes="+$("#admissTimesSearch").val()+"&name="+$("#searchName").val();
                    window.location.href = url;
                }
            }
        })
    }
}
//树操作
var zTree,zNodes;
var menu = {
    setting: {
        view:{
            fontCss : {"font-family": "微软雅黑","color":"blue"}
        },
        data:{
            key:{
                name:"collectTypeName"
            },
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "parentId",
            },
        },
        callback: { //回调函数
            onClick: zTreeOnClick }
    },
    loadMenuTree:function(){
        $.ajax({
            type: "get",
            url:path+"/collect/getEmrCollectTypeNameTree",
            dataType:"json",
            success:function(data){
                $.fn.zTree.init($("#ztree"), menu.setting, data);
                zTree = $.fn.zTree.getZTreeObj("ztree");
                var nodes = zTree.getNodes();
                for (var i = 0; i < nodes.length; i++) { //设置节点展开
                    zTree.expandNode(nodes[i], true, false, true);
                }
                zNodes = data;
            }
        })
    }
};
//加载树
$().ready(function(data){
    menu.loadMenuTree();
    fuzzySearch('ztree','#key',null,true,menu.setting,zNodes); //初始化模糊搜索方法
});

//树点击事件
function zTreeOnClick(event, treeId, treeNode) {
    $("#currentTypeId").val(treeNode.id);
    if(treeNode.level != 0){
        $("#collectTypeId").val(treeNode.id);
        $("#collectTypeFlag").val(treeNode.collectTypeFlag);
        $("#collectTypeName").val(treeNode.newName);
        $("#collectTypeDiv").show();
    }else{
        $("#collectTypeId").val("");
        form1.reset();
        $("#collectTypeDiv").hide();
    }
};

//获取当前时间
function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
}
$(function () {
	initDateInput(1);
	initDateInput(2);
	$("#collectTime").val(getNowFormatDate());
})
//清空收藏类别表单
function resetCollectType(){
    setFormToken();
    var currentTypeId = $("#currentTypeId").val();
    if(currentTypeId == '' || currentTypeId != 0){
        toastr.warning("请选中根节点添加!");
    }else{
        $("#collectTypeDiv").show();
        $("#collectTypeId").val("");
        form1.reset();
    }
}

//验证类别标志不能重复
$("#collectTypeFlag").blur(function(){
    var id = $("#collectTypeId").val();
    var  collectTypeFlag = $("#collectTypeFlag").val();
    if(collectTypeFlag != '' && id == ''){
        $.ajax({
            type:'get',
            url:path+'/collect/checkTypeFlagOrTypeName',
            data:{collectTypeFlag:collectTypeFlag},
            dataType:'json',
            success:function(data){
                if(data.code != 0){
                    toastr.warning("类别标志已存在!");
                    $("#collectTypeFlag").val("");
                    $("#collectTypeFlag").focus();
                }
            }
        })
    }
})
//验证类别名称不能重复
$("#collectTypeName").blur(function(){
    var id = $("#collectTypeId").val();
    var  collectTypeName = $("#collectTypeName").val();
    if(collectTypeName != '' && id == ''){
        $.ajax({
            type:'get',
            url:path+'/collect/checkTypeFlagOrTypeName',
            data:{collectTypeName:collectTypeName},
            dataType:'json',
            success:function(data){
                if(data.code != 0){
                    toastr.warning("类别名称已存在!");
                    $("#collectTypeName").val("");
                    $("#collectTypeName").focus();
                }
            }
        })
    }
})
//保存收藏类别功能方法
function saveCollectType(){
    var flag = false;
    if($("#collectTypeFlag").val() != ''){
        if($("#collectTypeName").val() != ''){
            $.ajax({
                type:'post',
                url:path+'/collect/addCollectType',
                data:$("#form1").serialize(),
                dataType:'json',
                success:function(data){
                    if(data.code == 0){
                        flag = true;
                        toastr.success("保存成功!");
                        menu.loadMenuTree();
                        setTimeout(function(){
                            var currentTypeId = $("#currentTypeId").val();
                            var zTree = $.fn.zTree.getZTreeObj("ztree");
                            var node = zTree.getNodeByParam("id",currentTypeId);
                            zTree.selectNode(node);
                        },500)
                    }else{
                        toastr.warning(data.msg);
                    }
                }
            })
        }else{
            toastr.warning("类别名称不能为空!");
            $("#collectTypeName").focus();
        }
    }else{
        toastr.warning("类别标志不能为空!");
        $("#collectTypeFlag").focus();
    }
}

/*删除收藏类别功能方法*/
function deleteCollectType(){
    if($("#collectTypeId").val() != ''){
        Common.confirm({
            title: "提示",
            message: "请确认是否删除该对象?",
            operate: function (reselt) {
                if (reselt) {
                    $.ajax({
                        type: 'post',
                        url: path + "/collect/deleteCollectType",
                        data: {id: $("#collectTypeId").val()},
                        dataType: 'json',
                        success: function (data) {
                            if (data.code == 0) {
                                toastr.success("删除成功!");
                                menu.loadMenuTree();
                                refreshTable();
                            } else {
                                toastr.error("删除失败，请联系超管!");
                            }
                        }
                    })
                }
            }
        })
    }else{
        toastr.warning("请确认您是否选中一项!");
    }
}
//监听关闭模态框刷新事件
$('#myModal1').on('hide.bs.modal', function () {
    window.location.reload();
});
/*********************************************添加收藏功能****************************************************/
//加载收藏类别
function loadCollectType() {
    $.ajax({
        type:'get',
        url:path+'/collect/getCollectType',
        dataType:'json',
        async:false,
        success:function (data) {
            if(null != data && data != ''){
                $("#parentId").empty();
                var html = '';
                for (var i = 0; i < data.length; i++) {
                    html += '<option value="'+data[i].id+'">'+data[i].collectTypeName+'</option>';
                }
                $("#parentId").append(html);
            }
        }
    })
}
//添加收藏功能方法
function addCollect(){
    loadCollectType();
    setFormToken();
    $("#inpatientNo").removeAttr("readonly");
    $("#admissTimes").removeAttr("readonly");
    $("#name").removeAttr("readonly");
    $("#startTime2").removeAttr("readonly");
    $("#endTime2").removeAttr("readonly");
    $("#approveDiv").empty();
    $("#collectId").val("");
    form2.reset();
    $("#collectTime").val(getNowFormatDate());
}
//保存收藏
function saveCollect(){
    var flag = false;
    var parentId = $("#parentId").val();
    if(parentId != '' && parentId != null){
        if($("#title").val() != ''){
            if($("#inpatientNo").val() != ''){
                if($("#admissTimes").val() != ''){
                    $.ajax({
                        type:'post',
                        url:path+"/collect/addCollect",
                        data:$("#form2").serialize(),
                        dataType:'json',
                        success:function(data){
                            if(data.code == 0){
                                flag = true;
                                toastr.success("收藏成功！");
                                addCollect();
                                refreshTable();
                                $('#mytab').bootstrapTable('selectPage', pageNumber);
                                $('#myModal2').modal('hide')
                            }else{
                                toastr.warning(data.msg);
                            }
                        }
                    })
                }else{
                    toastr.warning("住院次数不能为空!");
                    $("#admissTimes").focus();
                }
            }else{
                toastr.warning("病案号不能为空!");
                $("#inpatientNo").focus();
            }
        }else{
            toastr.warning("标题不能为空!");
            $("#title").focus();
        }
    }else{
        toastr.warning("收藏失败，收藏类别不能为空，如若没有为添加收藏类别请先到个人收藏页面添加类别！");
    }
}
//清空收藏表单
function clearCollect(){
    var collectId = $("#collectId").val();
    if(collectId == ''){
        form2.reset();
        $("#collectTime").val(getNowFormatDate());
    }else{
        $("#title").val("");
        $("#parentId").val("");
        $("#content").val("");
    }
}

//加载申请借阅类型
function loadApplyType(){
    $.ajax({
        type:'get',
        url:path+'/template/getLoadApplyType',
        dataType:'json',
        success:function (data) {
            if(null != data){
                $("#applyType").empty();
                var html = '';
                for (var i = 0; i < data.length; i++) {
                    if(data[i].code != ''){
                        html += '<option value="'+data[i].code+'">'+data[i].name+'</option>';
                    }
                }
                $("#applyType").append(html);
            }
        }
    })
}
//重新申请借阅
function borrowings(){
    pickTime("effeTime", null);
    loadApplyType();
    setFormToken();
    $('#myModal2').modal('hide');
    $("#form3")[0].reset();
    $("#approveId").val("");
    var patientId = $("#patientId").val();
    $("#check").val("'"+patientId+"',");
    //查询该记录是否有保存未提交的记录
    $.ajax({
        type:'post',
        url:path+'/approve/approveListByAppleStatus?patientId='+patientId,
        dataType:'json',
        success:function(data){
            if(data != null || data != ''){
                $("#approveId").val(data.id);
                $("#effeTime").val(data.effeTime);
                $("#applyType").val(data.applyType);
                $("#effeDays").val(data.effeDays);
                $("#inpatientNo1").val(data.inpatientNo);
                $("#applyReason").val(data.applyReason);
            }
        }
    })
}
