/**
 * Created by Tony on 2017/3/13.
 */

import mongoose from "mongoose";
import async from "async";

import JV from "../rpt_component/jpc_value_define";

let Template = mongoose.model('rpt_templates');
let rptTplDataFacade = require("../facade/rpt_tpl_data_facade");
let fsUtil = require("../../../public/fsUtil");
let pm_facade = require('../../../modules/pm/facade/pm_facade');

import rptTplFacade from "../facade/rpt_template_facade";
import demoTemplateFacade from "../facade/rpt_tpl_data_demo_facade";

import JpcEx from "../rpt_component/jpc_ex";
import rptUtil from "../util/rpt_util";
import rpt_xl_util from "../util/rpt_excel_util";
import rpt_pdf_util from "../util/rpt_pdf_util";
import rpt_svg_util from "../util/rpt_svg_util";
import fs from "fs";
import strUtil from "../../../public/stringUtil";
import rptDataExtractor from "../util/rpt_yanghu_data_util";

//统一回调函数
let callback = function(req, res, err, data){
    if(err){
        res.json({success: false, error: err});
    }
    else{
        //res.send({success: true, data: data});
        res.json({success:true, data: data});
    }
};

function getAllPagesCommonOrg(rpt_id, pageSize, option, cb) {
    let rptTpl = null;
    rptTplFacade.getRptTemplate(rpt_id).then(function(rst) {
        rptTpl = rst;
        if (rptTpl) {
            if (rptTpl.ID_KEY) {
                return demoTemplateFacade.getDemoData(rptTpl.ID_KEY);
            } else {
                //callback(req, res, 'No report template data were found!', null);
                cb('No report template data were found!', null);
            }
        } else {
            //callback(req, res, 'No report template was found!', null);
            cb('No report template was found!', null);
        }
    }).then(function(tplData){
            if (tplData) {
                let printCom = JpcEx.createNew();
                rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_PAGE_SIZE] = pageSize;
                let defProperties = rptUtil.getReportDefaultCache();
                let dftOption = option||JV.PAGING_OPTION_NORMAL;
                printCom.initialize(rptTpl);
                printCom.analyzeData(rptTpl, tplData, defProperties, dftOption, JV.OUTPUT_TYPE_NORMAL);
                let maxPages = printCom.totalPages;
                let pageRst = printCom.outputAsSimpleJSONPageArray(rptTpl, tplData, 1, maxPages, defProperties);
                if (pageRst) {
                    cb(null, pageRst);
                } else {
                    //callback(req, res, "Have errors while on going...", null);
                    cb('Have errors while on going...', null);
                }
            } else {
                //callback(req, res, 'No report data were found!', null);
                cb('No report data were found!', null);
            }
        }
    );
}
function setupCustomizeCfg(customizeCfg, rptTpl, defProperties) {
    let tmpObj = {};
    //1. 字体
    let newFonts = [];
    for (let font of defProperties.fonts) {
        let copyFont = {};
        copyFont.ID = font.ID;
        for (let fontProp of JV.FONT_PROPS) {
            copyFont[fontProp] = font[fontProp];
        }
        newFonts.push(copyFont);
        tmpObj[font.ID] = copyFont;
    }
    let private_setup_font = function (propStr, newFont) {
        if (tmpObj[propStr]) {
            tmpObj[propStr].Name = newFont.Name;
            tmpObj[propStr].FontHeight = String(newFont.FontHeight);
            tmpObj[propStr].FontBold = newFont.FontBold;
            tmpObj[propStr].FontItalic = newFont.FontItalic;
            tmpObj[propStr].FontUnderline = newFont.FontUnderline;
        }
    };
    for (let custFont of customizeCfg.fonts) {
        switch (custFont.CfgDispName) {
            case "表标题":
                private_setup_font("ReportTitle_Main", custFont);
                break;
            case "列标题":
                private_setup_font("HeaderColumn", custFont);
                private_setup_font("FooterColumn", custFont);
                break;
            case "正文内容":
                private_setup_font("Content", custFont);
                break;
            case "合计":
                private_setup_font("GrandTotal", custFont);
                private_setup_font("SectionTotal", custFont);
                break;
            case "表眉/表脚":
                private_setup_font("Header", custFont);
                private_setup_font("Footer", custFont);
                break;
        }
    }
    // 1.1 窄体
    if (tmpObj["Content_Narrow"]) {
        if (customizeCfg.isNarrow) {
            tmpObj["Content_Narrow"].Name = "Arial Narrow";
        } else {
            if (tmpObj["Content"]) {
                tmpObj["Content_Narrow"].Name = tmpObj["Content"].Name;
            } else {
                tmpObj["Content_Narrow"].Name = "宋体";
            }
        }
    }
    defProperties.fonts = newFonts;
    //2. 页边距
    rptTpl[JV.NODE_MAIN_INFO][JV.NODE_MARGINS][JV.PROP_LEFT] = customizeCfg.margins[JV.PROP_LEFT] / 10;
    rptTpl[JV.NODE_MAIN_INFO][JV.NODE_MARGINS][JV.PROP_RIGHT] = customizeCfg.margins[JV.PROP_RIGHT] / 10;
    rptTpl[JV.NODE_MAIN_INFO][JV.NODE_MARGINS][JV.PROP_TOP] = customizeCfg.margins[JV.PROP_TOP] / 10;
    rptTpl[JV.NODE_MAIN_INFO][JV.NODE_MARGINS][JV.PROP_BOTTOM] = customizeCfg.margins[JV.PROP_BOTTOM] / 10;
    //3. 边框竖线
    if (!(customizeCfg.showVerticalLine)) {
        let private_copy_border = function (src) {
            let rst = {};
            rst.Position = src.Position;
            rst.LineWeight = src.LineWeight;
            rst.DashStyle = src.DashStyle;
            rst.Color = src.Color;
            return rst;
        };
        let newStyles = [];
        for (let i =0 ; i < defProperties.styles.length; i++) {
            let style = defProperties.styles[i];
            newStyles.push(style);
            if (style.ID === "BORDER_ALL_AROUND") {
                let newStyle = {};
                newStyle.ID  = style.ID;
                newStyle.CfgDispName = style.CfgDispName;
                newStyle.border_style = [];
                for (let border of style.border_style) {
                    let newBorder = private_copy_border(border);
                    newStyle.border_style.push(newBorder);
                    if (border.Position === "Left" || border.Position === "Right") {
                        newBorder.LineWeight = 0;
                    }
                }
                newStyles[newStyles.length - 1] = newStyle;
            }
        }
        defProperties.styles = newStyles;
    }
    //4. 补0
    let private_Setup_Format = function(tabFields) {
        if (tabFields) {
            for (let tabField of tabFields) {
                if (tabField[JV.PROP_FORMAT]) {
                    tabField[JV.PROP_FORMAT] = tabField[JV.PROP_FORMAT].replace(new RegExp("#","gm"),"0");
                }
            }
        }
    };
    if (customizeCfg.fillZero) {
        if (rptTpl[JV.NODE_FLOW_INFO]) {
            if (rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_CONTENT]) private_Setup_Format(rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_CONTENT][JV.PROP_FLOW_FIELDS]);
            if (rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_PAGE_SUM]) private_Setup_Format(rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_PAGE_SUM][JV.PROP_SUM_FIELDS]);
            if (rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_SEG_SUM]) private_Setup_Format(rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_SEG_SUM][JV.PROP_SUM_FIELDS]);
            if (rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_GROUP] && rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_GROUP][JV.PROP_GROUP_LINES])
                private_Setup_Format(rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_GROUP][JV.PROP_GROUP_LINES][JV.PROP_SUM_FIELDS]);
            if (rptTpl[JV.NODE_FLOW_INFO][JV.NODE_DISCRETE_INFO]) {
                for (let discrete of rptTpl[JV.NODE_FLOW_INFO][JV.NODE_DISCRETE_INFO]) {
                    private_Setup_Format(discrete[JV.PROP_DISCRETE_FIELDS]);
                }
            }
            if (rptTpl[JV.NODE_FLOW_INFO_EX]) {
                if (rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_FLOW_CONTENT]) private_Setup_Format(rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_FLOW_CONTENT][JV.PROP_FLOW_FIELDS]);
                if (rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_FLOW_PAGE_SUM]) private_Setup_Format(rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_FLOW_PAGE_SUM][JV.PROP_SUM_FIELDS]);
                if (rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_FLOW_SEG_SUM]) private_Setup_Format(rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_FLOW_SEG_SUM][JV.PROP_SUM_FIELDS]);
                if (rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_FLOW_GROUP]) private_Setup_Format(rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_FLOW_GROUP][JV.PROP_SUM_FIELDS]);
                if (rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_FLOW_GROUP] && rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_FLOW_GROUP][JV.PROP_GROUP_LINES])
                    private_Setup_Format(rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_FLOW_GROUP][JV.PROP_GROUP_LINES][JV.PROP_SUM_FIELDS]);
                if (rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_DISCRETE_INFO]) {
                    for (let discrete of rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_DISCRETE_INFO]) {
                        private_Setup_Format(discrete[JV.PROP_DISCRETE_FIELDS]);
                    }
                }
            }
        } else if (rptTpl[JV.NODE_BILL_INFO]) {
            if (rptTpl[JV.NODE_BILL_INFO][JV.NODE_BILL_CONTENT]) private_Setup_Format(rptTpl[JV.NODE_BILL_INFO][JV.NODE_BILL_CONTENT][JV.PROP_BILL_FIELDS]);
            if (rptTpl[JV.NODE_BILL_INFO][JV.NODE_DISCRETE_INFO]) {
                for (let discrete of rptTpl[JV.NODE_BILL_INFO][JV.NODE_DISCRETE_INFO]) {
                    private_Setup_Format(discrete[JV.PROP_DISCRETE_FIELDS]);
                }
            }
        } else if (rptTpl[JV.NODE_CROSS_INFO]) {
            if (rptTpl[JV.NODE_CROSS_INFO][JV.NODE_CROSS_CONTENT]) private_Setup_Format(rptTpl[JV.NODE_CROSS_INFO][JV.NODE_CROSS_CONTENT][JV.TAB_CROSS_FIELDS]);
            if (rptTpl[JV.NODE_CROSS_INFO][JV.NODE_CROSS_ROW]) private_Setup_Format(rptTpl[JV.NODE_CROSS_INFO][JV.NODE_CROSS_ROW][JV.TAB_CROSS_FIELDS]);
            if (rptTpl[JV.NODE_CROSS_INFO][JV.NODE_CROSS_COL]) private_Setup_Format(rptTpl[JV.NODE_CROSS_INFO][JV.NODE_CROSS_COL][JV.TAB_CROSS_FIELDS]);
            if (rptTpl[JV.NODE_CROSS_INFO][JV.NODE_CROSS_COL_SUM]) private_Setup_Format(rptTpl[JV.NODE_CROSS_INFO][JV.NODE_CROSS_COL_SUM][JV.TAB_CROSS_FIELDS]);
            if (rptTpl[JV.NODE_CROSS_INFO][JV.NODE_CROSS_ROW_EXT]) private_Setup_Format(rptTpl[JV.NODE_CROSS_INFO][JV.NODE_CROSS_ROW_EXT][JV.TAB_CROSS_FIELDS]);
            if (rptTpl[JV.NODE_CROSS_INFO][JV.NODE_CROSS_ROW_SUM_EXT]) private_Setup_Format(rptTpl[JV.NODE_CROSS_INFO][JV.NODE_CROSS_ROW_SUM_EXT][JV.TAB_CROSS_FIELDS]);
            if (rptTpl[JV.NODE_CROSS_INFO][JV.NODE_DISCRETE_INFO]) {
                for (let discrete of rptTpl[JV.NODE_CROSS_INFO][JV.NODE_DISCRETE_INFO]) {
                    private_Setup_Format(discrete[JV.PROP_DISCRETE_FIELDS]);
                }
            }
        }
    }
}
function getAllPagesCommon(user_id, prj_id, rpt_id, pageSize, orientation, customizeCfg, option, outputType, cb) {
    let rptTpl = null;
    rptTplFacade.getRptTemplate(rpt_id).then(function(rst) {
        rptTpl = rst;
        if (rptTpl) {
            let rptDataUtil = new rptDataExtractor();
            rptDataUtil.initialize((rptTpl._doc)?rptTpl._doc:rptTpl);
            let summaryRst = [];
            let filter = rptDataUtil.getDataRequestFilter(summaryRst);
            let promiseArr = [null, null];
            if (summaryRst.length > 0) {
                if (summaryRst.indexOf(`Construct`) >= 0 || summaryRst.indexOf(`ConstructDetail`) >= 0) {
                    promiseArr[0] = pm_facade.getSummaryInfoByTender(prj_id, pm_facade.projectType.project);
                }
                if (summaryRst.indexOf(`Segment`) >= 0 || summaryRst.indexOf(`SegmentDetail`) >= 0) {
                    promiseArr[1] = pm_facade.getSummaryInfoByTender(prj_id, pm_facade.projectType.engineering);
                }
            }
            rptTplDataFacade.prepareProjectData(user_id, prj_id, filter, function (err, msg, rawDataObj) {
                if (!err) {
                    let buildPageData = function() {
                        try {
                            // fsUtil.writeObjToFile(rawDataObj, "D:/GitHome/ConstructionCost/tmp/rawDataObj.jsp");
                            let tplData = rptDataUtil.assembleData(rawDataObj);
                            let printCom = JpcEx.createNew();
                            if (pageSize) rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_PAGE_SIZE] = pageSize;
                            if (orientation && (orientation !== 'null')) rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_ORIENTATION] = orientation;
                            let defProperties = rptUtil.getReportDefaultCache();
                            if (customizeCfg) setupCustomizeCfg(customizeCfg, rptTpl, defProperties);
                            let dftOption = option||JV.PAGING_OPTION_NORMAL;
                            printCom.initialize(rptTpl);
                            printCom.analyzeData(rptTpl, tplData, defProperties, dftOption, outputType);
                            let maxPages = printCom.totalPages;
                            let pageRst = null;
                            if (maxPages > 0) {
                                pageRst = printCom.outputAsSimpleJSONPageArray(rptTpl, tplData, 1, maxPages, defProperties, customizeCfg);
                            } else {
                                pageRst = printCom.outputAsPreviewPage(rptTpl, defProperties);
                            }
                            if (pageRst) {
                                // fsUtil.writeObjToFile(pageRst, "D:/GitHome/ConstructionCost/tmp/testBuiltPageResult.jsp");
                                cb(null, pageRst);
                            } else {
                                cb('Have errors while on going...', null);
                            }
                        } catch (ex) {
                            console.log("报表数据异常： userId " + user_id + ", project id: " + prj_id);
                            console.log(ex);
                            cb('Exception occurs while on going...', null);
                        }
                    };
                    //*/
                    //取汇总数据流程
                    if (promiseArr[0] !== null) {
                        promiseArr[0].then(function (rst) {
                            rawDataObj.Construct = rst.parent;
                            rawDataObj.ConstructDetail = rst.subList;
                            if (promiseArr[1] !== null) {
                                promiseArr[1].then(function (rst) {
                                    rawDataObj.Segment = rst.parent;
                                    rawDataObj.SegmentDetail = rst.subList;
                                    buildPageData(rawDataObj, rptDataUtil, rptTpl);
                                });
                            } else {
                                buildPageData(rawDataObj, rptDataUtil, rptTpl);
                            }
                        });
                    } else  if (promiseArr[1] !== null) {
                        promiseArr[1].then(function (rst) {
                            rawDataObj.Segment = rst.parent;
                            rawDataObj.SegmentDetail = rst.subList;
                            buildPageData(rawDataObj, rptDataUtil, rptTpl);
                        });
                    } else {
                        buildPageData(rawDataObj, rptDataUtil, rptTpl);
                    }
                    /*/
                    let tplData = rptDataUtil.assembleData(rawDataObj);
                    let printCom = JpcEx.createNew();
                    if (pageSize) rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_PAGE_SIZE] = pageSize;
                    //console.log("orientation: " + (orientation === 'null'));
                    if (orientation && (orientation !== 'null')) rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_ORIENTATION] = orientation;
                    let defProperties = rptUtil.getReportDefaultCache();
                    if (customizeCfg) setupCustomizeCfg(customizeCfg, rptTpl, defProperties);
                    let dftOption = option||JV.PAGING_OPTION_NORMAL;
                    printCom.initialize(rptTpl);
                    printCom.analyzeData(rptTpl, tplData, defProperties, dftOption, outputType);
                    let maxPages = printCom.totalPages;
                    let pageRst = printCom.outputAsSimpleJSONPageArray(rptTpl, tplData, 1, maxPages, defProperties, customizeCfg);
                    if (pageRst) {
                        // fsUtil.writeObjToFile(pageRst, "D:/GitHome/ConstructionCost/tmp/testBuiltPageResult.jsp");
                        cb(null, pageRst);
                    } else {
                        cb('Have errors while on going...', null);
                    }
                    //*/
                } else {
                    cb('No report data were found!', null);
                }
            });
        } else {
            cb('No report template was found!', null);
        }
    });
}

function getMultiRptsCommon(user_id, prj_id, rpt_ids, pageSize, orientation, customizeCfg, option, outputType, cb) {
    for (let idx = 0; idx < rpt_ids.length; idx++) {
        rpt_ids[idx] = parseInt(rpt_ids[idx]); //转换一下，以防万一
    }
    rptTplFacade.getRptTemplates(rpt_ids).then(function(rptTpls) {
        let rptDataUtil = new rptDataExtractor();
        let filters = [];
        if (rptTpls.length > 1) {
            rptTpls.sort(function (item1, item2){
                let i1 = (item1._doc)?item1._doc:item1, i2 = (item2._doc)?item2._doc:item2;
                let ID1 = rpt_ids.indexOf(i1[JV.PROP_ID]), ID2 = rpt_ids.indexOf(i2[JV.PROP_ID]);
                return ID1 - ID2;
            });
        }
        for (let rptTpl of rptTpls) {
            rptDataUtil.initialize((rptTpl._doc)?rptTpl._doc:rptTpl);
            let filter = rptDataUtil.getDataRequestFilter();
            for (let dtlFilter of filter) {
                if (filters.indexOf(dtlFilter) < 0) {
                    filters.push(dtlFilter);
                }
            }
        }
        //正常应该根据报表模板定义的数据类型来请求数据
        rptTplDataFacade.prepareProjectData(user_id, prj_id, filters, function (err, msg, rawDataObj) {
            if (!err) {
                try {
                    let rptPageRstArray = [];
                    //1. 这里只用一份数据，根据实际应用情况，只需要保留copy三样数据： bills, ration, ration_glj, projectGLJ
                    let savedBillsData = [], savedRationData = [], savedGljData = [], savedPrjGljData = [], savedFeeRateData = [];
                    for (let dtlData of rawDataObj.prjData) {
                        if (dtlData.moduleName === 'bills') {
                            Object.assign(savedBillsData, dtlData.data);
                        } else if (dtlData.moduleName === 'ration') {
                            Object.assign(savedRationData, dtlData.data);
                        } else if (dtlData.moduleName === 'ration_glj') {
                            Object.assign(savedGljData, dtlData.data);
                        } else if (dtlData.moduleName === 'feeRate') {
                            Object.assign(savedFeeRateData, dtlData.data._doc.rates);
                        } else if (dtlData.moduleName === 'projectGLJ') {
                            Object.assign(savedPrjGljData, dtlData.data.gljList);
                        }
                    }
                    //2. 一个一个模板创建数据
                    for (let tplIdx = 0; tplIdx < rptTpls.length; tplIdx++) {
                        let rptTpl = (rptTpls[tplIdx]._doc)?rptTpls[tplIdx]._doc:rptTpls[tplIdx];
                        rptDataUtil.initialize(rptTpl);
                        let tplData = rptDataUtil.assembleData(rawDataObj);
                        let printCom = JpcEx.createNew();
                        rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_PAGE_SIZE] = pageSize;

                        if (pageSize) rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_PAGE_SIZE] = pageSize;
                        if (orientation && (orientation !== 'null')) rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_ORIENTATION] = orientation;
                        let defProperties = rptUtil.getReportDefaultCache();
                        if (customizeCfg) setupCustomizeCfg(customizeCfg, rptTpl, defProperties);
                        let dftOption = option||JV.PAGING_OPTION_NORMAL;

                        printCom.initialize(rptTpl);
                        printCom.analyzeData(rptTpl, tplData, defProperties, dftOption, outputType);
                        let maxPages = printCom.totalPages;
                        let pageRst = null;
                        if (maxPages > 0) {
                            pageRst = printCom.outputAsSimpleJSONPageArray(rptTpl, tplData, 1, maxPages, defProperties, customizeCfg);
                        } else {
                            pageRst = printCom.outputAsPreviewPage(rptTpl, defProperties);
                        }
                        rptPageRstArray.push(pageRst);
                        //注意：这里需要把清单、定额、工料机数据assign回去!!!
                        for (let dtlData of rawDataObj.prjData) {
                            if (dtlData.moduleName === 'bills' && savedBillsData.length > 0) {
                                Object.assign(dtlData.data, savedBillsData);
                            } else if (dtlData.moduleName === 'ration' && savedRationData.length > 0) {
                                Object.assign(dtlData.data, savedRationData);
                            } else if (dtlData.moduleName === 'ration_glj' && savedGljData.length > 0) {
                                Object.assign(dtlData.data, savedGljData);
                            } else if (dtlData.moduleName === 'feeRate' && savedFeeRateData.length > 0) {
                                Object.assign(dtlData.data._doc.rates, savedFeeRateData);
                            } else if (dtlData.moduleName === 'projectGLJ' && savedPrjGljData.length > 0) {
                                Object.assign(dtlData.data.gljList, savedPrjGljData);
                            }
                        }
                    }
                    cb(null, rptPageRstArray);
                } catch (ex) {
                    console.log("报表数据异常（getMultiRptsCommon）： userId " + user_id + ", project id: " + prj_id);
                    console.log(ex);
                    cb('Exception occurs while on going...', null);
                } finally {
                }
            } else {
                cb('No report data were found!', null);
            }
        })
    });
}

function getBillsSummaryReportPages(req, user_id, prjIds, rpt_id, pageSize, orientation, customizeCfg, option, outputType, cb) {
    let rptTpl = null;
    rptTplDataFacade.getBudgetSummayDatas(prjIds, req.session.sessionUser.id, req.session.sessionCompilation._id, req.session.sessionCompilation.overWriteUrl).then(function(summaryRawDataRst) {
        rptTplFacade.getRptTemplate(rpt_id).then(function(rptTpl) {
            let rptDataUtil = new rptDataExtractor();
            rptDataUtil.initialize((rptTpl._doc)?rptTpl._doc:rptTpl);
            try {
                let tplData = rptDataUtil.assembleData(summaryRawDataRst);
                // fsUtil.writeObjToFile(summaryRawDataRst, "D:/GitHome/temp/billsSummaryRawDataRstRawData.jsp");
                let printCom = JpcEx.createNew();
                if (pageSize) rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_PAGE_SIZE] = pageSize;
                //console.log("orientation: " + (orientation === 'null'));
                if (orientation && (orientation !== 'null')) rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_ORIENTATION] = orientation;
                let defProperties = rptUtil.getReportDefaultCache();
                if (customizeCfg) setupCustomizeCfg(customizeCfg, rptTpl, defProperties);
                let dftOption = option||JV.PAGING_OPTION_NORMAL;
                printCom.initialize(rptTpl);
                printCom.analyzeData(rptTpl, tplData, defProperties, dftOption, outputType);
                let maxPages = printCom.totalPages;
                let pageRst = null;
                if (maxPages > 0) {
                    pageRst = printCom.outputAsSimpleJSONPageArray(rptTpl, tplData, 1, maxPages, defProperties, customizeCfg);
                } else {
                    pageRst = printCom.outputAsPreviewPage(rptTpl, defProperties);
                }
                if (pageRst) {
                    cb(null, pageRst);
                } else {
                    cb('Have errors while on going...', null);
                }
            } catch (ex) {
                console.log("报表数据异常： userId " + user_id + ", project id: " + prj_id);
                console.log(ex);
                cb('Exception occurs while on going...', null);
            }
        });
    });

}

function getSummaryComboPages(req, user_id, prjIds, billsSummaryRpt_ids, gljSummaryRpt_ids, pageSize, orientation, customizeCfg, option, outputType, cb) {
    let pageRstArr = [];
    let pri_setup_rpt_tpl_data = function (rptTpl, summaryRawDataRst) {
        let rptDataUtil = new rptDataExtractor();
        rptDataUtil.initialize((rptTpl._doc)?rptTpl._doc:rptTpl);
        try {
            let tplData = rptDataUtil.assembleData(summaryRawDataRst);
            let printCom = JpcEx.createNew();
            if (pageSize) rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_PAGE_SIZE] = pageSize;
            if (orientation && (orientation !== 'null')) rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_ORIENTATION] = orientation;
            let defProperties = rptUtil.getReportDefaultCache();
            if (customizeCfg) setupCustomizeCfg(customizeCfg, rptTpl, defProperties);
            let dftOption = option||JV.PAGING_OPTION_NORMAL;
            printCom.initialize(rptTpl);
            printCom.analyzeData(rptTpl, tplData, defProperties, dftOption, outputType);
            let maxPages = printCom.totalPages;
            let pageRst = null;
            if (maxPages > 0) {
                pageRst = printCom.outputAsSimpleJSONPageArray(rptTpl, tplData, 1, maxPages, defProperties, customizeCfg);
            } else {
                pageRst = printCom.outputAsPreviewPage(rptTpl, defProperties);
            }
            pageRstArr.push(pageRst);
        } catch (ex) {
            console.log("Summary报表数据异常： userId " + user_id + ", project ids: " + prjIds);
            console.log(ex);
        }
    };

    let billRpts = [], gljRpts = [];
    rptTplFacade.getRptTemplates(billsSummaryRpt_ids.concat(gljSummaryRpt_ids)).then(function(rptTpls) {
        if (rptTpls && rptTpls.length > 0) {
            for (let rptTpl of rptTpls) {
                if (billsSummaryRpt_ids.indexOf(rptTpl.ID) >= 0) {
                    billRpts.push(rptTpl);
                } else if (gljSummaryRpt_ids.indexOf(rptTpl.ID) >= 0) {
                    gljRpts.push(rptTpl);
                }
            }
        }
        if (billRpts.length > 0) {
            rptTplDataFacade.getBudgetSummayDatas(prjIds, req.session.sessionUser.id, req.session.sessionCompilation._id, req.session.sessionCompilation.overWriteUrl).then(function(summaryRawDataRst) {
                // let savedBillsData = [];
                try {
                    // Object.assign(savedBillsData, summaryRawDataRst.SummaryAuditDetail);
                    for (let idx = 0; idx < billRpts.length; idx++) {
                        pri_setup_rpt_tpl_data(billRpts[idx], summaryRawDataRst);
                        // if (idx < billRpts.length - 1) {
                        //     Object.assign(summaryRawDataRst.SummaryAuditDetail, savedBillsData);
                        // }
                    }
                    if (gljRpts && gljRpts.length > 0) {
                        rptTplDataFacade.getGLJSummayDatas(prjIds).then(function(summaryRawDataRst) {
                            // let savedBillsData = [];
                            // Object.assign(savedBillsData, summaryRawDataRst.SummaryAuditDetail);
                            for (let idx = 0; idx < gljRpts.length; idx++) {
                                pri_setup_rpt_tpl_data(gljRpts[idx], summaryRawDataRst);
                                // if (idx < gljRpts.length - 1) {
                                //     Object.assign(summaryRawDataRst.SummaryAuditDetail, savedBillsData);
                                // }
                            }
                            cb(null, pageRstArr);
                        });
                    } else {
                        cb(null, pageRstArr);
                    }
                } catch (ex) {
                    console.log(ex);
                    cb(null, pageRstArr);
                }
            });
        } else if (gljRpts.length > 0) {
            rptTplDataFacade.getGLJSummayDatas(prjIds).then(function(summaryRawDataRst) {
                // let savedBillsData = [];
                // Object.assign(savedBillsData, summaryRawDataRst.SummaryAuditDetail);
                // 养护工料机汇总不用考虑back up问题。模板需要自觉一点，不要修改数据！！！
                for (let idx = 0; idx < gljRpts.length; idx++) {
                    pri_setup_rpt_tpl_data(gljRpts[idx], summaryRawDataRst);
                    if (idx < gljRpts.length - 1) {
                        // Object.assign(summaryRawDataRst.SummaryAuditDetail, savedBillsData);
                    }
                }
                cb(null, pageRstArr);
            });
        }
    });
}

function getGljSummaryReportPages(user_id, prjIds, rpt_id, pageSize, orientation, customizeCfg, option, outputType, cb) {
    let rptTpl = null;
    rptTplDataFacade.getGLJSummayDatas(prjIds).then(function(summaryRawDataRst) {
        rptTplFacade.getRptTemplate(rpt_id).then(function(rptTpl) {
            let rptDataUtil = new rptDataExtractor();
            rptDataUtil.initialize((rptTpl._doc)?rptTpl._doc:rptTpl);
            try {
                // fsUtil.writeObjToFile(summaryRawDataRst, "D:/GitHome/temp/gljSummaryRawDataRstRawData.jsp");
                let tplData = rptDataUtil.assembleData(summaryRawDataRst);
                let printCom = JpcEx.createNew();
                if (pageSize) rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_PAGE_SIZE] = pageSize;
                //console.log("orientation: " + (orientation === 'null'));
                if (orientation && (orientation !== 'null')) rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_ORIENTATION] = orientation;
                let defProperties = rptUtil.getReportDefaultCache();
                if (customizeCfg) setupCustomizeCfg(customizeCfg, rptTpl, defProperties);
                let dftOption = option||JV.PAGING_OPTION_NORMAL;
                printCom.initialize(rptTpl);
                printCom.analyzeData(rptTpl, tplData, defProperties, dftOption, outputType);
                let maxPages = printCom.totalPages;
                let pageRst = null;
                if (maxPages > 0) {
                    pageRst = printCom.outputAsSimpleJSONPageArray(rptTpl, tplData, 1, maxPages, defProperties, customizeCfg);
                } else {
                    pageRst = printCom.outputAsPreviewPage(rptTpl, defProperties);
                }
                if (pageRst) {
                    cb(null, pageRst);
                } else {
                    cb('Have errors while on going...', null);
                }
            } catch (ex) {
                // console.log("报表数据异常： userId " + user_id + ", project id: " + prj_id);
                console.log(ex);
                cb('Exception occurs while on going...', null);
            }
        });

    });
}

module.exports = {
    getReportAllPages: function (req, res) {
        let params = JSON.parse(req.body.params),
            rpt_id = params.rpt_tpl_id,
            prj_id = params.prj_id,
            pageSize = params.pageSize,
            orientation = params.orientation,
            customizeCfg = params.custCfg
        ;
        // req.session.sessionUser.ssoId
        let user_id = req.session.sessionUser.id;
        getAllPagesCommon(user_id, prj_id, rpt_id, pageSize, orientation, customizeCfg, null, JV.OUTPUT_TYPE_NORMAL, function (err, pageRst) {
            callback(req, res, err, pageRst);
        });
    },
    getMultiReports: function (req, res) {
        //打印预览用
        let params = JSON.parse(req.body.params),
            prj_id = params.prj_id,
            rpt_ids = params.rpt_ids.split(','),
            pageSize = params.pageSize,
            orientation = params.orientation,
            customizeCfg = params.custCfg,
            option = params.option;
        let user_id = req.session.sessionUser.id;
        let parallelFunctions = [];
        let dftOption = option||JV.PAGING_OPTION_NORMAL;
        for (let id of rpt_ids) {
            parallelFunctions.push((function (rpt_id) {
                return function (cb) {
                    getAllPagesCommon(user_id, prj_id, rpt_id, pageSize, orientation, customizeCfg, dftOption, JV.OUTPUT_TYPE_NORMAL, function (err, pageRst) {
                        if(err){
                            cb(err);
                        }
                        else{
                            cb(null, pageRst);
                        }
                    })
                }
            })(parseInt(id)));
        }
        async.parallel(parallelFunctions, function (err, pageRstArray) {
            if (err) {
                callback(req, res, '数据有误', null);
            } else {
                callback(req, res, err, pageRstArray);
            }
        })
    },
    getMultiReportsEx: function (req, res) {
        //原则说明：把所有报表模板集中获取，统一filter，只读一次数据！
        let params = JSON.parse(req.body.params),
            prj_id = params.prj_id,
            rpt_ids = params.rpt_ids,
            //--以下是汇总类数据----------
            rpt_bill_tpl_ids = params.rpt_bill_tpl_ids,
            rpt_glj_tpl_ids = params.rpt_glj_tpl_ids,
            prjIds = params.prjIds,
            //------------
            pageSize = params.pageSize,
            orientation = params.orientation,
            customizeCfg = params.custCfg,
            option = params.option;
        let user_id = req.session.sessionUser.id;
        let dftOption = option||JV.PAGING_OPTION_NORMAL;
        if (rpt_ids && rpt_ids.length > 0) {
            getMultiRptsCommon(user_id, prj_id, rpt_ids, pageSize, orientation, customizeCfg, dftOption, JV.OUTPUT_TYPE_PDF, function (err, rptPageRstArray) {
                if (err) {
                    callback(req, res, '数据有误', null);
                } else {
                    if ((rpt_bill_tpl_ids && rpt_bill_tpl_ids.length > 0) || (rpt_glj_tpl_ids && rpt_glj_tpl_ids.length > 0)) {
                        getSummaryComboPages(req, user_id, prjIds, rpt_bill_tpl_ids, rpt_glj_tpl_ids, pageSize, orientation, customizeCfg, option, JV.OUTPUT_TYPE_NORMAL, function (err, rptSumPageRstArray) {
                            callback(req, res, err, rptSumPageRstArray.concat(rptPageRstArray));
                        });
                    } else {
                        callback(req, res, err, rptPageRstArray);
                    }
                }
            });
        } else if ((rpt_bill_tpl_ids && rpt_bill_tpl_ids.length > 0) || (rpt_glj_tpl_ids && rpt_glj_tpl_ids.length > 0)) {
            getSummaryComboPages(req, user_id, prjIds, rpt_bill_tpl_ids, rpt_glj_tpl_ids, pageSize, orientation, customizeCfg, option, JV.OUTPUT_TYPE_NORMAL, function (err, rptSumPageRstArray) {
                callback(req, res, err, rptSumPageRstArray);
            });
        }
    },

    getBillSummaryReportPages: function (req, res) {
        let params = JSON.parse(req.body.params),
            rpt_id = params.rpt_tpl_id,
            prjIds = params.prjIds,
            pageSize = params.pageSize,
            orientation = params.orientation,
            customizeCfg = params.custCfg
        ;
        let user_id = req.session.sessionUser.id;
        getBillsSummaryReportPages(req, user_id, prjIds, rpt_id, pageSize, orientation, customizeCfg, null, JV.OUTPUT_TYPE_NORMAL, function (err, pageRst) {
            callback(req, res, err, pageRst);
        });
    },

    getGljSummaryReportPages: function (req, res) {
        let params = JSON.parse(req.body.params),
            rpt_id = params.rpt_tpl_id,
            prjIds = params.prjIds,
            pageSize = params.pageSize,
            orientation = params.orientation,
            customizeCfg = params.custCfg
        ;
        let user_id = req.session.sessionUser.id;
        getGljSummaryReportPages(user_id, prjIds, rpt_id, pageSize, orientation, customizeCfg, null, JV.OUTPUT_TYPE_NORMAL, function (err, pageRst) {
            callback(req, res, err, pageRst);
        });
    },

    createSummaryReportFiles: function (req, res) {
        let params = JSON.parse(req.body.params),
            rpt_bill_tpl_ids = params.rpt_bill_tpl_ids,
            rpt_glj_tpl_ids = params.rpt_glj_tpl_ids,
            prjIds = params.prjIds,
            pageSize = params.pageSize,
            orientation = params.orientation,
            customizeCfg = params.custCfg
        ;
        let user_id = req.session.sessionUser.id;
    },

    getReportAllPagesSvg: function (req, res) {
        let params = JSON.parse(req.body.params),
            rpt_id = params.rpt_tpl_id,
            prj_id = params.prj_id,
            pageSize = params.pageSize,
            orientation = params.orientation,
            customizeCfg = params.custCfg
        ;
        let user_id = req.session.sessionUser.id;
        getAllPagesCommon(user_id, prj_id, rpt_id, pageSize, orientation, customizeCfg, null, JV.OUTPUT_TYPE_SVG, function (err, pageRst) {
            let svgRstStrArr = rpt_svg_util.exportSvgStr(pageRst, 0, 0);
            callback(req, res, err, svgRstStrArr);
        });
    },

    createExcelFilesInOneBook: function (req, res) {
        let params = JSON.parse(req.body.params),
            prj_id = params.prj_id,
            rpt_ids = params.rpt_ids,
            rptName = params.rptName,
            pageSize = params.pageSize,
            orientation = params.orientation,
            customizeCfg = params.custCfg,
            option = params.option;
        let user_id = req.session.sessionUser.id;
        let parallelFunctions = [];
        let dftOption = option||JV.PAGING_OPTION_NORMAL;
        for (let idx = 0; idx < rpt_ids.length; idx++) {
            let r_id = rpt_ids[idx];
            parallelFunctions.push((function (rpt_id) {
                return function (cb) {
                    getAllPagesCommon(user_id, prj_id, rpt_id, pageSize, orientation, customizeCfg, dftOption, JV.OUTPUT_TYPE_EXCEL, function (err, pageRst) {
                        if(err){
                            cb(err);
                        }
                        else{
                            cb(err, pageRst);
                        }
                    })
                }
            })(parseInt(r_id)));
        }
        async.parallel(parallelFunctions, function (err, pageRstArray) {
            if (err) {
                callback(req, res, '数据有误', null);
            } else {
                rpt_xl_util.exportExcelInOneBook(pageRstArray, pageSize, rptName, function(uuidName){
                    let fileRst = {uuid: uuidName, reportName: rptName};
                    callback(req, res, err, fileRst);
                });
            }
        })
    },

    createExcelFilesInOneBookEx: function (req, res) {
        //采用了优化策略
        let params = JSON.parse(req.body.params),
            prj_id = params.prj_id,
            rpt_ids = params.rpt_ids,
            //--以下是汇总类数据----------
            rpt_bill_tpl_ids = params.rpt_bill_tpl_ids,
            rpt_glj_tpl_ids = params.rpt_glj_tpl_ids,
            prjIds = params.prjIds,
            //------------
            rptName = params.rptName,
            pageSize = params.pageSize,
            orientation = params.orientation,
            customizeCfg = params.custCfg,
            option = params.option;
        let user_id = req.session.sessionUser.id;
        let dftOption = option||JV.PAGING_OPTION_NORMAL;

        if (rpt_ids && rpt_ids.length > 0) {
            getMultiRptsCommon(user_id, prj_id, rpt_ids, pageSize, orientation, customizeCfg, dftOption, JV.OUTPUT_TYPE_NORMAL, function (err, rptPageRstArray) {
                if(err){
                    console.log('导出Excel错误（生成数据过程错误）, userId: ' + user_id + ', prjId' + prj_id);
                    callback(req, res, '数据有误', null);
                } else {
                    if ((rpt_bill_tpl_ids && rpt_bill_tpl_ids.length > 0) || (rpt_glj_tpl_ids && rpt_glj_tpl_ids.length > 0)) {
                        getSummaryComboPages(req, user_id, prjIds, rpt_bill_tpl_ids, rpt_glj_tpl_ids, pageSize, orientation, customizeCfg, option, JV.OUTPUT_TYPE_NORMAL, function (err, rptSumPageRstArray) {
                            rpt_xl_util.exportExcelInOneBook(rptPageRstArray.concat(rptSumPageRstArray), pageSize, rptName, function(uuidName){
                                let fileRst = {uuid: uuidName, reportName: rptName};
                                callback(req, res, err, fileRst);
                            });
                        });
                    } else {
                        rpt_xl_util.exportExcelInOneBook(rptPageRstArray, pageSize, rptName, function(uuidName){
                            let fileRst = {uuid: uuidName, reportName: rptName};
                            callback(req, res, err, fileRst);
                        });
                    }
                }
            });
        } else if ((rpt_bill_tpl_ids && rpt_bill_tpl_ids.length > 0) || (rpt_glj_tpl_ids && rpt_glj_tpl_ids.length > 0)) {
            getSummaryComboPages(req, user_id, prjIds, rpt_bill_tpl_ids, rpt_glj_tpl_ids, pageSize, orientation, customizeCfg, option, JV.OUTPUT_TYPE_NORMAL, function (err, rptPageRstArray) {
                rpt_xl_util.exportExcelInOneBook(rptPageRstArray, pageSize, rptName, function(uuidName){
                    let fileRst = {uuid: uuidName, reportName: rptName};
                    callback(req, res, err, fileRst);
                });
            });
        }
    },

    createExcelFiles: function (req, res) {
        let params = JSON.parse(req.body.params),
            prj_id = params.prj_id,
            rpt_ids = params.rpt_ids,
            rpt_names = params.rpt_names,
            pageSize = params.pageSize,
            orientation = params.orientation,
            isOneSheet = params.isOneSheet,
            customizeCfg = params.custCfg,
            option = params.option;
        let user_id = req.session.sessionUser.id;
        let parallelFunctions = [];
        let dftOption = option||JV.PAGING_OPTION_NORMAL;
        for (let idx = 0; idx < rpt_ids.length; idx++) {
            let r_id = rpt_ids[idx];
            let r_name = rpt_names[idx];
            parallelFunctions.push((function (rpt_id, rpt_name) {
                return function (cb) {
                    getAllPagesCommon(user_id, prj_id, rpt_id, pageSize, orientation, customizeCfg, dftOption, JV.OUTPUT_TYPE_EXCEL, function (err, pageRst) {
                        if(err){
                            cb(err);
                        } else {
                            rpt_xl_util.exportExcel(pageRst, pageSize, rpt_name, isOneSheet, null, null, function(uuidName){
                                let fileRst = {uuid: uuidName, reportName: rpt_name};
                                cb(err, fileRst);
                            })
                        }
                    })
                }
            })(parseInt(r_id), r_name));
        }
        async.parallel(parallelFunctions, function (err, fileRstArray) {
            if (err) {
                callback(req, res, '数据有误', null);
            } else {
                // console.log(err);
                callback(req, res, err, fileRstArray);
            }
        })
    },

    createExcelFilesEx: function (req, res) {
        let params = JSON.parse(req.body.params),
            prj_id = params.prj_id,
            rpt_ids = params.rpt_ids,
            //--以下是汇总类数据----------
            rpt_bill_tpl_ids = params.rpt_bill_tpl_ids,
            rpt_glj_tpl_ids = params.rpt_glj_tpl_ids,
            prjIds = params.prjIds,
            sum_rpt_names = params.sum_rpt_names,
            //------------
            rpt_names = params.rpt_names,
            pageSize = params.pageSize,
            orientation = params.orientation,
            isOneSheet = params.isOneSheet,
            customizeCfg = params.custCfg,
            option = params.option;
        let user_id = req.session.sessionUser.id;
        let dftOption = option||JV.PAGING_OPTION_NORMAL;
        let pri_Add_Parallel_Functions = function (parallelFunctions, rptPageRstArray, paraRptNames, err) {
            for (let idx = 0; idx < rptPageRstArray.length; idx++) {
                parallelFunctions.push((function (pageRst, rpt_name) {
                    return function (cb) {
                        rpt_xl_util.exportExcel(pageRst, pageSize, rpt_name, isOneSheet, null, null, function(uuidName){
                            let fileRst = {uuid: uuidName, reportName: rpt_name};
                            cb(err, fileRst);
                        })
                    };
                })(rptPageRstArray[idx], paraRptNames[idx]));
            }
        };
        let pri_Run_Parallel_Functions = function (parallelFunctions) {
            async.parallel(parallelFunctions, function (err, fileRstArray) {
                if (err) {
                    console.log('导出Excel错误（导出数据过程错误）, userId: ' + user_id + ', prjId' + prj_id);
                    callback(req, res, '数据导出错误', null);
                } else {
                    // console.log(err);
                    callback(req, res, err, fileRstArray);
                }
            });
        };
        if (rpt_ids && rpt_ids.length > 0) {
            getMultiRptsCommon(user_id, prj_id, rpt_ids, pageSize, orientation, customizeCfg, dftOption, JV.OUTPUT_TYPE_NORMAL, function (err, rptPageRstArray) {
                if (err) {
                    console.log('导出Excel错误（生成数据过程错误）, userId: ' + user_id + ', prjId' + prj_id);
                    callback(req, res, '数据生成错误', null);
                } else {
                    if ((rpt_bill_tpl_ids && rpt_bill_tpl_ids.length > 0) || (rpt_glj_tpl_ids && rpt_glj_tpl_ids.length > 0)) {
                        getSummaryComboPages(req, user_id, prjIds, rpt_bill_tpl_ids, rpt_glj_tpl_ids, pageSize, orientation, customizeCfg, option, JV.OUTPUT_TYPE_NORMAL, function (err, rptSumPageRstArray) {
                            let parallelFunctions = [];
                            pri_Add_Parallel_Functions(parallelFunctions, rptPageRstArray, rpt_names, err);
                            pri_Add_Parallel_Functions(parallelFunctions, rptSumPageRstArray, sum_rpt_names, err);
                            pri_Run_Parallel_Functions(parallelFunctions);
                        });
                    } else {
                        let parallelFunctions = [];
                        pri_Add_Parallel_Functions(parallelFunctions, rptPageRstArray, rpt_names, err);
                        pri_Run_Parallel_Functions(parallelFunctions);
                    }
                }
            });
        } else if ((rpt_bill_tpl_ids && rpt_bill_tpl_ids.length > 0) || (rpt_glj_tpl_ids && rpt_glj_tpl_ids.length > 0)) {
            // console.log('rpt_bill_tpl_ids:');
            // console.log(rpt_bill_tpl_ids);
            // console.log('rpt_glj_tpl_ids:');
            // console.log(rpt_glj_tpl_ids);
            getSummaryComboPages(req, user_id, prjIds, rpt_bill_tpl_ids, rpt_glj_tpl_ids, pageSize, orientation, customizeCfg, option, JV.OUTPUT_TYPE_NORMAL, function (err, rptSumPageRstArray) {
                let parallelFunctions = [];
                pri_Add_Parallel_Functions(parallelFunctions, rptSumPageRstArray, sum_rpt_names, err);
                pri_Run_Parallel_Functions(parallelFunctions);
            });
        }
    },
    getFileByUUID: function (req, res) {
        let uuid = req.params.uuid,
            rptName = req.params.rptName,
            suffix = "." + req.params.suffix
        ;
        // let user_id = req.session.sessionUser.id; //未来要校验user id
        try {
            res.setHeader('Content-Type', 'application/vnd.openxmlformats');
            let rptNameURI = encodeURI(rptName);
            res.setHeader("Content-Disposition", "attachment; filename=\"" + rptNameURI + suffix + "\"; filename*=utf-8''" + rptNameURI + suffix );
            let filestream = fs.createReadStream(__dirname.slice(0, __dirname.length - 28) + '/tmp/' + uuid + suffix);
            filestream.on('data', function(chunk) {
                res.write(chunk);
            });
            filestream.on('end', function() {
                res.end();
            });
        } catch (e) {
            console.log(e);
        }
    },
    getExcel: function(req, res) {
        let prj_id = req.params.prj_id,
            rpt_id = req.params.rpt_id,
            pageSize = req.params.size,
            orientation = req.params.orientation,
            rptName = req.params.rptName,
            isOneSheet = req.params.isOneSheet,
            option = req.params.option
        ;
        let customizeCfg = null;
        let user_id = req.session.sessionUser.id;
        let dftOption = option||JV.PAGING_OPTION_NORMAL;
        getAllPagesCommon(user_id, prj_id, rpt_id, pageSize, orientation, customizeCfg, dftOption, JV.OUTPUT_TYPE_EXCEL, function(err, pageRst){
            try {
                rpt_xl_util.exportExcel(pageRst, pageSize, rptName, isOneSheet, null, null, function(uuidName){
                    res.setHeader('Content-Type', 'application/vnd.openxmlformats');
                    let rptNameURI = encodeURI(rptName);
                    res.setHeader("Content-Disposition", "attachment; filename=\"" + rptNameURI + ".xlsx\"; filename*=utf-8''" + rptNameURI + '.xlsx' );
                    let filestream = fs.createReadStream(__dirname.slice(0, __dirname.length - 28) + '/tmp/' + uuidName + '.xlsx');
                    filestream.on('data', function(chunk) {
                        res.write(chunk);
                    });
                    filestream.on('end', function() {
                        res.end();
                    });
                });
            } catch (e) {
                console.log(e);
            }
        })
    },
    getExcelInOneBook: function (req, res) {
        let prj_id = req.params.prj_id,
            rpt_ids = req.params.rpt_ids.split(','),
            pageSize = req.params.size,
            rptName = req.params.rptName,
            option = req.params.option;
        let user_id = req.session.sessionUser.id;
        let parallelFunctions = [];
        let dftOption = option||JV.PAGING_OPTION_NORMAL;
        for (let id of rpt_ids) {
            parallelFunctions.push((function (rpt_id) {
                return function (cb) {
                    getAllPagesCommon(user_id, prj_id, rpt_id, pageSize, null, null, dftOption, JV.OUTPUT_TYPE_EXCEL, function (err, pageRst) {
                        if(err){
                            cb(err);
                        }
                        else{
                            cb(null, pageRst);
                        }
                    })
                }
            })(parseInt(id)));
        }
        async.parallel(parallelFunctions, function (err, pageRstArray) {
            if (err) {
                callback(req, res, '数据有误', null);
            } else {
                rpt_xl_util.exportExcelInOneBook(pageRstArray, pageSize, rptName, function(tmpFilePath){
                    res.setHeader('Content-Type', 'application/vnd.openxmlformats');
                    let rptNameURI = encodeURI(rptName);
                    res.setHeader("Content-Disposition", "attachment; filename=\"" + rptNameURI + ".xlsx\"; filename*=utf-8''" + rptNameURI + '.xlsx');
                    let filestream = fs.createReadStream(__dirname.slice(0, __dirname.length - 28) + '/tmp/' + tmpFilePath + '.xlsx');
                    filestream.on('data', function(chunk) {
                        res.write(chunk);
                    });
                    filestream.on('end', function() {
                        res.end();
                    });
                });
            }
        })
    },
    createPdfFiles: function (req, res) {
        let params = JSON.parse(req.body.params),
            prj_id = params.prj_id,
            rpt_ids = params.rpt_ids,
            rpt_names = params.rpt_names,
            pageSize = params.pageSize,
            orientation = params.orientation,
            customizeCfg = params.custCfg,
            option = params.option;
        let user_id = req.session.sessionUser.id;
        let parallelFunctions = [];
        let dftOption = option||JV.PAGING_OPTION_NORMAL;
        for (let idx = 0; idx < rpt_ids.length; idx++) {
            let r_id = rpt_ids[idx];
            let r_name = rpt_names[idx];
            parallelFunctions.push((function (rpt_id, rpt_name) {
                return function (cb) {
                    getAllPagesCommon(user_id, prj_id, rpt_id, pageSize, orientation, customizeCfg, dftOption, JV.OUTPUT_TYPE_PDF, function (err, pageRst) {
                        if(err){
                            cb(err);
                        }
                        else{
                            rpt_pdf_util.export_pdf_file(pageRst, pageSize, rpt_name, function(uuidName){
                                let fileRst = {uuid: uuidName, reportName: rpt_name};
                                cb(err, fileRst);
                            })
                        }
                    })
                }
            })(parseInt(r_id), r_name));
        }
        async.parallel(parallelFunctions, function (err, fileRstArray) {
            if (err) {
                callback(req, res, '数据有误', null);
            } else {
                // console.log(err);
                callback(req, res, err, fileRstArray);
            }
        })
    },
    createPdfFilesEx: function (req, res) {
        let params = JSON.parse(req.body.params),
            prj_id = params.prj_id,
            rpt_ids = params.rpt_ids,
            rpt_names = params.rpt_names,
            //--以下是汇总类数据----------
            rpt_bill_tpl_ids = params.rpt_bill_tpl_ids,
            rpt_glj_tpl_ids = params.rpt_glj_tpl_ids,
            prjIds = params.prjIds,
            sum_rpt_names = params.sum_rpt_names,
            //------------
            pageSize = params.pageSize,
            orientation = params.orientation,
            customizeCfg = params.custCfg,
            option = params.option;
        let user_id = req.session.sessionUser.id;
        let dftOption = option||JV.PAGING_OPTION_NORMAL;
        console.log('start!');
        let pri_Add_Parallel_Functions = function (parallelFunctions, rptPageRstArray, paraRptNames, err) {
            for (let idx = 0; idx < rptPageRstArray.length; idx++) {
                parallelFunctions.push((function (pageRst, rpt_name) {
                    return function (cb) {
                        rpt_pdf_util.export_pdf_file(pageRst, pageSize, rpt_name, function(uuidName){
                            let fileRst = {uuid: uuidName, reportName: rpt_name};
                            cb(err, fileRst);
                        })
                    };
                })(rptPageRstArray[idx], paraRptNames[idx]));
            }
        };
        let pri_Run_Parallel_Functions = function (parallelFunctions) {
            async.parallel(parallelFunctions, function (err, fileRstArray) {
                if (err) {
                    console.log('导出PDF错误（生成数据过程错误）, userId: ' + user_id + ', prjId' + prj_id);
                    callback(req, res, '数据导出错误', null);
                } else {
                    // console.log(err);
                    callback(req, res, err, fileRstArray);
                }
            });
        };
        if (rpt_ids && rpt_ids.length > 0) {
            console.log(0);
            getMultiRptsCommon(user_id, prj_id, rpt_ids, pageSize, orientation, customizeCfg, dftOption, JV.OUTPUT_TYPE_PDF, function (err, rptPageRstArray) {
                if (err) {
                    console.log('导出Excel错误（生成数据过程错误）, userId: ' + user_id + ', prjId' + prj_id);
                    callback(req, res, '数据生成错误', null);
                } else {
                    if ((rpt_bill_tpl_ids && rpt_bill_tpl_ids.length > 0) || (rpt_glj_tpl_ids && rpt_glj_tpl_ids.length > 0)) {
                        console.log(1);
                        getSummaryComboPages(req, user_id, prjIds, rpt_bill_tpl_ids, rpt_glj_tpl_ids, pageSize, orientation, customizeCfg, option, JV.OUTPUT_TYPE_NORMAL, function (err, rptSumPageRstArray) {
                            let parallelFunctions = [];
                            console.log(2);
                            pri_Add_Parallel_Functions(parallelFunctions, rptPageRstArray, rpt_names, err);
                            pri_Add_Parallel_Functions(parallelFunctions, rptSumPageRstArray, sum_rpt_names, err);
                            pri_Run_Parallel_Functions(parallelFunctions);
                        });
                    } else {
                        console.log(3);
                        let parallelFunctions = [];
                        pri_Add_Parallel_Functions(parallelFunctions, rptPageRstArray, rpt_names, err);
                        pri_Run_Parallel_Functions(parallelFunctions);
                    }
                }
            });
        } else if ((rpt_bill_tpl_ids && rpt_bill_tpl_ids.length > 0) || (rpt_glj_tpl_ids && rpt_glj_tpl_ids.length > 0)) {
            console.log(10);
            getSummaryComboPages(req, user_id, prjIds, rpt_bill_tpl_ids, rpt_glj_tpl_ids, pageSize, orientation, customizeCfg, option, JV.OUTPUT_TYPE_NORMAL, function (err, rptSumPageRstArray) {
                let parallelFunctions = [];
                pri_Add_Parallel_Functions(parallelFunctions, rptSumPageRstArray, sum_rpt_names, err);
                pri_Run_Parallel_Functions(parallelFunctions);
            });
        }
    },
    getPDF:function (req, res) {
        let prj_id = req.params.prj_id,
            rpt_id = req.params.rpt_id,
            pageSize = req.params.size,
            orientation = req.params.orientation,
            rptName = req.params.rptName
        ;
        let user_id = req.session.sessionUser.id;
        getAllPagesCommon(user_id, prj_id, rpt_id, pageSize, orientation, null, JV.PAGING_OPTION_NORMAL, JV.OUTPUT_TYPE_PDF, function(err, pageRst){
            rpt_pdf_util.export_pdf_file(pageRst, pageSize, rptName,function (uuidName) {
                res.setHeader('Content-Type', 'application/vnd.openxmlformats');
                // res.setHeader("Content-Disposition", "attachment; filename=" + strUtil.getPinYinCamelChars(rptName) + ".pdf");
                let rptNameURI = encodeURI(rptName);
                res.setHeader("Content-Disposition", "attachment; filename=\"" + rptNameURI + ".pdf\"; filename*=utf-8''" + rptNameURI + ".pdf" );

                let filestream = fs.createReadStream(__dirname.slice(0, __dirname.length - 28) + '/tmp/' + uuidName + '.pdf');
                filestream.on('data', function(chunk) {
                    res.write(chunk);
                });
                filestream.on('end', function() {
                    res.end();
                });
            })

        })

    },

    getTestReportAllPages: function(req, res){
        let rpt_id = req.body.ID;
        let pageSize = req.body.pageSize;
        getAllPagesCommonOrg(rpt_id, pageSize, JV.PAGING_OPTION_NORMAL, function(err, pageRst){
            //fs.writeFileSync('D:/GitHome/ConstructionOperation/tmp/testRpt.js', JSON.stringify(pageRst));
            callback(req, res, err, pageRst);
        })
    },
    getTestExcel: function(req, res) {
        let rpt_id = req.params.id,
            pageSize = req.params.size,
            rptName = req.params.rptName,
            isOneSheet = req.params.isOneSheet,
            option = req.params.option;
        let dftOption = option||JV.PAGING_OPTION_NORMAL;
        getAllPagesCommonOrg(rpt_id, pageSize, dftOption, function(err, pageRst){
            fs.writeFileSync('D:/GitHome/ConstructionOperation/tmp/testRpt.js', JSON.stringify(pageRst));
            try {
                rpt_xl_util.exportExcel(pageRst, pageSize, rptName, isOneSheet, null, null, function(uuidName){
                    res.setHeader('Content-Type', 'application/vnd.openxmlformats');
                    res.setHeader("Content-Disposition", "attachment; filename=" + strUtil.getPinYinCamelChars(rptName) + ".xlsx");
                    let filestream = fs.createReadStream(__dirname.slice(0, __dirname.length - 28) + '/tmp/' + uuidName + '.xlsx');
                    filestream.on('data', function(chunk) {
                        res.write(chunk);
                    });
                    filestream.on('end', function() {
                        res.end();
                    });
                });
            } catch (e) {
                console.log(e);
            }
        })
    },
    getTestExcelInOneBook: function(req, res) {
        let rpt_ids = req.params.ids.split(','),
            pageSize = req.params.size,
            rptName = req.params.rptName,
            option = req.params.option;
        let parallelFunctions = [];
        let dftOption = option||JV.PAGING_OPTION_NORMAL;
        for (let id of rpt_ids) {
            parallelFunctions.push((function (rpt_id) {
                return function (cb) {
                    getAllPagesCommonOrg(rpt_id, pageSize, dftOption, function (err, pageRst) {
                        if(err){
                            cb(err);
                        }
                        else{
                            cb(null, pageRst);
                        }
                    })
                }
            })(parseInt(id)));
        }
        async.parallel(parallelFunctions, function (err, pageRstArray) {
            if (err) {
                callback(req, res, '数据有误', null);
            } else {
                rpt_xl_util.exportExcelInOneBook(pageRstArray, pageSize, rptName, function(tmpFilePath){
                    res.setHeader('Content-Type', 'application/vnd.openxmlformats');
                    res.setHeader("Content-Disposition", "attachment; filename=" + strUtil.getPinYinCamelChars(rptName) + ".xlsx");
                    let filestream = fs.createReadStream(__dirname.slice(0, __dirname.length - 28) + '/tmp/' + tmpFilePath + '.xlsx');
                    filestream.on('data', function(chunk) {
                        res.write(chunk);
                    });
                    filestream.on('end', function() {
                        res.end();
                    });
                });
                //callback(req, res, false, '', {compilation: rst, gljLibs: gljLibsRst});
            }
        })
    },
    getTestPDF:function (req, res) {
        let rpt_id = req.params.id,
            pageSize = req.params.size,
            rptName = req.params.rptName;

        getAllPagesCommonOrg(rpt_id, pageSize, JV.PAGING_OPTION_NORMAL, function(err, pageRst){
            rpt_pdf_util.export_pdf_file(pageRst, pageSize, rptName,function (uuidName) {
                res.setHeader('Content-Type', 'application/vnd.openxmlformats');
                // res.setHeader("Content-Disposition", "attachment; filename=" + strUtil.getPinYinCamelChars(rptName) + ".pdf");
                let rptNameURI = encodeURI(rptName);
                res.setHeader("Content-Disposition", "attachment; filename=\"" + rptNameURI + ".pdf\"; filename*=utf-8''" + rptNameURI + ".pdf"  );

                let filestream = fs.createReadStream(__dirname.slice(0, __dirname.length - 28) + '/tmp/' + uuidName + '.pdf');
                filestream.on('data', function(chunk) {
                    res.write(chunk);
                });
                filestream.on('end', function() {
                    res.end();
                });
            })

        })

    }
};
