/**
 * Created by Tony on 2019/3/10.
 */

let test = require('tape');
import JpcEx from "../../../modules/reports/rpt_component/jpc_ex";
import JV from "../../../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');
dbm.connect(process.env.NODE_ENV);

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

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

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

let pm_facade = require('../../../modules/pm/facade/pm_facade');

let demoRptIds = [];
// demoRptIds.push(38); //5.2.2表
// demoRptIds.push(6); //封面
// demoRptIds.push(22); //03
// demoRptIds.push(23); //04 综合费率表
// demoRptIds.push(24); //05 预算
// demoRptIds.push(25); //06
// demoRptIds.push(26); //07
// demoRptIds.push(27); //08
// demoRptIds.push(28); //09
// demoRptIds.push(20); //01
// demoRptIds.push(56); //24
// demoRptIds.push(36); //5.1
// demoRptIds.push(49); //5.5
// demoRptIds.push(66); //5.4
// demoRptIds.push(57); //01
// demoRptIds.push(58); //03
// demoRptIds.push(59); //04
demoRptIds.push(65); //05 工程量清单

let pagesize = "A4";

let userId_Leng = "5c3ffa9aa0a92732f41216e0"; //小冷User Id (养护的)
// let userId_me = "5b6a60b1c4ba33000dd417c0"; //我的
// let userId_HaiZhu = "5b5a66c4a3c23e000dccdd77"; //海珠user id
let demoPrjId = - 1;
// demoPrjId = 720; //QA: DW3
//demoPrjId = 1626; //QA:
// demoPrjId = 2260; //QA:
// demoPrjId = 410; //QA:
// demoPrjId = 313; //PROD:
// demoPrjId = 455; //PROD:
// demoPrjId = 618; //PROD:
// demoPrjId = 815; //PROD:
demoPrjId = 552; //UAT:
//*/
let userId_Dft = userId_Leng;
// let userId_Dft = "5a025c4c15074d134c2b9689";
/*/
 let userId_Dft = "595328da1934dc327cad08eb";
 //*/

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

import rptDataExtractor from "../../../modules/reports/util/rpt_yanghu_data_util";
import rpt_xl_util from "../../../modules/reports/util/rpt_excel_util";
import rpt_pdf_util from "../../../modules/reports/util/rpt_pdf_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('测试 - 测试模板啦: ', function (t) {
    rptTplFacade.getRptTemplates(demoRptIds).then(function(rptTpls) {
        // console.log(rptTpls);
        let rptDataUtil = new rptDataExtractor();
        let filters = [];
        let summaryRst = [];
        let summaryIdxArr = [];
        //let promiseArr = [null, null];
        let promisesArr = []; //
        for (let tplFilterIdx = 0; tplFilterIdx < rptTpls.length; tplFilterIdx++) {
            let rptTpl = rptTpls[tplFilterIdx];
            rptDataUtil.initialize((rptTpl._doc)?rptTpl._doc:rptTpl);
            let filter = rptDataUtil.getDataRequestFilter(summaryRst);
            for (let dtlFilter of filter) {
                if (filters.indexOf(dtlFilter) < 0) {
                    filters.push(dtlFilter);
                }
            }
            if (summaryRst.length > 0) {
                summaryIdxArr.push(tplFilterIdx);
                promisesArr.push([null, null]);
                if (summaryRst.indexOf(`Construct`) >= 0 || summaryRst.indexOf(`ConstructDetail`) >= 0) {
                    promisesArr[promisesArr.length - 1][0] = pm_facade.getSummaryInfoByTender(demoPrjId, pm_facade.projectType.project);
                }
                if (summaryRst.indexOf(`Segment`) >= 0 || summaryRst.indexOf(`SegmentDetail`) >= 0) {
                    promisesArr[promisesArr.length - 1][1] = pm_facade.getSummaryInfoByTender(demoPrjId, pm_facade.projectType.engineering);
                }
            }
        }
        filters.push('projectGLJ'); //临时用
        console.log(filters);
        //正常应该根据报表模板定义的数据类型来请求数据
        rptTplDataFacade.prepareProjectData(userId_Dft, demoPrjId, filters, function (err, msg, rawDataObj) {
            if (!err) {
                try {
                    //1. 这里只用一份数据，根据实际应用情况，只需要保留copy三样数据： bills, ration, ration_glj, projectGLJ
                    fsUtil.writeObjToFile(rawDataObj, "D:/GitHome/YangHuCost/tmp/报表优化测试_原始数据.jsp");
                    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;
                        let defProperties = rpt_cfg;
                        let dftOption = JV.PAGING_OPTION_NORMAL;
                        printCom.initialize(rptTpl);
                        printCom.analyzeData(rptTpl, tplData, defProperties, dftOption, JV.OUTPUT_TYPE_EXCEL);
                        let maxPages = printCom.totalPages;
                        let customizeCfg = {"fillZero": true};
                        let pageRst = printCom.outputAsSimpleJSONPageArray(rptTpl, tplData, 1, maxPages, defProperties, customizeCfg);
                        if (pageRst) {
                            fsUtil.writeObjToFile(pageRst, "D:/GitHome/YangHuCost/tmp/testBuiltPageResult_测试模板_" + tplIdx + ".jsp");
                            // rpt_xl_util.exportExcel(pageRst, pagesize, "local_test_rpt_excel", true, null, null, function(uuidName){
                            //     console.log("excel uuid: " + uuidName);
                            // });
                            // rpt_pdf_util.export_pdf_file(pageRst, pagesize, 'local_test_rpt_pdf', function(uuidName){
                            //     console.log("pdf uuid: " + uuidName);
                            // });
                        } else {
                            console.log("oh! no pages were created!");
                        }
                        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);
                            }
                        }
                    }
                    //let tplData = rptDataUtil.assembleData(rawDataObj);
                } catch (ex) {
                    console.log(ex);
                    t.pass('pass with exception!');
                    t.end();
                } finally {
                    t.pass('pass succeeded!');
                    // t.end();
                    mongoose.disconnect();
                    t.pass('closing db connection');
                    t.end();
                }
            } else {
                console.log(msg);
                t.pass('pass with error!');
                t.end();
            }
        })
    });
});

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