/**
 * Created by Tony on 2017/3/13.
 */
let UserModel =  require("../../users/models/user_model");
const mongoose = require("mongoose");
const async = require("async");

const JV = require("../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');

const rptTplFacade = require("../facade/rpt_template_facade");
const demoTemplateFacade = require("../facade/rpt_tpl_data_demo_facade");

const JpcEx = require("../rpt_component/jpc_ex");
const rptUtil = require("../util/rpt_util");
const rpt_xl_util = require("../util/rpt_excel_util");
const rpt_pdf_util = require("../util/rpt_pdf_util");
const rpt_svg_util = require("../util/rpt_svg_util");
const fs = require("fs");
const strUtil = require("../../../public/stringUtil");
const rptDataExtractor = require("../util/rpt_construct_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});
    }
};

const WATERMARK_FONT = {
    "Name": "宋体",
    "FontHeight": "32",
    "FontColor": "GOLD",
    "FontBold": "T",
    "FontItalic": "F",
    "FontUnderline": "F",
    "FontStrikeOut": "F",
    "FontAngle": "45"
};

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

async function getAllPagesCommon(user_id, prj_id, prj_ids, rpt_id, pageSize, orientation, customizeCfg, option, outputType, flag, 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 = [], economicRst = [];
            let filter = rptDataUtil.getDataRequestFilter(summaryRst, economicRst);
            let promiseArr = [null, 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);
                }
            }
            if (economicRst.length > 0) {
                // economicRst.push('ProjectInfoFields');
                // economicRst.push('ProjectFeatureFields');
                promiseArr[2] = pm_facade.getIndexReportData(prj_id, economicRst);
            }

            let _createPntPageData = function(tplData, rptTpl) {
                try {
                    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) {
                        // 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.toString());
                    cb('Exception occurs while on going...', null);
                }
            };

            let buildPageData = function(rawDataObj, rptDataUtil, rptTpl) {
                try {
                    let tplData = rptDataUtil.assembleData(rawDataObj);
                    _createPntPageData(tplData, rptTpl);
                } catch (ex) {
                    console.log("报表数据异常： userId " + user_id + ", project id: " + prj_id);
                    console.log(ex.toString());
                    cb('Exception occurs while on going...', null);
                }
            };
        if (flag !== undefined && flag !== null && (flag.constructSumType === 'constructSum' || flag.auditType === 'audit_compare')) {
                //备注：原先这个功能是为了合并建设项目下所有的单位工程的数据，
                //     现在发现就是通用型，审核对比也可以用这个逻辑把数据合并在一起再处理(审核对比的处理逻辑放在模板计算式里)
                try {
                    console.log('准备取建设项目下所有单位工程数据：');
                    const _combineData = function(destData, srcData) {
                        // 备注：这里有一个前提条件，就是基于相同的报表模板
                        for (let idx = 0; idx < destData[JV.DATA_DISCRETE_DATA].length; idx++) {
                            destData[JV.DATA_DISCRETE_DATA][idx] = destData[JV.DATA_DISCRETE_DATA][idx].concat(srcData[JV.DATA_DISCRETE_DATA][idx]);
                        }
                        for (let idx = 0; idx < destData[JV.DATA_MASTER_DATA].length; idx++) {
                            destData[JV.DATA_MASTER_DATA][idx] = destData[JV.DATA_MASTER_DATA][idx].concat(srcData[JV.DATA_MASTER_DATA][idx]);
                        }
                        for (let idx = 0; idx < destData[JV.DATA_MASTER_DATA_EX].length; idx++) {
                            destData[JV.DATA_MASTER_DATA_EX][idx] = destData[JV.DATA_MASTER_DATA_EX][idx].concat(srcData[JV.DATA_MASTER_DATA_EX][idx]);
                        }
                        for (let idx = 0; idx < destData[JV.DATA_DETAIL_DATA].length; idx++) {
                            destData[JV.DATA_DETAIL_DATA][idx] = destData[JV.DATA_DETAIL_DATA][idx].concat(srcData[JV.DATA_DETAIL_DATA][idx]);
                        }
                        for (let idx = 0; idx < destData[JV.DATA_DETAIL_DATA_EX].length; idx++) {
                            destData[JV.DATA_DETAIL_DATA_EX][idx] = destData[JV.DATA_DETAIL_DATA_EX][idx].concat(srcData[JV.DATA_DETAIL_DATA_EX][idx]);
                        }
                    };
                    // let multiRawData = rptTplDataFacade.prepareMultiProjectData(user_id, prj_ids, filter);
                    // //终于出来结果了 !_! (multiRawData是多个单位工程的原始数据！)
                    // if (multiRawData.length > 0) {
                    //     //考虑到工料机的数据还需要再计算，所以还不能直接用，需要每个工程都处理一遍后，再合并
                    //     let tplData = rptDataUtil.assembleData(multiRawData[0]);
                    //     for (let idx = 1; idx < multiRawData.length; idx++) {
                    //         let tmpData = rptDataUtil.assembleData(multiRawData[idx]);
                    //         _combineData(tplData, tmpData);
                    //     }
                    //     _createPntPageData(tplData, rptTpl);
                    // } else {
                    //     cb('Have errors while on going...', null);
                    // }

                    rptTplDataFacade.prepareMultiProjectData(user_id, prj_ids, filter).then(function(multiRawData) {
                        //终于出来结果了 !_! (multiRawData是多个单位工程的原始数据！)
                        if (multiRawData.length > 0) {
                            //考虑到工料机的数据还需要再计算，所以还不能直接用，需要每个工程都处理一遍后，再合并
                            let tplData = rptDataUtil.assembleData(multiRawData[0]);
                            for (let idx = 1; idx < multiRawData.length; idx++) {
                                let tmpData = rptDataUtil.assembleData(multiRawData[idx]);
                                _combineData(tplData, tmpData);
                            }
                            _createPntPageData(tplData, rptTpl);
                        } else {
                            cb('Have errors while on going...', null);
                        }
                    });
                } catch(ex) {
                    console.log("取建设项目下所有单位工程数据异常： userId " + user_id + ", project id: " + prj_ids.toString());
                    console.log(ex.toString());
                    cb('Exception occurs while on going...', null);
                }
            } else {
                //原有流程
                rptTplDataFacade.prepareProjectData(user_id, prj_id, filter, function (err, msg, rawDataObj) {
                    if (!err) {
                        //取汇总数据流程
                        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 {
                            if (promiseArr[2] !== null) {
                                promiseArr[2].then(function (rst) {
                                    let ecoFieldsRst = (rst._doc)?rst._doc:rst;
                                    // fsUtil.writeObjToFile(ecoFieldsRst, "D:/GitHome/ConstructionCost/tmp/testEcoFieldsResult.jsp");
                                    rawDataObj.prjData.push({moduleName: 'ProjectInfoFields', data: ecoFieldsRst.ProjectInfoFields});
                                    rawDataObj.prjData.push({moduleName: 'ProjectFeatureFields', data: ecoFieldsRst.ProjectFeatureFields});
                                    rawDataObj.prjData.push({moduleName: 'ProjectCostFields', data: ecoFieldsRst.ProjectCostFields});
                                    rawDataObj.prjData.push({moduleName: 'ProjectEcoFields', data: ecoFieldsRst.ProjectEcoFields});
                                    rawDataObj.prjData.push({moduleName: 'ProjectLabMaterialFields', data: ecoFieldsRst.ProjectLabMaterialFields});
                                    rawDataObj.prjData.push({moduleName: 'ProjectQtyFields', data: ecoFieldsRst.ProjectQtyFields});
                                    buildPageData(rawDataObj, rptDataUtil, rptTpl);
                                });
                            } else {
                                buildPageData(rawDataObj, rptDataUtil, rptTpl);
                            }
                        }
                    } else {
                        cb('No report data were found!', null);
                    }
                });
            }
        } else {
            cb('No report template was found!', null);
        }
    })
}

function fillWaterMark(pageRstArray) {
    for (const pageRst of pageRstArray) {
        if (!pageRst[JV.NODE_FONT_COLLECTION].hasOwnProperty(JV.PROP_WATERMARK)) {
            pageRst[JV.NODE_FONT_COLLECTION][JV.PROP_WATERMARK] = WATERMARK_FONT;
        }
        for (const page of pageRst.items) {
            const warterCell = {
                "font": "WaterMark",
                "control": "NewContent_Center",
                "style": "Default_None",
                "Value": "大司空云计价",
                "area": {
                    "Left": 300,
                    "Right": 500,
                    "Top": 300,
                    "Bottom": 500
                }
            };
            //page.cells.push(warterCell);
            page.cells.unshift(warterCell);
        }
    }
}

module.exports = {
    getReportAllPages: function (req, res) {
        let params = JSON.parse(req.body.params),
            rpt_id = params.rpt_tpl_id,
            prj_id = params.prj_id,
            prj_ids = params.prj_ids,
            flag = params.flag;
            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, prj_ids, rpt_id, pageSize, orientation, customizeCfg, null, JV.OUTPUT_TYPE_NORMAL, flag, function (err, pageRst) {
            try {
                let userModel = new UserModel();
                // console.log('req.session.sessionUser.ssoId: ' + req.session.sessionUser.ssoId);
                userModel.isFree(req.session.sessionUser.ssoId, params.compilation).then(function(rst) {
                    // console.log('is Free user? ' + rst);
                    if (rst) {
                        //加水印！
                        // fillWaterMark([pageRst]);
                    }
                    callback(req, res, err, pageRst);
                });
            } catch (error) {
                //
            } finally {
                //callback(req, res, err, pageRst);
            }
        });
    },
    getMultiReports: function (req, res) {
        let params = JSON.parse(req.body.params),
            prj_id = params.prj_id,
            prj_ids = params.prj_ids,
            compare_ids = params.compare_ids,
            rpt_ids = params.rpt_ids.split(','),
            flags = params.flags;
            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 id = rpt_ids[idx], r_flag = flags[idx];
            let f_prj_ids = prj_ids;
            if (r_flag !== undefined && r_flag !== null && r_flag.auditType === 'audit_compare') {
                f_prj_ids = compare_ids[idx];
            }
            parallelFunctions.push((function (rpt_id, flag) {
                return function (cb) {
                    getAllPagesCommon(user_id, prj_id, f_prj_ids, rpt_id, pageSize, orientation, customizeCfg, dftOption, JV.OUTPUT_TYPE_NORMAL, flag, function (err, pageRst) {
                        if(err){
                            cb(err);
                        }
                        else{
                            cb(null, pageRst);
                        }
                    })
                }
            })(parseInt(id), r_flag));
        }
        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.split(','),
            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;
    },

    getReportAllPagesSvg: function (req, res) {
        let params = JSON.parse(req.body.params),
            rpt_id = params.rpt_tpl_id,
            flag = params.flag;
            prj_id = params.prj_id,
            prj_ids = params.prj_ids,
            pageSize = params.pageSize,
            orientation = params.orientation,
            customizeCfg = params.custCfg
        ;
        let user_id = req.session.sessionUser.id;
        getAllPagesCommon(user_id, prj_id, prj_ids, rpt_id, pageSize, orientation, customizeCfg, null, JV.OUTPUT_TYPE_SVG, flag, 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,
            prj_ids = params.prj_ids,
            compare_ids = params.compare_ids,
            rpt_ids = params.rpt_ids,
            flags = params.flags;
            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], r_flag = flags[idx];
            let f_prj_ids = prj_ids;
            if (r_flag !== undefined && r_flag !== null && r_flag.auditType === 'audit_compare') {
                f_prj_ids = compare_ids[idx];
            }
            parallelFunctions.push((function (rpt_id, flag) {
                return function (cb) {
                    getAllPagesCommon(user_id, prj_id, f_prj_ids, rpt_id, pageSize, orientation, customizeCfg, dftOption, JV.OUTPUT_TYPE_EXCEL, flag, function (err, pageRst) {
                        if(err){
                            cb(err);
                        }
                        else{
                            cb(err, pageRst);
                        }
                    })
                }
            })(parseInt(r_id), r_flag));
        }
        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);
                });
            }
        })
    },

    createExcelFiles: function (req, res) {
        let params = JSON.parse(req.body.params),
            prj_id = params.prj_id,
            prj_ids = params.prj_ids,
            compare_ids = params.compare_ids,
            rpt_ids = params.rpt_ids,
            flags = params.flags;
            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], r_flag = flags[idx];
            let f_prj_ids = prj_ids;
            if (r_flag !== undefined && r_flag !== null && r_flag.auditType === 'audit_compare') {
                f_prj_ids = compare_ids[idx];
            }
            let r_name = rpt_names[idx];
            parallelFunctions.push((function (rpt_id, rpt_name, flag) {
                return function (cb) {
                    getAllPagesCommon(user_id, prj_id, f_prj_ids, rpt_id, pageSize, orientation, customizeCfg, dftOption, JV.OUTPUT_TYPE_EXCEL, flag, 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, r_flag));
        }
        async.parallel(parallelFunctions, function (err, fileRstArray) {
            if (err) {
                callback(req, res, '数据有误', null);
            } else {
                // console.log(err);
                callback(req, res, err, fileRstArray);
            }
        })
    },
    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,
            prj_ids = params.prj_ids,
            rpt_id = req.params.rpt_id,
            flag = req.params.flag,
            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, prj_ids, rpt_id, pageSize, orientation, customizeCfg, dftOption, JV.OUTPUT_TYPE_EXCEL, flag, 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,
            prj_ids = params.prj_ids,
            rpt_ids = req.params.rpt_ids.split(','),
            flags = req.params.flags;
            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 idx = 0; idx < rpt_ids.length; idx++) {
            let id = rpt_ids[idx], r_flag = flags[idx];
            parallelFunctions.push((function (rpt_id, flag) {
                return function (cb) {
                    getAllPagesCommon(user_id, prj_id, prj_ids, rpt_id, pageSize, null, null, dftOption, JV.OUTPUT_TYPE_EXCEL, flag, function (err, pageRst) {
                        if(err){
                            cb(err);
                        }
                        else{
                            cb(null, pageRst);
                        }
                    })
                }
            })(parseInt(id), r_flag));
        }
        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,
            prj_ids = params.prj_ids,
            rpt_ids = params.rpt_ids,
            flags = params.flags,
            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], r_flag = flags[idx];
            let r_name = rpt_names[idx];
            parallelFunctions.push((function (rpt_id, rpt_name, flag) {
                return function (cb) {
                    getAllPagesCommon(user_id, prj_id, prj_ids, rpt_id, pageSize, orientation, customizeCfg, dftOption, JV.OUTPUT_TYPE_PDF, flag, 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, r_flag));
        }
        async.parallel(parallelFunctions, function (err, fileRstArray) {
            if (err) {
                callback(req, res, '数据有误', null);
            } else {
                // console.log(err);
                callback(req, res, err, fileRstArray);
            }
        })
    },
    getPDF:function (req, res) {
        let prj_id = req.params.prj_id,
            prj_ids = params.prj_ids,
            rpt_id = req.params.rpt_id,
            flag = req.params.flag;
            pageSize = req.params.size,
            orientation = req.params.orientation,
            rptName = req.params.rptName
        ;
        let user_id = req.session.sessionUser.id;
        getAllPagesCommon(user_id, prj_id, prj_ids, rpt_id, pageSize, orientation, null, JV.PAGING_OPTION_NORMAL, JV.OUTPUT_TYPE_PDF, flag, 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();
                });
            })

        })

    }
};

