/**
 * 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,
    project_tree: null,
    pdfFont: {'SmartSimsun': [], 'simhei': [], 'simkai': []},
    iniPage: function() {
        let me = this;
        if (!me.hasInitialized) {
            zTreeOprObj.getCustomerCfg();
            zTreeOprObj.getReportTemplateTree();
            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');
            }
            //收集本单位工程所属的建设项目下所有单位工程id用
            // GetAllProjectData(function (datas) {
            //     //
            // }
            let params = {
                rootProjectID: projectObj.project.property.rootProjectID,
                user_id: userID
            };
            CommonAjax.post("pm/api/getAllUnitProjects", params, function(result) {
                // console.log(result);
                me.project_tree = result;
                // console.log(me.getAllPrjIds());
            });
        }
    },
    
    getAllPrjIds: function() {
        let me = this;
        let rst = [];
        if (me.project_tree) {
            for (let prj of me.project_tree) {
                rst.push(prj.ID);
            }
        }
        return rst;
    },

    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,
    currentNode: null,
    checkedRptTplNodes: null,
    currentRptPageRst: null,
    reportPageCfg: null,
    defReportPageCfg: null,
    currentPage: 1,
    maxPages: 0,
    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;
            }
            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) {
                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);
                            }
                        }
                    }
                }
            }
            private_remove_hide_item(result);
            for (let topNode of result) {
                if (topNode.userId === "-100") {
                    topNode.name = topNode.name + " - 标准报表";
                } else {
                    topNode.name = topNode.name + " - 定制报表";
                }
            }
            zTreeHelper.createTreeDirectly(result, 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: async function(event,treeId,treeNode) {
        let me = zTreeOprObj;
        if (treeNode.nodeType === TPL_TYPE_TEMPLATE && treeNode.refId > 0) {
            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;
            params.flag = null;
            if (treeNode.hasOwnProperty('flags')) {
                if (treeNode.flags.hasOwnProperty('auditType') && treeNode.flags.auditType === 'audit_compare') {
                    let pids = [];
                    let comp_pid = await compareObject.getCompareID(); //返回单个对应的project ID
                    if (comp_pid !== null) {
                        pids.push(projectObj.project.projectInfo.ID);
                        pids.push(comp_pid);
                        params.prj_ids = pids;
                    } else {
                        /*
                        params.prj_ids = [25062, 25082]; // hard code 测试项目：酉阳县东部沿海产业转移承接基地建设项目（一期）一标段 + 审定
                        /*/
                        alert('未设置审核对比项目！');
                        exit;
                        //*/
                    }
                } else {
                    params.prj_ids = rptTplObj.getAllPrjIds();
                }
                params.flag = treeNode.flags;
            }
            me.currentNode = treeNode;
            me.requestReport(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: async function() {
        let me = zTreeOprObj;
        let params = {};
        params.pageSize = rptControlObj.getCurrentPageSize();
        params.orientation = rptControlObj.getCurrentOrientation();
        params.rpt_tpl_id = me.currentNode.refId;
        params.flag = null;
        // if (me.currentNode.hasOwnProperty('flags')) {
        //     params.flag = me.currentNode.flags;
        //     params.prj_ids = rptTplObj.getAllPrjIds();
        // }
        if (me.currentNode.hasOwnProperty('flags')) {
            if (me.currentNode.flags.hasOwnProperty('auditType') && me.currentNode.flags.auditType === 'audit_compare') {
                let pids = [];
                let comp_pid = await compareObject.getCompareID(); //返回单个对应的project ID
                if (comp_pid !== null) {
                    pids.push(projectObj.project.projectInfo.ID);
                    pids.push(comp_pid);
                    params.prj_ids = pids;
                } else {
                    alert('未设置审核对比项目！');
                    exit;
                }
            } else {
                params.prj_ids = rptTplObj.getAllPrjIds();
            }
            params.flag = me.currentNode.flags;
        }        
        params.prj_id = projectObj.project.projectInfo.ID;
        params.custCfg = me.reportPageCfg;
        me.requestReport(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 = "横向";
        }
    },
    requestReport: function (params) {
        let me = zTreeOprObj;
        params.compilation = projectObj.project.projectInfo.compilation;
        hintBox.waitBox();
        CommonAjax.postEx("report_api/getReport", params, 15000, 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();
            }
        );
    },
    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.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 < PRE_PAGE_OFFSET) {
                zTreeOprObj.showPage(zTreeOprObj.currentPage - 1, 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.
        }
    },
    getAllInOneBook: async function () {
        if (zTreeOprObj.checkedRptTplNodes && zTreeOprObj.checkedRptTplNodes.length > 0) {
            let me = rptControlObj;
            let orgRptName = projectObj.project.projectInfo.name;
            let refRptTplIds = [], compare_ids = [];
            let flags = [];
            let params = {};
            for (let node of zTreeOprObj.checkedRptTplNodes) {
                refRptTplIds.push(node.refId);
                let flag = null;
                if (node.hasOwnProperty('flags')) {
                    flag = node.flags;
                    params.prj_ids = rptTplObj.getAllPrjIds();
                    if (flag.auditType === 'audit_compare') {
                        let pids = [];
                        let comp_pid = await compareObject.getCompareID(); //返回单个对应的project ID
                        if (comp_pid !== null) {
                            pids.push(projectObj.project.projectInfo.ID);
                            pids.push(comp_pid);
                        }
                        compare_ids.push(pids);
                    } else {
                        compare_ids.push([]);
                    }
                } else {
                    compare_ids.push([]);
                }
                flags.push(flag);
            }
            params.prj_id = projectObj.project.projectInfo.ID;
            params.compare_ids = compare_ids;
            params.rpt_ids = refRptTplIds;
            params.flags = flags;
            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: async function () {
        let me = rptControlObj;
        if (zTreeOprObj.checkedRptTplNodes && zTreeOprObj.checkedRptTplNodes.length > 0) {
            let rpt_ids = [], flags = [], rpt_names = [], compare_ids = [];
            let params = {};
            for (let tplNode of zTreeOprObj.checkedRptTplNodes) {
                rpt_ids.push(tplNode.refId);
                rpt_names.push(tplNode.name)
                let flag = null;
                if (tplNode.hasOwnProperty('flags')) {
                    flag = tplNode.flags;
                    params.prj_ids = rptTplObj.getAllPrjIds();
                    if (flag.auditType === 'audit_compare') {
                        let pids = [];
                        let comp_pid = await compareObject.getCompareID(); //返回单个对应的project ID
                        if (comp_pid !== null) {
                            pids.push(projectObj.project.projectInfo.ID);
                            pids.push(comp_pid);
                        }
                        compare_ids.push(pids);
                    } else {
                        compare_ids.push([]);
                    }
                } else {
                    compare_ids.push([]);
                }
                flags.push(flag);
            }
            params.prj_id = projectObj.project.projectInfo.ID;
            params.compare_ids = compare_ids;
            params.rpt_ids = rpt_ids;
            params.flags = flags;
            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.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: async function() {
        let me = rptControlObj;
        if (zTreeOprObj.checkedRptTplNodes && zTreeOprObj.checkedRptTplNodes.length > 0) {
            let rpt_ids = [], flags = [], rpt_names = [], compare_ids = [];
            for (let tplNode of zTreeOprObj.checkedRptTplNodes) {
                rpt_ids.push(tplNode.refId);
                rpt_names.push(tplNode.name);
                let flag = null;
                if (tplNode.hasOwnProperty('flags')) {
                    flag = tplNode.flags;
                    if (flag.auditType === 'audit_compare') {
                        let pids = [];
                        let comp_pid = await compareObject.getCompareID(); //返回单个对应的project ID
                        if (comp_pid !== null) {
                            pids.push(projectObj.project.projectInfo.ID);
                            pids.push(comp_pid);
                        }
                        compare_ids.push(pids);
                    } else {
                        compare_ids.push([]);
                    }
                } else {
                    compare_ids.push([]);
                }
                flags.push(flag);
            }
            let params = {};
            params.prj_id = projectObj.project.projectInfo.ID;
            params.compare_ids = compare_ids;
            params.rpt_ids = rpt_ids;
            params.flags = flags;
            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";
            params.compilation = projectObj.project.projectInfo.compilation;
            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
            );
        }
    },
    getPdfFontCallback: function(fontProperty) {
        let me = rptControlObj;
        rptTplObj.pdfFont['SmartSimsun'].push(fontProperty);
        if (rptTplObj.pdfFont['SmartSimsun'].length === 2) {
            me.getPDFEx();
        }
    },
    getPDFPre: function () {
        let me = rptControlObj;
        if (rptTplObj.pdfFont['SmartSimsun'].length === 2) {
            $.bootstrapLoading.start();
            me.getPDFEx();
        } else {
            $("#ini_PDF_Btn").trigger("click");
            // dynamicLoadJs('/lib/jspdf/SmartSimsun-normal.js',"normal", me.getPdfFontCallback);
            // dynamicLoadJs('/lib/jspdf/SmartSimsun-bold.js',"bold", me.getPdfFontCallback);
            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: async function () {
        if (zTreeOprObj.checkedRptTplNodes && zTreeOprObj.checkedRptTplNodes.length > 0) {
            let rptIds = [], rpt_names = [], flagsArr = [], compare_ids = [];
            let params = {};
            params.pageSize = rptControlObj.getCurrentPageSize();
            params.orientation = ((zTreeOprObj.checkedRptTplNodes.length > 1)?null:rptControlObj.getCurrentOrientation());
            params.custCfg = zTreeOprObj.reportPageCfg;
            params.prj_id = projectObj.project.projectInfo.ID;
            for (let tplNode of zTreeOprObj.checkedRptTplNodes) {
                rptIds.push(tplNode.refId);
                rpt_names.push(tplNode.name);
                let flag = null;
                if (tplNode.hasOwnProperty('flags')) {
                    flag = tplNode.flags;
                    params.prj_ids = rptTplObj.getAllPrjIds();
                    if (flag.auditType === 'audit_compare') {
                        let pids = [];
                        let comp_pid = await compareObject.getCompareID(); //返回单个对应的project ID
                        if (comp_pid !== null) {
                            pids.push(projectObj.project.projectInfo.ID);
                            pids.push(comp_pid);
                        }
                        compare_ids.push(pids);
                    } else {
                        compare_ids.push([]);
                    }
                } else {
                    compare_ids.push([]);
                }
                flagsArr.push(flag);
            }
            params.rpt_ids = rptIds.join(",");
            params.compare_ids = compare_ids;
            params.flags = flagsArr;
            params.compilation = projectObj.project.projectInfo.compilation;
            CommonAjax.postEx("report_api/getMultiReports", params, WAIT_TIME_EXPORT, true,
                function(result){
                    $.bootstrapLoading.end();
                    if ($('#ini_PDF_cover').is(':visible')) {
                        $("#ini_PDF_Btn_Cancel").trigger("click");
                        // $("#ini_PDF_cover").remove();
                    }
                    let pageSize = rptControlObj.getCurrentPageSize();
                    downloadPDFReport(result, pageSize, rpt_names);
                    // for (let idx = 0; idx < result.length; idx++) {
                    //     let pageData = result[idx];
                    //     JpcJsPDFHelper.outputAsPdf(pageData, pageSize, rpt_names[idx]);
                    // }
                },
                function(failRst){
                    $.bootstrapLoading.end();
                    if ($('#ini_PDF_cover').is(':visible')) {
                        $("#ini_PDF_Btn_Cancel").trigger("click");
                        // $("#ini_PDF_cover").remove();
                    }
                    sessionStorage.currentPageData = null;
                    console.log(failRst);
                },
                function(exceptionRst){
                    $.bootstrapLoading.end();
                    if ($('#ini_PDF_cover').is(':visible')) {
                        $("#ini_PDF_Btn_Cancel").trigger("click");
                        // $("#ini_PDF_cover").remove();
                    }
                    sessionStorage.currentPageData = null;
                    console.log(exceptionRst);
                }
            );
        } else {
            //不可能的branch
        }
    },
    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: async function() {
        let treeNode = zTreeOprObj.currentNode;
        if (treeNode.nodeType === TPL_TYPE_TEMPLATE && treeNode.refId > 0) {
            let params = {};
            params.pageSize = rptControlObj.getCurrentPageSize();
            params.rpt_tpl_id = treeNode.refId;
            params.flag = null;
            // if (me.currentNode.hasOwnProperty('flags')) {
            //     params.flag = me.currentNode.flags;
            //     params.prj_ids = rptTplObj.getAllPrjIds();
            // }
            if (treeNode.hasOwnProperty('flags')) {
                if (treeNode.flags.hasOwnProperty('auditType') && treeNode.flags.auditType === 'audit_compare') {
                    let pids = [];
                    let comp_pid = await compareObject.getCompareID(); //返回单个对应的project ID
                    if (comp_pid !== null) {
                        pids.push(projectObj.project.projectInfo.ID);
                        pids.push(comp_pid);
                        params.prj_ids = pids;
                    } else {
                        alert('未设置审核对比项目！');
                        exit;
                    }
                } else {
                    params.prj_ids = rptTplObj.getAllPrjIds();
                }
                params.flag = treeNode.flags;
            }        
            params.prj_id = projectObj.project.projectInfo.ID;
            params.custCfg = zTreeOprObj.reportPageCfg;
            zTreeOprObj.requestReport(params);
        }

    }
};

function downloadPDFReport(pageDataArr, pageSize, rpt_names) {
    rptControlObj.currentDownloadIdx = 0;
    const private_download = function() {
        if (rptControlObj.currentDownloadIdx < pageDataArr.length) {
            let pageData = pageDataArr[rptControlObj.currentDownloadIdx];
            let rptName = rpt_names[rptControlObj.currentDownloadIdx];
            rptControlObj.currentDownloadIdx++;
            JpcJsPDFHelper.outputAsPdf(pageData, pageSize, rptName);
            if (rptControlObj.currentDownloadIdx < pageDataArr.length) setTimeout(private_download, 1000);
        }
    }
    private_download();
}

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);
}

function _getCommonParams(treeNode) {
    let rstParmas = {};
    rstParmas.pageSize = rptControlObj.getCurrentPageSize();
    rstParmas.rpt_tpl_id = treeNode.refId;
    if (zTreeOprObj.checkedRptTplNodes && zTreeOprObj.checkedRptTplNodes.length > 0) {
        let refRptTplIds = [];
        for (let node of zTreeOprObj.checkedRptTplNodes) {
            refRptTplIds.push(node.refId);
            let flag = null;
            if (node.hasOwnProperty('flags')) {
                flag = node.flags;
                params.prj_ids = rptTplObj.getAllPrjIds();
            }
            flags.push(flag);
        }
        params.rpt_ids = refRptTplIds;
    }
    params.prj_id = projectObj.project.projectInfo.ID;

    rstParmas.prj_id = projectObj.project.projectInfo.ID;
    // rstParmas.custCfg = me.reportPageCfg;
    return rstParmas;
}