/**
 * Created by Tony on 2017/6/26.
 */
'use strict'

const PRE_PAGE_OFFSET = 150;
const NEXT_PAGE_OFFSET = 160;
const FIRST_PAGE_OFFSET = 50;
const LAST_PAGE_OFFSET = 60;

const WAIT_TIME_EXPORT = 300000;

let fontSuffixMapObj = {"表标题": "title", "列标题": "column", "正文内容": "content", "合计": "summary", "表眉/表脚": "header_footer"};

let rptTplObj = {
    hasInitialized: false,
    pdfFont: {'SmartSimsun': [], 'simhei': [], 'simkai': []},
    iniPage: function() {
        let me = this;
        if (!me.hasInitialized) {
            zTreeOprObj.getCustomerCfg();
            zTreeOprObj.getReportTemplateTree();
            zTreeOprObj.selectedPrjIDs = [];
            me.hasInitialized = true;
            let canvas = document.getElementById("rptCanvas");
            canvas.onclick = canvasOprObj.canvasOnClick;
            canvas.onmousemove = canvasOprObj.canvasOnMouseMove;
            if (JpcJsPDFHelper.doc === null) {
                JpcJsPDFHelper.initialize('p', 'pt', 'a4');
            }
            // dynamicLoadJs('/lib/jspdf/SmartSimsun-normal.js');
            // dynamicLoadJs('/lib/jspdf/SmartSimsun-bold.js', me.pdfFontSimsunCallBack);
            // dynamicLoadJs('http://d2.smartcost.com.cn/cach/SmartSimsun-normal.js');
            // dynamicLoadJs('http://d2.smartcost.com.cn/cach/SmartSimsun-bold.js', me.pdfFontSimsunCallBack);
        }
    },
    pdfFontSimsunCallBack: function() {
        rptTplObj.pdfFont['SmartSimsun'].push('normal');
        rptTplObj.pdfFont['SmartSimsun'].push('bold');
    },
    pdfFontSimkaiCallBack: function() {
        rptTplObj.pdfFont['simkai'].push('normal');
        rptTplObj.pdfFont['simkai'].push('bold');
    },
    pdfFontSimheiCallBack: function() {
        rptTplObj.pdfFont['simhei'].push('normal');
        rptTplObj.pdfFont['simhei'].push('bold');
    }
}

let zTreeOprObj = {
    treeObj: null,
    prjFolderTreeObj: null,
    currentNode: null,
    checkedRptTplNodes: null,
    currentRptPageRst: null,
    reportPageCfg: null,
    defReportPageCfg: null,
    currentPage: 1,
    maxPages: 0,
    selectedPrjIDs: [],
    isFreeUser: true,
    waterMarks: [],
    countChkedRptTpl: function () {
        let me = zTreeOprObj;
        if (me.treeObj) {
            me.checkedRptTplNodes = [];
            let chkNodes = me.treeObj.getCheckedNodes(true), cnt = 0, hasCurrentNode = false;
            for (let node of chkNodes) {
                if (node.nodeType === TPL_TYPE_TEMPLATE) {
                    cnt++;
                    me.checkedRptTplNodes.push(node);
                    if (me.currentNode === node) hasCurrentNode = true;
                }
            }
            if (!hasCurrentNode && cnt === 0 && me.currentNode !== null) {
                //这里根据实际需求再做处理
                cnt++;
                me.checkedRptTplNodes.push(me.currentNode);
            }
            $("#export_div").find("span").each(function(cIdx,elementSpan){
                elementSpan.innerText = cnt;
            });
            $("#print_div").find("span").each(function(cIdx,elementSpan){
                elementSpan.innerText = cnt;
            });
        }
    },
    getReportTemplateTree: function() {
        let me = zTreeOprObj, params = {};
        params.engineerId = projectObj.project.projectInfo.property.engineering;
        let private_chk_hide = function (chkTplItem) {
            //考虑未来拓展，统一在此判断报表模板是否显示
            let rst = false;
            // if (chkTplItem.hasOwnProperty('flags') && chkTplItem.flags.hasOwnProperty('taxType') && chkTplItem.flags['taxType'] !== null &&
            //     parseInt(chkTplItem.flags['taxType']) !== parseInt(projectObj.project.projectInfo.property.taxType)) {
            //     rst = true;
            // }
            //重庆养护系统的判断逻辑有所不同
            if (chkTplItem.hasOwnProperty('flags') && chkTplItem.flags.hasOwnProperty('valuationType') && chkTplItem.flags['valuationType'] !== null &&
                chkTplItem.flags['valuationType'] !== projectObj.project.projectInfo.property.valuationType) {
                rst = true;
            }
            return rst;
        };
        // projectObj.project.projectInfo.property.taxType === 1 //1: 一般计税 2: 简易计税
        CommonAjax.postEx("report_tpl_api/getRptTplTree", params, 20000, true, function(result){
            let private_remove_hide_item = function (items, nlv) {
                if (items && items.length > 0) {
                    for (let i = items.length - 1; i >= 0; i--) {
                        if (!(items[i].released) && items[i].nodeType === 2) {
                            items.splice(i, 1);
                        } else if(private_chk_hide(items[i])) {
                            items.splice(i, 1);
                        } else {
                            if (items[i].items && items[i].items.length > 0) {
                                private_remove_hide_item(items[i].items, nlv + 1);
                                if (items[i].items.length === 0 && nlv > 0) {
                                    items.splice(i, 1);
                                }
                            }
                        }
                    }
                }
            }
            let nodeLv = 0;
            zTreeOprObj.isFreeUser = result.isFreeUser;
            zTreeOprObj.waterMarks = result.waterMarks;
            private_remove_hide_item(result.data, nodeLv);
            for (let topNode of result.data) {
                if (topNode.userId === "-100") {
                    topNode.name = topNode.name + " - 标准报表";
                } else {
                    topNode.name = topNode.name + " - 定制报表";
                }
            }
            zTreeHelper.createTreeDirectly(result.data, rpt_tpl_setting, "rptTplTree", me);
            me.refreshNodes();
        }, null, null);
    },
    getCustomerCfg: function() {
        let me = zTreeOprObj, params = {};
        params.engineerId = projectObj.project.projectInfo.property.engineering;
        CommonAjax.postEx("report_tpl_api/getCustomizeCfg", params, 20000, true, function(result){
                if (result) {
                    me.defReportPageCfg = result[0];
                    me.reportPageCfg = result[1];
                    me.iniFontCfgDom(me.reportPageCfg);
                    me.renderRptCfg(result[1]);
                } else {
                    me.reportPageCfg = null;
                    me.defReportPageCfg = null;
                }
            }, null, null
        );
    },
    iniFontCfgDom: function (cfg) {
        for (let font of cfg.fonts) {
            let domArrs = [];
            let fontPropSuffix = fontSuffixMapObj[font.CfgDispName];
            domArrs.push("<div class='row mb-1'>");
            //1. label
            domArrs.push("<div class='col-3'>" + font.CfgDispName + "</div>");
            //2. font name
            domArrs.push("<div class='col-3'>");
            domArrs.push("<select class='form-control input-sm' id='fontName_" + fontPropSuffix + "' onchange='rptControlObj.changeFontMain(\"" + font.CfgDispName + "\", \"Name\", this)'>");
            domArrs.push("<option>宋体</option><option>楷体</option><option>黑体</option>");
            domArrs.push("</select>");
            domArrs.push("</div>");
            //3. font height
            domArrs.push("<div class='col-3'>");
            domArrs.push("<input class='form-control input-sm' id='fontHeight_" + fontPropSuffix + "' type='number' value='30' step='1' min='6' max='66' " +
                "onchange='rptControlObj.changeFontMain(\"" + font.CfgDispName + "\", \"FontHeight\", this)' " +
                "onkeyup='rptControlObj.changeFontMain(\"" + font.CfgDispName + "\", \"FontHeight\", this)'>");
            domArrs.push("</div>");
            //4. font bold italic underline
            domArrs.push("<div class='col-3'>");
            domArrs.push("<a id='font_bold_" + fontPropSuffix + "' class='btn btn-sm btn-outline-secondary' title='加粗' onclick='rptControlObj.changeFontAdhoc(\"" + font.CfgDispName + "\", \"FontBold\", this)'><i class='fa fa-bold'></i></a>");
            domArrs.push("<a id='font_italic_" + fontPropSuffix + "' class='btn btn-sm btn-outline-secondary' title='斜体' onclick='rptControlObj.changeFontAdhoc(\"" + font.CfgDispName + "\", \"FontItalic\", this)'><i class='fa fa-italic'></i></a>");
            domArrs.push("<a id='font_underline_" + fontPropSuffix + "' class='btn btn-sm btn-outline-secondary' title='下划线' onclick='rptControlObj.changeFontAdhoc(\"" + font.CfgDispName + "\", \"FontUnderline\", this)'><i class='fa fa-underline'></i></a>");
            domArrs.push("</div>");
            //
            domArrs.push("</div>");
            $(domArrs.join("")).insertBefore($("#font_cfg_blank_flag"));
        }
    },
    renderRptCfg: function (cfg) {
        $("#elementMargin_Left").get(0).value = cfg.margins.Left;
        $("#elementMargin_Right").get(0).value = cfg.margins.Right;
        $("#elementMargin_Top").get(0).value = cfg.margins.Top;
        $("#elementMargin_Bottom").get(0).value = cfg.margins.Bottom;

        for (let font of cfg.fonts) {
            let fontPropSuffix = fontSuffixMapObj[font.CfgDispName];
            document.getElementById("fontName_" + fontPropSuffix).value = font.Name;
            document.getElementById("fontHeight_" + fontPropSuffix).value = font.FontHeight;
            document.getElementById("font_bold_" + fontPropSuffix).className = (font.FontBold === "T")?"btn btn-sm btn-outline-secondary active":"btn btn-sm btn-outline-secondary";
            document.getElementById("font_italic_" + fontPropSuffix).className = (font.FontItalic === "T")?"btn btn-sm btn-outline-secondary active":"btn btn-sm btn-outline-secondary";
            document.getElementById("font_underline_" + fontPropSuffix).className = (font.FontUnderline === "T")?"btn btn-sm btn-outline-secondary active":"btn btn-sm btn-outline-secondary";
        }
        document.getElementById("rpt_vertical_line").checked = cfg.showVerticalLine;
        document.getElementById("rpt_narrow").checked = cfg.isNarrow;
        // document.getElementById("rpt_narrow").checked = false;
        document.getElementById("rpt_fill_zero").checked = cfg.fillZero;
    },
    extractRptCfg: function (cfg) {
        cfg.margins.Left = $("#elementMargin_Left").get(0).value;
        cfg.margins.Right = $("#elementMargin_Right").get(0).value;
        cfg.margins.Top = $("#elementMargin_Top").get(0).value;
        cfg.margins.Bottom = $("#elementMargin_Bottom").get(0).value;

        for (let font of cfg.fonts) {
            let fontPropSuffix = fontSuffixMapObj[font.CfgDispName];
            font.Name = document.getElementById("fontName_" + fontPropSuffix).value;
            font.FontHeight = document.getElementById("fontHeight_" + fontPropSuffix).value;
            font.FontBold = (document.getElementById("font_bold_" + fontPropSuffix).className === "btn btn-sm btn-outline-secondary active")?"T":"F";
            font.FontItalic = (document.getElementById("font_italic_" + fontPropSuffix).className === "btn btn-sm btn-outline-secondary active")?"T":"F";
            font.FontUnderline = (document.getElementById("font_underline_" + fontPropSuffix).className === "btn btn-sm btn-outline-secondary active")?"T":"F";
        }
        cfg.showVerticalLine = document.getElementById("rpt_vertical_line").checked;
        cfg.isNarrow = document.getElementById("rpt_narrow").checked;
        cfg.fillZero = document.getElementById("rpt_fill_zero").checked;
    },
    refreshNodes: function() {
        let me = this;
        let private_setupIsParent = function(node){
            node.isParent = (node.nodeType === RT.NodeType.NODE || node.level === 0);
            if (node.items && node.items.length) {
                for (let i = 0; i < node.items.length; i++) {
                    private_setupIsParent(node.items[i]);
                }
            }
        };
        let topNodes = me.treeObj.getNodes();
        for (let i = 0; i < topNodes.length; i++) {
            private_setupIsParent(topNodes[i]);
        }
        me.treeObj.refresh();
    },
    onCheck: function(event, treeId, treeNode) {
        zTreeOprObj.countChkedRptTpl();
    },
    onClick: function(event,treeId,treeNode) {
        let me = zTreeOprObj;
        if (treeNode.nodeType === TPL_TYPE_TEMPLATE && treeNode.refId > 0) {
            me.currentNode = treeNode;
            if (treeNode.hasOwnProperty('flags') && treeNode.flags.hasOwnProperty('reportType') && treeNode['flags']['reportType'] !== 'NA') {
                if (treeNode['flags']['reportType'] === 'billSummary') {
                    me.requestPrjFolderForBillsSummary();
                } else if (treeNode['flags']['reportType'] === 'gljSummary') {
                    me.requestPrjFolderForGljSummary();
                }
            } else {
                let params = {};
                let pageSize = rptControlObj.getCurrentPageSize();
                params.pageSize = pageSize;
                params.rpt_tpl_id = treeNode.refId;
                params.prj_id = projectObj.project.projectInfo.ID;
                params.custCfg = me.reportPageCfg;
                me.requestNormalReport(params);
            }
            me.countChkedRptTpl();
        }
    },
    changePageSize: function(dom) {
        let me = zTreeOprObj,
            targetDom = document.getElementById("btnRptPageSize");
        let tmpStr = targetDom.innerHTML.trim();
        targetDom.innerHTML = dom.innerHTML.trim();
        dom.innerHTML = tmpStr;
        me.changeCfg();

    },
    changeOrientation: function(dom) {
        let me = zTreeOprObj,
            targetDom = document.getElementById("btnRptOrientation");
        let tmpStr = targetDom.innerHTML.trim();
        targetDom.innerHTML = dom.innerHTML.trim();
        dom.innerHTML = tmpStr;
        me.changeCfg();
    },
    changeCfg: function() {
        let me = zTreeOprObj;

        if (me.currentNode) {
            if (me.currentNode.hasOwnProperty('flags') && me.currentNode.flags.hasOwnProperty('reportType') && me.currentNode['flags']['reportType'] !== 'NA') {
                let refRptTplIds = [], refBillSumPrjsIds = [], refGljSumPrjsIds = [];
                if (me.currentNode['flags']['reportType'] === 'billSummary') {
                    refBillSumPrjsIds.push(me.currentNode.refId);
                } else if (me.currentNode['flags']['reportType'] === 'gljSummary') {
                    refGljSumPrjsIds.push(me.currentNode.refId);
                }
                if (zTreeOprObj.selectedPrjIDs.length > 0) {
                    let params = rptControlObj.creatCommonExportParam(refRptTplIds, refBillSumPrjsIds, refGljSumPrjsIds);
                    params.pageSize = rptControlObj.getCurrentPageSize();
                    params.orientation = rptControlObj.getCurrentOrientation();
                    params.rpt_ids = refRptTplIds;
                    params.rpt_bill_tpl_ids = refBillSumPrjsIds;
                    params.rpt_glj_tpl_ids = refGljSumPrjsIds;
                    params.custCfg = me.reportPageCfg;
                    CommonAjax.postEx("report_api/getMultiReports", params, 300000, true,
                        function(result){
                            hintBox.unWaitBox();
                            let pageRst = result[0];
                            let canvas = document.getElementById("rptCanvas");
                            if (pageRst && pageRst.items && pageRst.items.length > 0) {
                                me.resetAfter(pageRst);
                                me.currentRptPageRst = pageRst;
                                me.maxPages = pageRst.items.length;
                                me.currentPage = 1;
                                me.displayPageValue();
                                let size = JpcCanvasOutput.getReportSizeInPixel(me.currentRptPageRst, getScreenDPI());
                                canvas.width = size[0] + 20;
                                if (size[1] > size[0]) {
                                    canvas.height = size[1] + 100;
                                } else {
                                    canvas.height = size[1] + 50;
                                }
                                me.showPage(1, canvas);
                            } else {
                                //返回了无数据表
                                JpcCanvasOutput.cleanCanvas(canvas);
                                JpcCanvasOutput.drawPageBorder(me.currentRptPageRst, canvas, getScreenDPI());
                            }
                        }, function(err){
                            hintBox.unWaitBox();
                        }, function(ex){
                            hintBox.unWaitBox();
                        }
                    );
                } else {
                    if (me.currentNode['flags']['reportType'] === 'billSummary') {
                        me.requestPrjFolderForBillsSummary();
                    } else if (me.currentNode['flags']['reportType'] === 'gljSummary') {
                        me.requestPrjFolderForGljSummary();
                    }
                }
            } else {
                let params = {};
                params.pageSize = rptControlObj.getCurrentPageSize();
                params.orientation = rptControlObj.getCurrentOrientation();
                params.rpt_tpl_id = me.currentNode.refId;
                params.prj_id = projectObj.project.projectInfo.ID;
                params.custCfg = me.reportPageCfg;
                me.requestNormalReport(params);
            }
        }
    },
    resetAfter: function (pageRst) {
        let size = pageRst[JV.NODE_PAGE_INFO][JV.NODE_PAGE_SIZE].slice(0);
        if (size[0] > size[1]) {
            document.getElementById("btnRptOrientation").innerHTML = "横向";
            document.getElementById("hrefRptOrientation").innerHTML = "纵向";
        } else {
            document.getElementById("btnRptOrientation").innerHTML = "纵向";
            document.getElementById("hrefRptOrientation").innerHTML = "横向";
        }
    },
    requestNormalReport: function (params) {
        let me = zTreeOprObj;
        hintBox.waitBox();
        CommonAjax.postEx("report_api/getReport", params, 60000, true,
            function(result){
                hintBox.unWaitBox();
                let pageRst = result;
                let canvas = document.getElementById("rptCanvas");
                if (pageRst && pageRst.items && pageRst.items.length > 0) {
                    me.resetAfter(pageRst);
                    me.currentRptPageRst = pageRst;
                    me.maxPages = pageRst.items.length;
                    me.currentPage = 1;
                    me.displayPageValue();
                    let size = JpcCanvasOutput.getReportSizeInPixel(me.currentRptPageRst, getScreenDPI());
                    canvas.width = size[0] + 20;
                    if (size[1] > size[0]) {
                        canvas.height = size[1] + 100;
                    } else {
                        canvas.height = size[1] + 50;
                    }
                    me.showPage(1, canvas);
                } else {
                    //返回了无数据表
                    JpcCanvasOutput.cleanCanvas(canvas);
                    JpcCanvasOutput.drawPageBorder(me.currentRptPageRst, canvas, getScreenDPI());
                }
            }, function(err){
                hintBox.unWaitBox();
            }, function(ex){
                hintBox.unWaitBox();
            }
        );
    },
    requestPrjFolderCommon: function () {
        let me = zTreeOprObj;
        hintBox.waitBox();
        $.ajax({
            type:"POST",
            url: '/pm/api/getProjects',
            data: {'data': JSON.stringify({"user_id": userID, "compilation": projectObj.project.projectInfo.compilation})},
            dataType: 'json',
            cache: false,
            timeout: 15000,
            success: function(result){
                hintBox.unWaitBox();
                if (result.error === 0) {
                    //console.log(result.data);
                    let currPrjParentID = projectObj.project.projectInfo.ParentID;
                    let selectedProjects = [];
                    for (let prj of result.data) {
                        if (currPrjParentID === prj.ParentID) {
                            selectedProjects.push({name: prj.name, ID: prj.ID});
                        }
                    }
                    $("#show_project_folder").trigger("click");
                    let topItem = [{name: '所有相关项目', items: selectedProjects}];
                    // me.prjFolderTreeObj = $.fn.zTree.init($("#prjFolderTree"), rpt_prj_folder_setting, selectedProjects);
                    me.prjFolderTreeObj = $.fn.zTree.init($("#prjFolderTree"), rpt_prj_folder_setting, topItem);
                    me.prjFolderTreeObj.expandAll(true);
                } else {
                    alert('error: ' + result.message);
                }
            },
            error: function(jqXHR, textStatus, errorThrown){
                hintBox.unWaitBox();
                alert('error ' + textStatus + " " + errorThrown);
            }
        });
    },
    requestPrjFolderForBillsSummary: function () {
        let me = zTreeOprObj;
        $("#divReqBillSummary")[0].style.display = "";
        $("#divReqGljSummary")[0].style.display = "none";
        $("#divReqCommonSummaryExcel")[0].style.display = "none";
        $("#divReqCommonSummaryMultiExcel")[0].style.display = "none";
        $("#divReqCommonSummaryPDF")[0].style.display = "none";
        me.requestPrjFolderCommon();
    },
    requestPrjFolderForGljSummary: function () {
        let me = zTreeOprObj;
        $("#divReqBillSummary")[0].style.display = "none";
        $("#divReqGljSummary")[0].style.display = "";
        $("#divReqCommonSummaryExcel")[0].style.display = "none";
        $("#divReqCommonSummaryMultiExcel")[0].style.display = "none";
        $("#divReqCommonSummaryPDF")[0].style.display = "none";
        me.requestPrjFolderCommon();
    },
    requestBillsSummaryRpt: function () {
        let me = zTreeOprObj;
        let nodes = me.prjFolderTreeObj.getCheckedNodes(true);
        if (nodes.length > 0) {
            if (nodes[0].level === 0) {
                nodes.splice(0, 1);
            }
            hintBox.waitBox();
            let params = {};
            params.pageSize = rptControlObj.getCurrentPageSize();
            params.rpt_tpl_id = me.currentNode.refId;
            params.custCfg = me.reportPageCfg;
            params.prjIds = [];
            me.selectedPrjIDs = [];
            for (let node of nodes) {
                params.prjIds.push(node.ID);
                me.selectedPrjIDs.push(node.ID);
            }
            CommonAjax.postEx("report_api/getBillsSummaryReport", params, 60000, true,
                function(result){
                    hintBox.unWaitBox();
                    let pageRst = result;
                    let canvas = document.getElementById("rptCanvas");
                    if (pageRst && pageRst.items && pageRst.items.length > 0) {
                        me.resetAfter(pageRst);
                        me.currentRptPageRst = pageRst;
                        me.maxPages = pageRst.items.length;
                        me.currentPage = 1;
                        me.displayPageValue();
                        let size = JpcCanvasOutput.getReportSizeInPixel(me.currentRptPageRst, getScreenDPI());
                        canvas.width = size[0] + 20;
                        if (size[1] > size[0]) {
                            canvas.height = size[1] + 100;
                        } else {
                            canvas.height = size[1] + 50;
                        }
                        me.showPage(1, canvas);
                    } else {
                        //返回了无数据表
                        JpcCanvasOutput.cleanCanvas(canvas);
                        JpcCanvasOutput.drawPageBorder(me.currentRptPageRst, canvas, getScreenDPI());
                    }
                }, function(err){
                    hintBox.unWaitBox();
                }, function(ex){
                    hintBox.unWaitBox();
                }
            );
        }
    },
    requestGljSummaryRpt: function () {
        let me = zTreeOprObj;
        let nodes = me.prjFolderTreeObj.getCheckedNodes(true);
        if (nodes.length > 0) {
            if (nodes[0].level === 0) {
                nodes.splice(0, 1);
            }
            hintBox.waitBox();
            let params = {};
            params.pageSize = rptControlObj.getCurrentPageSize();
            params.rpt_tpl_id = me.currentNode.refId;
            params.custCfg = me.reportPageCfg;
            params.prjIds = [];
            zTreeOprObj.selectedPrjIDs = [];
            for (let node of nodes) {
                params.prjIds.push(node.ID);
                zTreeOprObj.selectedPrjIDs.push(node.ID);
            }
            CommonAjax.postEx("report_api/getGljSummaryReport", params, 60000, true,
                function(result){
                    hintBox.unWaitBox();
                    let pageRst = result;
                    let canvas = document.getElementById("rptCanvas");
                    if (pageRst && pageRst.items && pageRst.items.length > 0) {
                        me.resetAfter(pageRst);
                        me.currentRptPageRst = pageRst;
                        me.maxPages = pageRst.items.length;
                        me.currentPage = 1;
                        me.displayPageValue();
                        let size = JpcCanvasOutput.getReportSizeInPixel(me.currentRptPageRst, getScreenDPI());
                        canvas.width = size[0] + 20;
                        if (size[1] > size[0]) {
                            canvas.height = size[1] + 100;
                        } else {
                            canvas.height = size[1] + 50;
                        }
                        me.showPage(1, canvas);
                    } else {
                        //返回了无数据表
                        JpcCanvasOutput.cleanCanvas(canvas);
                        JpcCanvasOutput.drawPageBorder(me.currentRptPageRst, canvas, getScreenDPI());
                    }
                }, function(err){
                    hintBox.unWaitBox();
                }, function(ex){
                    hintBox.unWaitBox();
                }
            );
        }
    },
    requestSumAndNormalRptForPDF: function () {
        let rpt_names = [], bill_rpt_names = [], glj_rpt_names = [];
        let refRptTplIds = [], refBillSumPrjsIds = [], refGljSumPrjsIds = [];
        rptControlObj.getTplIdsCommon(refRptTplIds, refBillSumPrjsIds, refGljSumPrjsIds, rpt_names, bill_rpt_names, glj_rpt_names);
        let params = rptControlObj.creatCommonExportParam(refRptTplIds, refBillSumPrjsIds, refGljSumPrjsIds);
        params.sum_rpt_names = bill_rpt_names.concat(glj_rpt_names);
        params.rpt_names = rpt_names;
        params.isOneSheet = true;

        CommonAjax.postEx("report_api/createPdfFiles", params, WAIT_TIME_EXPORT, true, function(result){
                if (result) {
                    let uuIdUrls = [];
                    for (let uuIdObj of result) {
                        let uuIdUrl =  "/report_api/getFileByUUID/" + uuIdObj.uuid + "/" + stringUtil.replaceAll(uuIdObj.reportName, "#", "_") + "/pdf";
                        uuIdUrls.push(uuIdUrl);
                    }
                    downloadReport(uuIdUrls);
                } else {
                    //
                }
            }, null, null
        );
    },
    requestSumAndNormalRptForPDF_Ex: function () {
        let rpt_names = [], bill_rpt_names = [], glj_rpt_names = [];
        let refRptTplIds = [], refBillSumPrjsIds = [], refGljSumPrjsIds = [];
        rptControlObj.getTplIdsCommon(refRptTplIds, refBillSumPrjsIds, refGljSumPrjsIds, rpt_names, bill_rpt_names, glj_rpt_names);
        let params = rptControlObj.creatCommonExportParam(refRptTplIds, refBillSumPrjsIds, refGljSumPrjsIds);
        params.sum_rpt_names = bill_rpt_names.concat(glj_rpt_names);
        params.rpt_names = rpt_names;
        params.isOneSheet = true;
        CommonAjax.postEx("report_api/getMultiReports", params, WAIT_TIME_EXPORT, true,
            function(result){
                let pageSize = rptControlObj.getCurrentPageSize();
                for (let idx = 0; idx < result.length; idx++) {
                    let pageData = result[idx];
                    JpcJsPDFHelper.outputAsPdf(pageData, pageSize, result[idx][JV.NODE_PAGE_INFO][JV.NODE_MAIN_INFO_RPT_NAME]);
                }
            },
            function(failRst){
                console.log(failRst);
            },
            function(exceptionRst){
                console.log(exceptionRst);
            }
        );
    },
    requestSumAndNormalRptForMultiExcel: function () {
        let rpt_names = [], bill_rpt_names = [], glj_rpt_names = [];
        let refRptTplIds = [], refBillSumPrjsIds = [], refGljSumPrjsIds = [];
        rptControlObj.getTplIdsCommon(refRptTplIds, refBillSumPrjsIds, refGljSumPrjsIds, rpt_names, bill_rpt_names, glj_rpt_names);
        let params = rptControlObj.creatCommonExportParam(refRptTplIds, refBillSumPrjsIds, refGljSumPrjsIds);
        params.sum_rpt_names = bill_rpt_names.concat(glj_rpt_names);
        params.rpt_names = rpt_names;
        params.isOneSheet = true;
        $.bootstrapLoading.start();
        CommonAjax.postEx("report_api/createExcelFiles", params, WAIT_TIME_EXPORT, true, function(result){
                if (result) {
                    $.bootstrapLoading.end();
                    let uuIdUrls = [];
                    for (let uuIdObj of result) {
                        let uuIdUrl =  "/report_api/getFileByUUID/" + uuIdObj.uuid + "/" + stringUtil.replaceAll(uuIdObj.reportName, "#", "_") + "/xlsx";
                        uuIdUrls.push(uuIdUrl);
                    }
                    downloadReport(uuIdUrls);
                } else {
                    $.bootstrapLoading.end();
                }
            },
            function(failRst){
                $.bootstrapLoading.end();
                console.log(failRst);
            },
            function(exceptionRst){
                $.bootstrapLoading.end();
                console.log(exceptionRst);
            }
        );
    },
    requestSumAndNormalRptForAllInOneExcel: function () {
        let orgRptName = projectObj.project.projectInfo.name;
        let refRptTplIds = [], refBillSumPrjsIds = [], refGljSumPrjsIds = [];
        rptControlObj.getTplIdsCommon(refRptTplIds, refBillSumPrjsIds, refGljSumPrjsIds, null, null, null);
        let params = rptControlObj.creatCommonExportParam(refRptTplIds, refBillSumPrjsIds, refGljSumPrjsIds);
        params.rptName = orgRptName;
        $.bootstrapLoading.start();
        CommonAjax.postEx("report_api/createExcelFilesInOneBook", params, WAIT_TIME_EXPORT, true, function(result){
                if (result) {
                    $.bootstrapLoading.end();
                    let uuIdUrls = [];
                    let uuIdUrl =  "/report_api/getFileByUUID/" + result.uuid + "/" + stringUtil.replaceAll(result.reportName, "#", "_") + "/xlsx";
                    uuIdUrls.push(uuIdUrl);
                    downloadReport(uuIdUrls);
                } else {
                    $.bootstrapLoading.end();
                }
            },
            function(failRst){
                $.bootstrapLoading.end();
                console.log(failRst);
            },
            function(exceptionRst){
                $.bootstrapLoading.end();
                console.log(exceptionRst);
            }
        );
    },
    showPage: function (pageNum, canvas) {
        let me = zTreeOprObj;
        if (pageNum >= 1 && pageNum <= me.maxPages) {
            me.currentPage = pageNum;
            JpcCanvasOutput.cleanCanvas(canvas);
            JpcCanvasOutput.drawPageBorder(me.currentRptPageRst, canvas, getScreenDPI());
            // JpcCanvasOutput.drawWaterMarks(canvas, zTreeOprObj.waterMarks);
            JpcCanvasOutput.drawToCanvas(me.currentRptPageRst, canvas, me.currentPage);
        }
        me.displayPageValue();
    },
    displayPageValue: function() {
        let me = zTreeOprObj;
        $("#rpt_page_num").get(0).value = me.currentPage + "/" + me.maxPages;
    }
};

let canvasOprObj = {
    canvasOnMouseMove: function (event) {
        if (zTreeOprObj.currentNode) {
            let x = event.offsetX - JpcCanvasOutput.offsetX, canvas = event.originalTarget;
            if (!(canvas)) canvas = event.target; //chrome浏览器不认event.originalTarget,只认event.target或event.currentTarget
            if (x < PRE_PAGE_OFFSET) {
                canvas.style.cursor = "url(/web/building_saas/img/PreviousPage.cur), auto";
            } else if ((canvas.width - x) < NEXT_PAGE_OFFSET) {
                canvas.style.cursor = "url(/web/building_saas/img/NextPage.cur), auto";
            } else {
                canvas.style.cursor = "";
            }
        }
    },
    canvasOnClick: function(event){
        if (zTreeOprObj.currentNode) {
            let x = event.offsetX - JpcCanvasOutput.offsetX, canvas = event.originalTarget;
            if (!(canvas)) canvas = event.target; //chrome浏览器不认event.originalTarget,只认event.target或event.currentTarget
            if (x < FIRST_PAGE_OFFSET) {
                zTreeOprObj.showPage(1, canvas);
            } else if (x < PRE_PAGE_OFFSET) {
                zTreeOprObj.showPage(zTreeOprObj.currentPage - 1, canvas);
            } else if ((canvas.width - x) < LAST_PAGE_OFFSET) {
                zTreeOprObj.showPage(zTreeOprObj.maxPages, canvas);
            } else if ((canvas.width - x) < NEXT_PAGE_OFFSET) {
                zTreeOprObj.showPage(zTreeOprObj.currentPage + 1, canvas);
            }
        }
    }
};

let rptControlObj = {
    currentOutputType: "Excel",
    currentDownloadUrl: null,
    currentDownloadIdx: 0,
    getCurrentPageSize: function() {
        // let rst = "A4";
        let rst = document.getElementById("btnRptPageSize").innerHTML.trim();
        //btnRptPageSize
        return rst;
    },
    getCurrentOrientation: function() {
        // let rst = "横向";
        let rst = document.getElementById("btnRptOrientation").innerHTML.trim();
        return rst;
    },
    getCurrentReportOption: function() {
        //
    },
    changeType: function(newType) {
        let me = rptControlObj;
        let excelDom = document.getElementById("EXCEL_TYPE");
        let pdfDom = document.getElementById("PDF_TYPE");
        if (newType === "Excel") {
            excelDom.className = "btn btn-block btn-primary";
            pdfDom.className = "btn btn-block btn-outline-secondary";
            me.currentOutputType = newType;
        } else if (newType === "PDF") {
            excelDom.className = "btn btn-block btn-outline-secondary";
            pdfDom.className = "btn btn-block btn-primary";
            me.currentOutputType = newType;
        } else {
            //me.currentOutputType = newType;
        }
    },
    outputRpt: function() {
        let me = rptControlObj;
        if (me.currentOutputType === "Excel") {
            me.getExcel();
        } else if (me.currentOutputType === "PDF") {
            me.getPDF();
        } else {
            //other types if needed.
        }
    },
    getTplIdsCommon: function (refRptTplIds, refBillSumPrjsIds, refGljSumPrjsIds, rpt_names, bill_rpt_names, glj_rpt_names) {
        for (let node of zTreeOprObj.checkedRptTplNodes) {
            if (node.hasOwnProperty('flags') && node.flags.hasOwnProperty('reportType') && node['flags']['reportType'] !== 'NA') {
                if (node['flags']['reportType'] === 'billSummary') {
                    refBillSumPrjsIds.push(node.refId);
                    if (bill_rpt_names) bill_rpt_names.push(node.name);
                } else if (node['flags']['reportType'] === 'gljSummary') {
                    refGljSumPrjsIds.push(node.refId);
                    if (glj_rpt_names) glj_rpt_names.push(node.name);
                }
            } else {
                refRptTplIds.push(node.refId);
                if (rpt_names) rpt_names.push(node.name);
            }
        }
    },
    creatCommonExportParam: function (refRptTplIds, refBillSumPrjsIds, refGljSumPrjsIds) {
        let nodes = (zTreeOprObj.prjFolderTreeObj === null)?[]:zTreeOprObj.prjFolderTreeObj.getCheckedNodes(true);
        let rst = {};
        rst.prj_id = projectObj.project.projectInfo.ID;
        rst.rpt_ids = refRptTplIds;
        rst.rpt_bill_tpl_ids = refBillSumPrjsIds;
        rst.rpt_glj_tpl_ids = refGljSumPrjsIds;
        rst.prjIds = [];
        zTreeOprObj.selectedPrjIDs = [];
        for (let node of nodes) {
            if (node.level > 0) {
                rst.prjIds.push(node.ID);
                zTreeOprObj.selectedPrjIDs.push(node.ID);
            }
        }
        // rst.sum_rpt_names = bill_rpt_names.concat(glj_rpt_names);
        // rst.rpt_names = rpt_names;
        // rst.isOneSheet = true;
        rst.pageSize = rptControlObj.getCurrentPageSize();
        rst.orientation = ((zTreeOprObj.checkedRptTplNodes.length > 1)?null:rptControlObj.getCurrentOrientation());
        rst.custCfg = zTreeOprObj.reportPageCfg;
        rst.option = "normal";
        return rst;
    },
    getAllInOneBook: function () {
        if (zTreeOprObj.checkedRptTplNodes && zTreeOprObj.checkedRptTplNodes.length > 0) {
            let me = rptControlObj;
            let orgRptName = projectObj.project.projectInfo.name;
            let refRptTplIds = [], refBillSumPrjsIds = [], refGljSumPrjsIds = [];
            rptControlObj.getTplIdsCommon(refRptTplIds, refBillSumPrjsIds, refGljSumPrjsIds);
            if (zTreeOprObj.selectedPrjIDs.length > 0 && (refBillSumPrjsIds.length > 0 || refGljSumPrjsIds.length > 0)) {
                let params = rptControlObj.creatCommonExportParam(refRptTplIds, refBillSumPrjsIds, refGljSumPrjsIds);
                params.rptName = orgRptName;
                $.bootstrapLoading.start();
                CommonAjax.postEx("report_api/createExcelFilesInOneBook", params, WAIT_TIME_EXPORT, true, function(result){
                        if (result) {
                            $.bootstrapLoading.end();
                            let uuIdUrls = [];
                            let uuIdUrl =  "/report_api/getFileByUUID/" + result.uuid + "/" + stringUtil.replaceAll(result.reportName, "#", "_") + "/xlsx";
                            uuIdUrls.push(uuIdUrl);
                            downloadReport(uuIdUrls);
                        } else {
                            $.bootstrapLoading.end();
                        }
                    },
                    function(failRst){
                        $.bootstrapLoading.end();
                        console.log(failRst);
                    },
                    function(exceptionRst){
                        $.bootstrapLoading.end();
                        console.log(exceptionRst);
                    }
                );
            } else {
                if (refBillSumPrjsIds.length > 0 || refGljSumPrjsIds.length > 0) {
                    $("#divReqBillSummary")[0].style.display = "none";
                    $("#divReqGljSummary")[0].style.display = "none";
                    $("#divReqCommonSummaryExcel")[0].style.display = "";
                    $("#divReqCommonSummaryMultiExcel")[0].style.display = "none";
                    $("#divReqCommonSummaryPDF")[0].style.display = "none";
                    zTreeOprObj.requestPrjFolderCommon(); //先处理需要汇总的报表，走另外一个分支
                } else if (refRptTplIds.length > 0) {
                    let params = {};
                    params.prj_id = projectObj.project.projectInfo.ID;
                    params.rpt_ids = refRptTplIds;
                    params.rptName = orgRptName;
                    params.pageSize = me.getCurrentPageSize();
                    params.orientation = ((zTreeOprObj.checkedRptTplNodes.length > 1)?null:me.getCurrentOrientation());
                    params.custCfg = zTreeOprObj.reportPageCfg;
                    params.option = "normal";
                    $.bootstrapLoading.start();
                    CommonAjax.postEx("report_api/createExcelFilesInOneBook", params, WAIT_TIME_EXPORT, true, function(result){
                            if (result) {
                                $.bootstrapLoading.end();
                                let uuIdUrls = [];
                                let uuIdUrl =  "/report_api/getFileByUUID/" + result.uuid + "/" + stringUtil.replaceAll(result.reportName, "#", "_") + "/xlsx";
                                uuIdUrls.push(uuIdUrl);
                                downloadReport(uuIdUrls);
                            } else {
                                $.bootstrapLoading.end();
                            }
                        },
                        function(failRst){
                            $.bootstrapLoading.end();
                            console.log(failRst);
                        },
                        function(exceptionRst){
                            $.bootstrapLoading.end();
                            console.log(exceptionRst);
                        }
                    );
                }
            }
        }
    },
    getAllIndividualExcelBook: function () {
        let me = rptControlObj;
        if (zTreeOprObj.checkedRptTplNodes && zTreeOprObj.checkedRptTplNodes.length > 0) {
            let refRptTplIds = [], refBillSumPrjsIds = [], refGljSumPrjsIds = [];
            let rpt_names = [], bill_rpt_names = [], glj_rpt_names = [];
            rptControlObj.getTplIdsCommon(refRptTplIds, refBillSumPrjsIds, refGljSumPrjsIds, rpt_names, bill_rpt_names, glj_rpt_names);
            if (zTreeOprObj.selectedPrjIDs.length > 0 && (glj_rpt_names.length > 0 || bill_rpt_names.length > 0)) {
                let params = rptControlObj.creatCommonExportParam(refRptTplIds, refBillSumPrjsIds, refGljSumPrjsIds);
                params.prj_id = projectObj.project.projectInfo.ID;
                params.sum_rpt_names = bill_rpt_names.concat(glj_rpt_names);
                params.rpt_names = rpt_names;
                params.isOneSheet = true;
                params.rptName = projectObj.project.projectInfo.name;
                $.bootstrapLoading.start();
                CommonAjax.postEx("report_api/createExcelFiles", params, WAIT_TIME_EXPORT, true, function(result){
                        if (result) {
                            $.bootstrapLoading.end();
                            let uuIdUrls = [];
                            for (let uuIdObj of result) {
                                let uuIdUrl =  "/report_api/getFileByUUID/" + uuIdObj.uuid + "/" + stringUtil.replaceAll(uuIdObj.reportName, "#", "_") + "/xlsx";
                                uuIdUrls.push(uuIdUrl);
                            }
                            downloadReport(uuIdUrls);
                        } else {
                            $.bootstrapLoading.end();
                        }
                    },
                    function(failRst){
                        $.bootstrapLoading.end();
                        console.log(failRst);
                    },
                    function(exceptionRst){
                        $.bootstrapLoading.end();
                        console.log(exceptionRst);
                    }
                );
            } else {
                if (refBillSumPrjsIds.length > 0 || refGljSumPrjsIds.length > 0) {
                    $("#divReqBillSummary")[0].style.display = "none";
                    $("#divReqGljSummary")[0].style.display = "none";
                    $("#divReqCommonSummaryExcel")[0].style.display = "none";
                    $("#divReqCommonSummaryMultiExcel")[0].style.display = "";
                    $("#divReqCommonSummaryPDF")[0].style.display = "none";
                    zTreeOprObj.requestPrjFolderCommon(); //先处理需要汇总的报表，走另外一个分支
                } else if (refRptTplIds.length > 0) {
                    let params = {};
                    params.prj_id = projectObj.project.projectInfo.ID;
                    params.rpt_ids = refRptTplIds;
                    params.rpt_names = rpt_names;
                    params.pageSize = me.getCurrentPageSize();
                    params.orientation = ((zTreeOprObj.checkedRptTplNodes.length > 1)?null:me.getCurrentOrientation());
                    params.isOneSheet = true;
                    params.custCfg = zTreeOprObj.reportPageCfg;
                    params.option = "normal";
                    $.bootstrapLoading.start();
                    CommonAjax.postEx("report_api/createExcelFiles", params, WAIT_TIME_EXPORT, true, function(result){
                            if (result) {
                                $.bootstrapLoading.end();
                                let uuIdUrls = [];
                                for (let uuIdObj of result) {
                                    let uuIdUrl =  "/report_api/getFileByUUID/" + uuIdObj.uuid + "/" + stringUtil.replaceAll(uuIdObj.reportName, "#", "_") + "/xlsx";
                                    uuIdUrls.push(uuIdUrl);
                                }
                                downloadReport(uuIdUrls);
                            } else {
                                $.bootstrapLoading.end();
                            }
                        },
                        function(failRst){
                            $.bootstrapLoading.end();
                            console.log(failRst);
                        },
                        function(exceptionRst){
                            $.bootstrapLoading.end();
                            console.log(exceptionRst);
                        }
                    );
                }
            }
        }
    },
    checkAndGetExcel: function () {
        if (zTreeOprObj.isFreeUser) {
            hintBox.versionBox('对不起，您当前使用的是免费公用版，不提供导出、打印报表功能，请联系我们的客服人员。');
            return;
        }
        if (zTreeOprObj.treeObj) {
            let chkNodes = zTreeOprObj.treeObj.getCheckedNodes(true);
            if (chkNodes.length > 0) {
                $("#show_excel_output_cfg").trigger("click");
            } else {
                rptControlObj.getAllIndividualExcelBook();
            }
        }
    },
    getExcel: function () {
        let me = rptControlObj;
        if ($("#excelExportType_AllInOneBook").get(0).checked) {
            me.getAllInOneBook();
        } else if ($("#excelExportType_IndividualBook").get(0).checked) {
            me.getAllIndividualExcelBook();
        }
    },
    getPDF: function () {
        let me = rptControlObj;
        if (zTreeOprObj.checkedRptTplNodes && zTreeOprObj.checkedRptTplNodes.length > 0) {
            let refRptTplIds = [], refBillSumPrjsIds = [], refGljSumPrjsIds = [];
            let rpt_names = [], bill_rpt_names = [], glj_rpt_names = [];
            rptControlObj.getTplIdsCommon(refRptTplIds, refBillSumPrjsIds, refGljSumPrjsIds, rpt_names, bill_rpt_names, glj_rpt_names);
            if (zTreeOprObj.selectedPrjIDs.length > 0 && (glj_rpt_names.length > 0 || bill_rpt_names.length > 0)) {
                let params = rptControlObj.creatCommonExportParam();
                params.prj_id = projectObj.project.projectInfo.ID;
                params.sum_rpt_names = bill_rpt_names.concat(glj_rpt_names);
                params.rpt_ids = refRptTplIds;
                params.rpt_bill_tpl_ids = refBillSumPrjsIds;
                params.rpt_glj_tpl_ids = refGljSumPrjsIds;
                params.rpt_names = rpt_names;
                params.isOneSheet = true;
                params.rptName = projectObj.project.projectInfo.name;
                CommonAjax.postEx("report_api/createPdfFiles", params, WAIT_TIME_EXPORT, true, function(result){
                        if (result) {
                            let uuIdUrls = [];
                            for (let uuIdObj of result) {
                                let uuIdUrl =  "/report_api/getFileByUUID/" + uuIdObj.uuid + "/" + stringUtil.replaceAll(uuIdObj.reportName, "#", "_") + "/pdf";
                                uuIdUrls.push(uuIdUrl);
                            }
                            downloadReport(uuIdUrls);
                        } else {
                            //
                        }
                    }, null, null
                );
            } else {
                if (refBillSumPrjsIds.length > 0 || refGljSumPrjsIds.length > 0) {
                    $("#divReqBillSummary")[0].style.display = "none";
                    $("#divReqGljSummary")[0].style.display = "none";
                    $("#divReqCommonSummaryExcel")[0].style.display = "none";
                    $("#divReqCommonSummaryMultiExcel")[0].style.display = "none";
                    $("#divReqCommonSummaryPDF")[0].style.display = "";
                    zTreeOprObj.requestPrjFolderCommon(); //先处理需要汇总的报表，走另外一个分支
                } else if (refRptTplIds.length > 0) {
                    let params = {};
                    params.prj_id = projectObj.project.projectInfo.ID;
                    params.rpt_ids = refRptTplIds;
                    params.rpt_names = rpt_names;
                    params.pageSize = me.getCurrentPageSize();
                    params.orientation = ((zTreeOprObj.checkedRptTplNodes.length > 1)?null:me.getCurrentOrientation());
                    params.custCfg = zTreeOprObj.reportPageCfg;
                    params.option = "normal";
                    CommonAjax.postEx("report_api/createPdfFiles", params, WAIT_TIME_EXPORT, true, function(result){
                            if (result) {
                                let uuIdUrls = [];
                                for (let uuIdObj of result) {
                                    let uuIdUrl =  "/report_api/getFileByUUID/" + uuIdObj.uuid + "/" + stringUtil.replaceAll(uuIdObj.reportName, "#", "_") + "/pdf";
                                    uuIdUrls.push(uuIdUrl);
                                }
                                downloadReport(uuIdUrls);
                            } else {
                                //
                            }
                        }, null, null
                    );
                }
            }
        }
    },
    _hidePdfIniPage: function () {
        if ($('#ini_PDF_cover').is(':visible')) {
            $("#ini_PDF_Btn_Cancel").trigger("click");
        }
    },
    getPdfFontCallback: function(fontProperty) {
        let me = rptControlObj;
        rptTplObj.pdfFont['SmartSimsun'].push(fontProperty);
        if (rptTplObj.pdfFont['SmartSimsun'].length === 2) {
            me._hidePdfIniPage();
            setTimeout(function(){
                me.getPDFEx();
            }, 20);
            // me.getPDFEx();
        }
    },
    getPDFPre: function () {
        let me = rptControlObj;
        if (zTreeOprObj.isFreeUser) {
            hintBox.versionBox('对不起，您当前使用的是免费公用版，不提供导出、打印报表功能，请联系我们的客服人员。');
            return;
        }
        if (rptTplObj.pdfFont['SmartSimsun'].length === 2) {
            $.bootstrapLoading.start();
            me.getPDFEx();
        } else {
            // dynamicLoadJs('/lib/jspdf/SmartSimsun-normal.js', 'normal', me.getPdfFontCallback);
            // dynamicLoadJs('/lib/jspdf/SmartSimsun-bold.js', 'bold', me.getPdfFontCallback);
            $("#ini_PDF_Btn").trigger("click");
            dynamicLoadJs('https://d2.smartcost.com.cn/cach/SmartSimsun-normal.js', 'normal', me.getPdfFontCallback);
            dynamicLoadJs('https://d2.smartcost.com.cn/cach/SmartSimsun-bold.js', 'bold', me.getPdfFontCallback);
        }
    },
    getPDFEx: function () {
        let me = rptControlObj;
        if (zTreeOprObj.checkedRptTplNodes && zTreeOprObj.checkedRptTplNodes.length > 0) {
            let refRptTplIds = [], refBillSumPrjsIds = [], refGljSumPrjsIds = [];
            let rpt_names = [], bill_rpt_names = [], glj_rpt_names = [];
            rptControlObj.getTplIdsCommon(refRptTplIds, refBillSumPrjsIds, refGljSumPrjsIds, rpt_names, bill_rpt_names, glj_rpt_names);
            if (zTreeOprObj.selectedPrjIDs.length > 0 && (glj_rpt_names.length > 0 || bill_rpt_names.length > 0)) {
                let params = rptControlObj.creatCommonExportParam();
                params.prj_id = projectObj.project.projectInfo.ID;
                params.sum_rpt_names = bill_rpt_names.concat(glj_rpt_names);
                params.rpt_ids = refRptTplIds;
                params.rpt_bill_tpl_ids = refBillSumPrjsIds;
                params.rpt_glj_tpl_ids = refGljSumPrjsIds;
                params.rpt_names = rpt_names;
                params.isOneSheet = true;
                params.rptName = projectObj.project.projectInfo.name;
                CommonAjax.postEx("report_api/getMultiReports", params, WAIT_TIME_EXPORT, true,
                    function(result){
                        $.bootstrapLoading.end();
                        me._hidePdfIniPage();
                        let pageSize = rptControlObj.getCurrentPageSize();
                        for (let idx = 0; idx < result.length; idx++) {
                            let pageData = result[idx];
                            JpcJsPDFHelper.outputAsPdf(pageData, pageSize, result[idx][JV.NODE_PAGE_INFO][JV.NODE_MAIN_INFO_RPT_NAME]);
                        }
                    },
                    function(failRst){
                        $.bootstrapLoading.end();
                        me._hidePdfIniPage();
                        console.log(failRst);
                    },
                    function(exceptionRst){
                        $.bootstrapLoading.end();
                        me._hidePdfIniPage();
                        console.log(exceptionRst);
                    }
                );
            } else {
                if (refBillSumPrjsIds.length > 0 || refGljSumPrjsIds.length > 0) {
                    $("#divReqBillSummary")[0].style.display = "none";
                    $("#divReqGljSummary")[0].style.display = "none";
                    $("#divReqCommonSummaryExcel")[0].style.display = "none";
                    $("#divReqCommonSummaryMultiExcel")[0].style.display = "none";
                    $("#divReqCommonSummaryPDF")[0].style.display = "";
                    zTreeOprObj.requestPrjFolderCommon(); //先处理需要汇总的报表，走另外一个分支
                } else if (refRptTplIds.length > 0) {
                    if (refRptTplIds.length > 1) {
                        let params = {};
                        params.prj_id = projectObj.project.projectInfo.ID;
                        params.rpt_ids = refRptTplIds;
                        params.rpt_names = rpt_names;
                        params.pageSize = me.getCurrentPageSize();
                        params.orientation = ((zTreeOprObj.checkedRptTplNodes.length > 1)?null:me.getCurrentOrientation());
                        params.custCfg = zTreeOprObj.reportPageCfg;
                        params.option = "normal";
                        CommonAjax.postEx("report_api/getMultiReports", params, WAIT_TIME_EXPORT, true,
                            function(result){
                                $.bootstrapLoading.end();
                                me._hidePdfIniPage();
                                let pageSize = rptControlObj.getCurrentPageSize();
                                for (let idx = 0; idx < result.length; idx++) {
                                    let pageData = result[idx];
                                    JpcJsPDFHelper.outputAsPdf(pageData, pageSize, rpt_names[idx]);
                                }
                            },
                            function(failRst){
                                $.bootstrapLoading.end();
                                me._hidePdfIniPage();
                                console.log(failRst);
                            },
                            function(exceptionRst){
                                $.bootstrapLoading.end();
                                me._hidePdfIniPage();
                                console.log(exceptionRst);
                            }
                        );
                    } else {
                        //这个分支是为了减少请求，用户已经点过的表，又没有勾选，那么就直接导出成PDF
                        let pageSize = rptControlObj.getCurrentPageSize();
                        let pageData = zTreeOprObj.currentRptPageRst;
                        $.bootstrapLoading.end();
                        me._hidePdfIniPage();
                        JpcJsPDFHelper.outputAsPdf(pageData, pageSize, rpt_names[0]);
                    }
                }
            }
        }
    },
    firstPage: function(dom) {
        let canvas = document.getElementById("rptCanvas");
        zTreeOprObj.showPage(1, canvas);
    },
    prePage: function(dom) {
        let canvas = document.getElementById("rptCanvas");
        zTreeOprObj.showPage(zTreeOprObj.currentPage - 1, canvas);
    },
    nextPage: function(dom) {
        let canvas = document.getElementById("rptCanvas");
        zTreeOprObj.showPage(zTreeOprObj.currentPage + 1, canvas);
    },
    lastPage: function(dom) {
        let me = zTreeOprObj;
        let canvas = document.getElementById("rptCanvas");
        zTreeOprObj.showPage(me.maxPages, canvas);
    },
    onKeydown: function (event, dom) {
        let me = zTreeOprObj, keyPressed = null;
        if (window.event) {
            keyPressed = window.event.keyCode; // IE/Chrome
        } else {
            keyPressed = event.which; // Firefox
        }
        if (keyPressed === 13) {
            let pageNum = 1;
            try {
                pageNum = parseInt(dom.value);
            } catch (e) {
                pageNum = 1;
            }
            let canvas = document.getElementById("rptCanvas");
            if (pageNum < 1) {
                pageNum = 1;
            } else if (pageNum > me.maxPages) {
                pageNum = me.maxPages;
            }
            zTreeOprObj.showPage(pageNum, canvas);
            return false;
        }
    },
    changeMargin: function(marginPropStr, marginDom) {
        zTreeOprObj.reportPageCfg.margins[marginPropStr] = marginDom.value;
    },
    changeFontMain: function(CfgDispName, fontProperty, fontDom) {
        for (let font of zTreeOprObj.reportPageCfg.fonts) {
            if (font["CfgDispName"] === CfgDispName) {
                font[fontProperty] = fontDom.value;
                break;
            }
        }
    },
    changeCfgOption: function (optStr, dom) {
        zTreeOprObj.reportPageCfg[optStr] = dom.checked;
    },
    changeFontAdhoc: function(CfgDispName, fontProperty, fontDom) {
        for (let font of zTreeOprObj.reportPageCfg.fonts) {
            if (font["CfgDispName"] === CfgDispName) {
                if (font[fontProperty] === 'T') {
                    font[fontProperty] = 'F';
                    fontDom.className = "btn btn-sm btn-outline-secondary";
                } else {
                    font[fontProperty] = 'T';
                    fontDom.className = "btn btn-sm btn-outline-secondary active";
                }
                break;
            }
        }
    },
    restoreCustCFG: function () {
        let me = this;
        zTreeOprObj.renderRptCfg(zTreeOprObj.defReportPageCfg);
        zTreeOprObj.extractRptCfg(zTreeOprObj.reportPageCfg);
        me.saveCustCfg();
    },
    saveCustCfg: function() {
        let params = {};
        params.custCfg = zTreeOprObj.reportPageCfg;
        CommonAjax.postEx("report_tpl_api/saveCustomerCfg", params, 20000, true, function(result){
                // alert("Save successfully!");
                $("#update_msg_response")[0].style.color = "green";
                $("#update_msg_response")[0].innerHTML = " (保存成功!)";
                setTimeout(function(){
                    $("#update_msg_response")[0].innerHTML = "";
                }, 1000);
            }, function (failRst) {
                $("#update_msg_response")[0].style.color = "red";
                $("#update_msg_response")[0].innerHTML = " (保存失败!)";
                setTimeout(function(){
                    $("#update_msg_response")[0].innerHTML = "";
                }, 1000);
            }, null
        );
    },
    confirmCfgChange: function() {
        zTreeOprObj.changeCfg();
    }
};

function downloadReport(urls) {
    //考虑到多个报表下载，一些浏览器（如chrome）不允许一下子下载多个文件，得缓缓处理，统一在这处理
    rptControlObj.currentDownloadUrl = null;
    rptControlObj.currentDownloadIdx = 0;
    let private_download = function() {
        if (rptControlObj.currentDownloadIdx >= 0 && rptControlObj.currentDownloadIdx < urls.length) {
            rptControlObj.currentDownloadUrl = urls[rptControlObj.currentDownloadIdx];
            rptControlObj.currentDownloadIdx++;
            window.location = rptControlObj.currentDownloadUrl;
            setTimeout(private_download, 2000);
        }
    }
    private_download();
}

function dynamicLoadJs(url, type, callback) {
    let head = document.getElementsByTagName('head')[0];
    let script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    if(callback) {
        script.onload = script.onreadystatechange = function (event) {
            // console.log('this.readyState: ' + this.readyState);
            callback(type);
            script.onload = script.onreadystatechange = null;
            // if (this.readyState === "loaded" || this.readyState === "complete"){
            // }
        };
    }
    head.appendChild(script);
}

function dynamicLoadCss(url) {
    let head = document.getElementsByTagName('head')[0];
    let link = document.createElement('link');
    link.type='text/css';
    link.rel = 'stylesheet';
    link.href = url;
    head.appendChild(link);
}