/**
 * Created by Tony on 2018/8/15.
 */

let test = require('tape');
const JpcEx = require("../../../modules/reports/rpt_component/jpc_ex");
const JV = require("../../../modules/reports/rpt_component/jpc_value_define");
let config = require("../../../config/config.js");
config.setupDb(process.env.NODE_ENV);
let mongoose = require("mongoose");
let fileUtils = require("../../../modules/common/fileUtils");
let path = require('path');
let dbm = require("../../../config/db/db_manager");
let rpt_cfg = require('./rpt_cfg');
let consts = require('../../../modules/main/models/project_consts');
dbm.connect(process.env.NODE_ENV);

//统一引用models
fileUtils.getGlobbedFiles('../../../modules/all_models/*.js').forEach(function(modelPath) {
    require(path.resolve(modelPath));
});

let cfgCacheUtil = require("../../../config/cacheCfg");
cfgCacheUtil.setupDftCache();

let fsUtil = require("../../../public/fsUtil");

let demoPrjId = - 1;
let demoRptId = 551; //05
// let demoRptId = 626; //06
let pagesize = "A4";

// demoPrjId = 720; //QA: DW3
// demoPrjId = 4563; //QA:
demoPrjId = 4552; //UAT:
//*/
// let userId_Leng = "59cdf14a0034a1000ba52b97"; //小冷User Id 换成_id了
let userId_Leng = "5b5a66c4a3c23e000dccdd77"; //海珠的 _id
let userId_Dft = userId_Leng;
/*/
 let userId_Dft = "595328da1934dc327cad08eb";
 //*/

let rptTplFacade = require("../../../modules/reports/facade/rpt_template_facade");
let rptTplDataFacade = require("../../../modules/reports/facade/rpt_tpl_data_facade");
let pm_facade = require('../../../modules/pm/facade/pm_facade');

const rptDataExtractor = require("../../../modules/reports/util/rpt_construct_data_util");

let fs = require('fs');
//设置Date Format函数
fs.readFile(__dirname.slice(0, __dirname.length - 18) + '/public/web/date_util.js', 'utf8', 'r', function (err, data) {
    eval(data);
});

//*
test('测试 - 模板05汇总表: ', function (t) {
    rptTplFacade.getRptTemplate(demoRptId).then(function(rptTpl) {
        let rptDataUtil = new rptDataExtractor();
        rptDataUtil.initialize(rptTpl._doc);
        let summaryRst = [];
        let filter = rptDataUtil.getDataRequestFilter(summaryRst);
        console.log(filter);
        console.log(summaryRst);
        let promiseArr = [null, null];
        if (summaryRst.length > 0) {
            if (summaryRst.indexOf(`Construct`) >= 0 || summaryRst.indexOf(`ConstructDetail`) >= 0) {
                promiseArr[0] = pm_facade.getSummaryInfoByTender(demoPrjId, pm_facade.projectType.project);
            }
            if (summaryRst.indexOf(`Segment`) >= 0 || summaryRst.indexOf(`SegmentDetail`) >= 0) {
                promiseArr[1] = pm_facade.getSummaryInfoByTender(demoPrjId, pm_facade.projectType.engineering);
            }
        }
        //*/
        rptTplDataFacade.prepareProjectData(userId_Dft, demoPrjId, 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(t, rawDataObj, rptDataUtil, rptTpl);
                            });
                        } else {
                            buildPageData(t, rawDataObj, rptDataUtil, rptTpl);
                        }
                    });
                } else  if (promiseArr[1] !== null) {
                    try {
                        promiseArr[1].then(function (rst) {
                            rawDataObj.Segment = rst.parent;
                            rawDataObj.SegmentDetail = rst.subList;
                            buildPageData(t, rawDataObj, rptDataUtil, rptTpl);
                        });
                    } catch (ex) {
                        console.log(ex);
                    }
                } else {
                    buildPageData(t, rawDataObj, rptDataUtil, rptTpl);
                }
            } else {
                console.log(msg);
                t.pass('pass with error!');
                t.end();
            }
        });
        //*/
        //正常应该根据报表模板定义的数据类型来请求数据
    });
});
//*/

function buildPageData(t, rawDataObj, rptDataUtil, rptTpl) {
    try {
        // fsUtil.writeObjToFile(rawDataObj, "D:/GitHome/ConstructionCost/tmp/rptTplRawDataObject_汇总表.jsp");
        let tplData = rptDataUtil.assembleData(rawDataObj);
        fsUtil.writeObjToFile(rawDataObj, "D:/GitHome/ConstructionCost/tmp/rptTplRawDataAfterCacl_汇总表.jsp");
        fsUtil.writeObjToFile(tplData, "D:/GitHome/ConstructionCost/tmp/rptTplAssembledData_汇总表.jsp");
        //it's time to build the report!!!
        let printCom = JpcEx.createNew();
        rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_PAGE_SIZE] = pagesize;
        let defProperties = rpt_cfg;
        let dftOption = JV.PAGING_OPTION_NORMAL;
        printCom.initialize(rptTpl);
        // fsUtil.writeObjToFile(tplData, "D:/GitHome/ConstructionCost/tmp/rptAssembledData_汇总表.jsp");
        // fsUtil.writeObjToFile(rawDataObj, "D:/GitHome/ConstructionCost/tmp/rptRawDataAfterAssembled_汇总表.jsp");
        printCom.analyzeData(rptTpl, tplData, defProperties, dftOption);
        let maxPages = printCom.totalPages;
        let pageRst = printCom.outputAsSimpleJSONPageArray(rptTpl, tplData, 1, maxPages, defProperties);
        if (pageRst) {
            // fsUtil.writeObjToFile(pageRst, "D:/GitHome/ConstructionCost/tmp/rptPageResult_汇总表.jsp");
        } else {
            console.log("oh! no pages were created!");
        }
    } catch (ex) {
        console.log(ex);
        t.pass('pass with exception!');
        t.end();
    }

    t.pass('pass succeeded!');
    t.end();
}

test('close the connection', function (t) {
    setTimeout(function () {
        mongoose.disconnect();
        t.pass('closing db connection');
        t.end();
    }, 3000);
    // mongoose.disconnect();
    // t.pass('closing db connection');
    // t.end();
});