//树操作
var menu = {
    setting: {
        view: {
            fontCss: {"font-family": "微软雅黑", "color": "blue"}
        },
        data: {
            key: {
                name: "newName"
            },
            simpleData: {
                chkStyle: "checkbox",
                enable: true,
                idKey: "id",
                pIdKey: "parentId",
            },
        },
        check: {
            enable: true
        },
        callback: { //回调函数
            onCheck: onCheck,
            onClick: onClick
        }
    },
    loadMenuTree: function () {
        $.ajax({
            type: "post",
            url: path + "/font/getBloodRecordTree",
            data: {patientId: $("#patientId").val(), typeId: $("#typeId").val()},
            dataType: "json",
            success: function (data) {
                $("#assortIds").val("");
                if (data != null) {
                    //图片相对路径集合
                    var scanPages = '';
                    //图片来源集合
                    var sources = '';
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].parentId != null && data[i].parentId != 1 && data[i].checked == 'true') {
                            scanPages += data[i].assortName + ",";
                            sources += data[i].source + ",";
                        }
                    }
                    //去掉后面逗号
                    if (scanPages != '') {
                        scanPages = scanPages.substring(0, scanPages.length - 1);
                        $("#assortIds").val(scanPages);
                        sources = sources.substring(0, sources.length - 1);
                        $("#sources").val(sources);
                    }
                    $.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);
                    }
                    //加载pdf
                    onloadPdf(scanPages, sources);
                }
            }
        })
    }
};
//加载树
$().ready(function (data) {
    menu.loadMenuTree();
});

//树选中事件
function onCheck(e, treeId, treeNode) {
    var treeObj = $.fn.zTree.getZTreeObj("ztree");
    nodes = treeObj.getCheckedNodes(true);
    var assortIds = '';
    var sources = '';
    for (var i = 0; i < nodes.length; i++) {
        if (nodes[i].level == 2) {
            if (i != (nodes.length - 1)) {
                assortIds += nodes[i].assortName + ",";
                sources += +nodes[i].source + ",";
            } else {
                assortIds += nodes[i].assortName + "";
                sources += nodes[i].source;
            }
        }
    }
    $("#assortIds").val(assortIds);
    $("#sources").val(sources);
};

//树点击事件
function onClick(e, treeId, treeNode) {
    var treeLevel = treeNode.level;
    //选中图片节点时
    if (treeLevel == 2) {
        //图片集合
        var scanPages = treeNode.assortName;
        //来源集合
        var sources = treeNode.source;
        $("#assortIdByClick").val(scanPages);
        $("#sourceByClick").val(sources);
        onloadPdf(scanPages, sources);
    }
};
//打印分类变更事件
$("#typeId").change(function () {
    menu.loadMenuTree();
})

//树复选框选中后加载pdf按钮
function onloadPdfMethod() {
    var scanPages = $("#assortIds").val();
    //来源集合
    var sources = $("#sources").val();
    $("#assortIdByClick").val("");
    $("#sourceByClick").val("");
    onloadPdf(scanPages, sources);
}

//加载pdf按钮功能
function onloadPdf(scanPages, sources) {
    $("#iframeLoad").val("");
    $("#printPicLoaded").val("");
    var patientId = $("#patientId").val();
    //根目录字段识别名称
    var flag = parent.$("#flag").val();
    $.ajax({
        type: 'post',
        url: path + "/font/showRecordContentBlood",
        data: {
            patientId: patientId,
            scanPages: scanPages,
            flag: flag,
            sources: sources
        },
        datType: 'json',
        success: function (data) {
            if (data.code == 0) {
                var str = path + "/font/getRecordContentBlood?patientId=" + patientId;
                $("#iframe1").attr("src", path + "/static/pdfjs/web/viewer3.html?file=" + encodeURIComponent(str))
            }
        }
    })
}

var iframe = document.getElementById("iframe1");


if (iframe.attachEvent) {
    iframe.attachEvent("onreadystatechange", function () {
        //此事件在内容没有被载入时候也会被触发，所以我们要判断状态
        //有时候会比较怪异 readyState状态会跳过 complete 所以我们loaded状态也要判断
        if (iframe.readyState === "complete" || iframe.readyState == "loaded") {
            //代码能执行到这里说明已经载入成功完毕了
            //要清除掉事件
            iframe.detachEvent("onreadystatechange", arguments.callee);
            //这里是回调函数
        }
    });
} else {
    iframe.addEventListener("load", function () {
        $("#iframeLoad").val(1);
        //代码能执行到这里说明已经载入成功完毕了
        this.removeEventListener("load", arguments.call, false);
    }, false);
}

//下载pdf按钮功能
function onloadJpgForPdf() {
    var typeId = $("#typeId").val();
    if (typeId == undefined) {
        typeId = '';
    }
    Common.confirm({
        title: "提示",
        message: "确认将左侧树选中的图片下载pdf?",
        operate: function (reselt) {
            if (reselt) {
                var patientId = $("#patientId").val();
                var assortIds = $("#assortIds").val();
                var flag = parent.$("#flag").val();
                post(path + '/template/downloadPdfBlood', {
                    "patientIds": patientId,
                    "assortIds": assortIds,
                    "typeId": typeId,
                    "flag": flag
                });
            }
        }
    })
}

//重新归页确定按钮功能
function sure() {
    Common.confirm({
        title: "提示",
        message: "确认将左侧树选中的图片是否重新归页?",
        operate: function (reselt) {
            if (reselt) {
                //pdf页数
                var newAssortId = $("#newAssortId").val();
                if (newAssortId != '') {
                    var patientId = $("#patientId").val();
                    var assortIds = $("#assortIds").val();
                    if (assortIds != '') {
                        $.ajax({
                            type: 'post',
                            url: path + '/commom/updateScanAssortByBlood',
                            data: {
                                patientId: patientId,
                                name: parent.$("#name").val(),
                                assortIds: assortIds,
                                newAssortId: newAssortId
                            },
                            dataType: 'json',
                            success: function (data) {
                                if (data.code == 0) {
                                    toastr.success("重新归页成功！");
                                }
                                //重新加载
                                menu.loadMenuTree();
                            }
                        })
                    } else {
                        toastr.warning("左侧树至少选中一张图片!")
                    }
                } else {
                    toastr.warning("要重新分页，需选中其中下拉框其中一项！")
                }
            }
        }
    })
}

//删除图片
function delPic() {
    Common.confirm({
        title: "提示",
        message: "确认将左侧树选中的图片删除?",
        operate: function (reselt) {
            if (reselt) {
                var patientId = $("#patientId").val();
                var assortIds = $("#assortIds").val();
                if (assortIds != '') {
                    $.ajax({
                        type: 'post',
                        url: path + '/commom/delScanAssortByBlood',
                        data: {patientId: patientId, name: parent.$("#name").val(), assortIds: assortIds},
                        dataType: 'json',
                        success: function (data) {
                            if (data.code == 0) {
                                toastr.success("删除成功！");
                            }
                            //重新加载
                            menu.loadMenuTree();
                        }
                    })
                }
            }
        }
    })
}

//记录打印记录
function printInfoBlood() {
    var patientId = "'" + $("#patientId").val() + "'";
    var typeId = $("#typeId").val();
    if (typeId == undefined) {
        typeId = '';
    }
    var assortIds = '';
    //判断树点击选中赋值的框是否有值，有则属于取点击选中的值，否则去加载pdf的值
    var assortIdByClick = $("#assortIdByClick").val();
    if (assortIdByClick != '') {
        assortIds = $("#assortIdByClick").val();
    } else {
        assortIds = $("#assortIds").val();
    }
    var flag = $("#flag").val();
    $.ajax({
        type: 'post',
        url: path + '/template/printInfoBlood',
        data: {"patientIds": patientId, "assortIds": assortIds, "typeId": typeId, "flag": flag},
        dataType: 'json',
        success: function (data) {
            if (data.code == 0) {
                toastr.success("打印成功")
            } else {
                toastr.success(data.msg)
            }
        }
    })
}

/**
 * 病案查询
 */
function search() {
    var inpatientNo = $("#inpatientNo").val();
    var admissTimes = $("#admissTimes").val();
    var name = $("#name").val();
    if (inpatientNo == "" && admissTimes == "" && name == "") {
        toastr.warning("请输入搜索信息在进行查询");
    } else {
        var sql = "select patient_id,inpatient_no,name,admiss_times,admiss_date,dis_date,dis_dept from commomtable where 1 = 1";
        if (null != inpatientNo && "" != inpatientNo) {
            sql += " and inpatient_no like '%" + inpatientNo + "%'";
        }
        if (null != admissTimes && "" != admissTimes) {
            sql += " and admiss_times like '%" + admissTimes + "%'";
        }
        if (null != name && "" != name) {
            4
            sql += " and name like '%" + name + "%'";
        }
        $("#mytab").bootstrapTable('destroy');
        //生成用户数据
        $('#mytab').bootstrapTable({
            method: 'post',
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            toolbar: '#toolbar',    			//工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            paginationPreText: '上一页',
            paginationNextText: '下一页',
            paginationFirstText: '<',
            paginationLastText: '>',
            detailView: flag,
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 5,                       //每页的记录行数（*）
            pageList: [5, 10, 20, 50, 100],//可供选择的每页的行数（*）
            height: 400,//高度调整                 //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            buttonsAlign: "left",//按钮对齐方式
            columns: [
                {
                    title: '病案号',
                    field: 'inpatientNo',
                },
                {
                    title: '姓名',
                    field: 'name',
                },
                {
                    title: '住院次数',
                    field: 'admissTimes',
                },
                {
                    title: '入院日期',
                    field: 'admissDate',
                },
                {
                    title: '出院时间',
                    field: 'disDate',
                },
                {
                    title: '出院科室',
                    field: 'disDept',
                },
                {
                    title: '操作',
                    formatter: function (value, row, index) {
                        var patientId = row.patientId;
                        var inpatientNo = row.inpatientNo.replace(/\s+/g, "");
                        var name = row.name;
                        var admissTimes = row.admissTimes;
                        var info = "'" + patientId + "," + inpatientNo + "," + name + "," + admissTimes + "'";
                        var editanddrop = '<button type="button" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#myModal2" onclick="showInfo(' + info + ')">选择分段</button>';
                        return editanddrop;
                    }
                }
            ],
            locale: 'zh-CN',//中文支持,
            url: path + '/template/cutomSearchTable',//排序方式
            queryParams: function (params) {
                return {
                    sql: sql,
                    limit: params.limit, // 每页显示数量
                    offset: params.offset, // SQL语句起始索引
                    page: (params.offset / params.limit) + 1 //当前页码
                }
            },
            responseHandler: function (res) {
                //在ajax获取到数据，渲染表格之前，修改数据源
                var nres = [];
                nres.push({total: res.total, rows: res.list});
                return nres[0];
            },
            onLoadSuccess: function (res) {
                $(".clearfix").height(0);
                $(".page-list").show();
                $(".fixed-table-body").css("overflow", "auto");
                //赋值总数
                $("#rows").val(res.total);
                //全选
                $('.fixed-table-container').on('click', 'input[name="btSelectAll"]', function () {
                    if ($(this).is(':checked')) {
                        $('input[name="btSelectItem"]').prop('checked', true);
                    } else {
                        $('input[name="btSelectItem"]').prop('checked', false);
                    }
                })
                //逐个选择
                $('.fixed-table-container').on('click', 'input[name="btSelectItem"]', function () {
                    var inputs = $(this).parents('.fixed-table-body-columns').find('input[name="btSelectItem"]')
                    var num = 0;
                    inputs.each(function () {
                        if ($(this).is(':checked')) {
                            num++;
                        }
                    });
                    if (num == inputs.length) {
                        $('input[name="btSelectAll"]').prop('checked', true);
                    } else {
                        $('input[name="btSelectAll"]').prop('checked', false);
                    }
                    var index = $(this).parents('tr').index();
                    $('#Table1').find('input[name="btSelectItem"]').eq(index).click();
                });
            }
        })
    }
}

/**
 * 显示需要移动的病案信息
 * @param patientId
 */
function showInfo(info) {
    var infoList = info.split(",");
    $("#patientIdInfo").val(infoList[0]);
    $("#inpatientNoInfo").val(infoList[1]);
    $("#nameInfo").val(infoList[2]);
    $("#admissTimesInfo").val(infoList[3]);
}

/**
 * 修改PDF存放地址
 */
function movePdf() {
    //需要移动PDF的病案id
    var oldPatientId = $("#patientId").val();
    //目标病案id
    var newPatientId = $("#patientIdInfo").val();
    //选中图片名称
    var assortIds = $("#assortIds").val();
    //选中分段
    var newAssortId = $("#moveAssortId").val();
    if (oldPatientId == '' || newPatientId == '' || assortIds == '' || newAssortId == '') {
        toastr.warning("程序出现错误,请联系管理员！");
    } else {
        $.ajax({
            type: 'post',
            url: path + '/template/movePdfBlood',
            data: {
                oldPatientId: oldPatientId,
                newPatientId: newPatientId,
                assortIds: assortIds,
                newAssortId: newAssortId,
                flag: parent.$("#flag").val()
            },
            dataType: 'json',
            success: function (data) {
                if (data.code == 0) {
                    window.location.reload();
                    toastr.success("转移成功！");
                }
            }
        })
    }


}
