let JV = require('./jpc_value_define');
let JE = require('./jpc_rte');
let JpcFieldHelper = require('./helper/jpc_helper_field');
let JpcBandHelper = require('./helper/jpc_helper_band');
let JpcBand = require('./jpc_band');
let JpcFlowTabHelper = require('./helper/jpc_helper_flow_tab');
let JpcCommonHelper = require('./helper/jpc_helper_common');
let JpcDiscreteHelper = require('./helper/jpc_helper_discrete');
let JpcTextHelper = require('./helper/jpc_helper_text');
let JpcCommonOutputHelper = require('./helper/jpc_helper_common_output');
let JpcAreaHelper = require('./helper/jpc_helper_area');

let JpcFlowTabSrv = function(){};
JpcFlowTabSrv.prototype.createNew = function(){
    function private_addPageValue(ValuedIdxLst, sortedSequence, preRec, nextRec,page_seg_map, segIdx, pageIdx) {
        let vIdx = [];
        for (let vi = 0; vi < nextRec; vi++) {
            if (sortedSequence.length > preRec + vi) {
                vIdx.push(sortedSequence[preRec + vi]);
            } else {
                vIdx.push(JV.BLANK_VALUE_INDEX);
            }
        }
        page_seg_map.push([pageIdx, segIdx]);
        ValuedIdxLst.push(vIdx);
    }
    let JpcFlowTabResult = {};
    JpcFlowTabResult.initialize = function(isEx) {
        let me = this;
        me.isEx = isEx;
        me.paging_option = JV.PAGING_OPTION_NORMAL;
        me.segments = [];
        me.dispValueIdxLst = [];
        me.page_seg_map = [];
        me.disp_fields_idx = [];
        me.seg_sum_fields_idx = [];
        me.seg_sum_tab_fields = [];
        me.page_sum_fields_idx = [];
        me.group_fields_idx = [];
        me.pageStatusLst = [];
        me.groupSumValLst = [];
        me.segSumValLst = [];
        me.multiCols = 1;
        me.pagesAmt = 0;
    };
    JpcFlowTabResult.sorting = function(rptTpl, dataObj, dataSeq) {
        let me = this;
        let FLOW_NODE_STR = me.isEx?JV.NODE_FLOW_INFO_EX:JV.NODE_FLOW_INFO;
        JpcFieldHelper.findAndPutDataFieldIdx(rptTpl, rptTpl[FLOW_NODE_STR][JV.NODE_FLOW_SEG_SUM][JV.PROP_SUM_FIELDS], me.seg_sum_tab_fields, me.seg_sum_fields_idx, me.isEx);
        JpcFieldHelper.findAndPutDataFieldIdx(rptTpl, rptTpl[FLOW_NODE_STR][JV.NODE_FLOW_PAGE_SUM][JV.PROP_SUM_FIELDS], null, me.page_sum_fields_idx, me.isEx);
        JpcFieldHelper.findAndPutDataFieldIdx(rptTpl, rptTpl[FLOW_NODE_STR][JV.NODE_FLOW_GROUP][JV.PROP_GROUP_FIELDS], null, me.group_fields_idx, me.isEx);
        for (let si = 0; si < dataSeq.length; si++) {
            me.segments.push(dataSeq[si].slice(0));
        }
        //pre-sum the data(for seg sum display)
        let data_details = me.isEx?dataObj[JV.DATA_DETAIL_DATA_EX]:dataObj[JV.DATA_DETAIL_DATA],
            data_fields = [];
        for (let i = 0; i < me.seg_sum_fields_idx.length; i++) {
            let data_field = data_details[me.seg_sum_fields_idx[i]];
            data_fields.push(data_field);
        }
        for (let i = 0; i < me.segments.length; i++) { //seg level
            if (me.segments[i].length > 0) {
                let rowGrandTotal = [];
                for (let di = 0; di < data_fields.length; di++) {
                    rowGrandTotal.push(0.0);
                    for (let j = 0; j < me.segments[i].length; j++) {
                        //3. start to sum
                        rowGrandTotal[di] = rowGrandTotal[di] + 1.0 * JpcFieldHelper.getValue(data_fields[di], me.segments[i][j]);
                    }
                }
                me.segSumValLst.push(rowGrandTotal);
            }

        }
    };
    JpcFlowTabResult.preSetupPages = function (rptTpl, dataOjb, defProperties, option) {
        let me = this, rst = 1, counterRowRec = 0, maxRowRec = 1, pageIdx = 0;
        me.paging_option = option||JV.PAGING_OPTION_NORMAL;
        let CURRENT_FLOW_INFO = (me.isEx)?JV.NODE_FLOW_INFO_EX:JV.NODE_FLOW_INFO;
        JpcFieldHelper.findAndPutDataFieldIdx(rptTpl, rptTpl[CURRENT_FLOW_INFO][JV.NODE_FLOW_CONTENT][JV.PROP_FLOW_FIELDS], null, me.disp_fields_idx, me.isEx);
        if (me.paging_option === JV.PAGING_OPTION_INFINITY) {
            rst = me.segments.length;
            let pageStatus = [true, true, false, true, true, true, false, false];
            for (let segIdx = 0; segIdx < me.segments.length; segIdx++) {
                if (segIdx === me.segments.length - 1) {
                    pageStatus[JV.STATUS_REPORT_END] = true;
                }
                if (segIdx > 0) {
                    pageStatus[JV.STATUS_REPORT_START] = false;
                }
                me.pageStatusLst.push(pageStatus.slice(0));
                pageIdx++;
                private_addPageValue(me.dispValueIdxLst, me.segments[segIdx], 0, me.segments[segIdx].length, me.page_seg_map, segIdx, pageIdx);
            }
        } else {
            let bands = JpcBand.createNew(rptTpl, defProperties);
            let pageStatus = [true, true, false, true, false, false, false, false];
            if (me.isEx) {
                pageStatus[JV.STATUS_REPORT_START] = false;
            }
            if (rptTpl[CURRENT_FLOW_INFO][JV.PROP_MULTI_COLUMN]) {
                me.multiCols = 1 * rptTpl[CURRENT_FLOW_INFO][JV.PROP_MULTI_COLUMN];
            }
            function private_resetBandArea() {
                JpcBandHelper.setBandArea(bands, rptTpl, pageStatus, !me.isEx, me.isEx);
                maxRowRec = JpcFlowTabHelper.getMaxRowsPerPage(bands, rptTpl);
            }
            for (let segIdx = 0; segIdx < me.segments.length; segIdx++) {
                private_resetBandArea();
                let orgMaxRowRec = maxRowRec;
                let rowSplitCnt = Math.ceil(1.0 * me.segments[segIdx].length / orgMaxRowRec);
                pageStatus[JV.STATUS_SEGMENT_END] = true;
                private_resetBandArea();
                let hasAdHocRow = !JpcFlowTabHelper.chkSegEnd(bands, rptTpl, me.segments, segIdx, (rowSplitCnt - 1) * orgMaxRowRec, maxRowRec);
                if (hasAdHocRow) rowSplitCnt++;
                if (rowSplitCnt % me.multiCols > 0) {
                    rowSplitCnt++
                }
                for (let rowIdx = 0; rowIdx < rowSplitCnt; rowIdx++) {
                    pageStatus[JV.STATUS_SEGMENT_END] = (rowIdx === (rowSplitCnt - 1));
                    if (pageIdx > 0) pageStatus[JV.STATUS_REPORT_START] = false;
                    private_resetBandArea();
                    me.pageStatusLst.push(pageStatus.slice(0));
                    pageIdx++;
                    counterRowRec = orgMaxRowRec * rowIdx;
                    private_addPageValue(me.dispValueIdxLst, me.segments[segIdx], counterRowRec, maxRowRec,me.page_seg_map, segIdx, pageIdx);
                }
                pageStatus[JV.STATUS_SEGMENT_END] = false;
                pageStatus[JV.STATUS_REPORT_START] = false;
            }
            rst = Math.ceil(pageIdx / me.multiCols);
        }
        me.pagesAmt = rst;
        return rst;
    };
    JpcFlowTabResult.outputAsSimpleJSONPage = function (rptTpl, dataObj, page, bands, controls, adHocMergePos, $CURRENT_RPT) {
        let me = this, rst = [], tabRstLst = [];
        let FLOW_NODE_STR = me.isEx?JV.NODE_FLOW_INFO_EX:JV.NODE_FLOW_INFO;
        let unitFactor = JpcCommonHelper.getUnitFactor(rptTpl);
        if (me.paging_option === JV.PAGING_OPTION_INFINITY) {
            let segIdx = page - 1;
            //1 calculate the band position
            JpcBandHelper.setBandArea(bands, rptTpl, me.pageStatusLst[page - 1], !me.isEx, me.isEx);
            //2. then reset the band height
            let tab = rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_CONTENT];
            let flowContentBand = bands[tab[JV.PROP_BAND_NAME]];
            let actH = JpcFlowTabHelper.getActualContentAreaHeight(bands, rptTpl, me.segments, page);
            let offsetY = actH - (flowContentBand.Bottom - flowContentBand.Top);
            JpcBandHelper.resetBandPos(rptTpl[JV.NODE_BAND_COLLECTION], bands, flowContentBand, 0, offsetY);

            tabRstLst.push(me.outputContent(rptTpl, dataObj, page, bands, unitFactor, controls, 0, $CURRENT_RPT));
            // 2.2 Column tab
            tabRstLst.push(me.outputColumn(rptTpl, dataObj, page, segIdx, bands, unitFactor, controls, 0));
            // 2.3 Sum Seg
            tabRstLst.push(me.outputSegSum(rptTpl, dataObj, page, segIdx, bands, unitFactor, controls));
            // 2.4 Sum Page
            // 2.5 Discrete
            tabRstLst.push(JpcDiscreteHelper.outputDiscreteInfo(rptTpl[FLOW_NODE_STR][JV.NODE_DISCRETE_INFO], bands, dataObj, unitFactor, me.pageStatusLst[page - 1], segIdx, 1, 0, $CURRENT_RPT));
            //3. reset merge band position
            if (bands[JV.BAND_PROP_MERGE_BAND] && adHocMergePos) {
                let mergedBand = bands[JV.BAND_PROP_MERGE_BAND];
                let arr = [];
                arr.push(parseInt(mergedBand[JV.PROP_LEFT].toFixed(0)));
                adHocMergePos[JV.PROP_LEFT] = arr;
                arr = [];
                arr.push(parseInt(mergedBand[JV.PROP_RIGHT].toFixed(0)));
                adHocMergePos[JV.PROP_RIGHT] = arr;
                arr = [];
                arr.push(parseInt(mergedBand[JV.PROP_TOP].toFixed(0)));
                adHocMergePos[JV.PROP_TOP] = arr;
                arr = [];
                arr.push(parseInt((mergedBand[JV.PROP_BOTTOM]).toFixed(0)));
                adHocMergePos[JV.PROP_BOTTOM] = arr;
            }
        } else {
            let segIdx = JpcCommonHelper.getSegIdxByPageIdx(page, me.page_seg_map);
            //1 calculate the band position
            JpcBandHelper.setBandArea(bands, rptTpl, me.pageStatusLst[page - 1], !me.isEx, me.isEx);
            //2. start to output detail-part
            for (let pi = 0; pi < me.multiCols; pi++) {
                let actualPage = (page - 1) * me.multiCols + pi + 1;
                //2.1 Content-Tab
                tabRstLst.push(me.outputContent(rptTpl, dataObj, actualPage, bands, unitFactor, controls, pi, $CURRENT_RPT));
                //2.2 Column tab
                tabRstLst.push(me.outputColumn(rptTpl, dataObj, actualPage, segIdx, bands, unitFactor, controls, pi));
                //2.3 Sum Seg
                tabRstLst.push(me.outputSegSum(rptTpl, dataObj, actualPage, segIdx, bands, unitFactor, controls));
                //2.4 Sum Page
                //2.5 Discrete
                if (pi === 0) {
                    tabRstLst.push(JpcDiscreteHelper.outputDiscreteInfo(rptTpl[FLOW_NODE_STR][JV.NODE_DISCRETE_INFO], bands, dataObj, unitFactor, me.pageStatusLst[actualPage - 1], segIdx, 1, pi, $CURRENT_RPT));
                }
            }
        }
        for (let i = 0; i < tabRstLst.length; i++) {
            rst = rst.concat(tabRstLst[i]);
            tabRstLst[i] = null;
        }
        return rst;
    };
    JpcFlowTabResult.outputContent = function(rptTpl, dataObj, page, bands, unitFactor, controls, multiColIdx, $CURRENT_RPT) {
        let me = this, rst = [];
        let FLOW_NODE_STR = me.isEx?JV.NODE_FLOW_INFO_EX:JV.NODE_FLOW_INFO;
        let tab = rptTpl[FLOW_NODE_STR][JV.NODE_FLOW_CONTENT];
        let band = bands[tab[JV.PROP_BAND_NAME]];
        if (band) {
            let pageStatus = me.pageStatusLst[page - 1];
            if (pageStatus[band[JV.BAND_PROP_DISPLAY_TYPE]]) {
                let tab_fields = tab[JV.PROP_FLOW_FIELDS];
                let data_details = me.isEx?dataObj[JV.DATA_DETAIL_DATA_EX]:dataObj[JV.DATA_DETAIL_DATA];
                let contentValuesIdx = me.dispValueIdxLst[page - 1];
                for (let i = 0; i < tab_fields.length; i++) {
                    let tab_field = tab_fields[i];
                    let data_field = null;
                    if (me.disp_fields_idx[i] !== JV.BLANK_FIELD_INDEX) {
                        data_field = data_details[me.disp_fields_idx[i]];
                    } else {
                        data_field = JE.F(tab_field[JV.PROP_FIELD_ID], $CURRENT_RPT);
                        if (data_field) {
                            data_field = data_field[JV.PROP_AD_HOC_DATA];
                        }
                    }
                    if (!(tab_field[JV.PROP_HIDDEN])) {
                        for (let rowIdx = 0; rowIdx < contentValuesIdx.length; rowIdx++) {
                            rst.push(me.outputTabField(band, tab_field, data_field, contentValuesIdx[rowIdx], -1, contentValuesIdx.length, rowIdx, 1, 0, unitFactor, true, controls, multiColIdx));
                        }
                    }
                }
            }
        }
        return rst;
    };
    JpcFlowTabResult.outputColumn = function (rptTpl, dataObj, page, segIdx, bands, unitFactor, controls, multiColIdx) {
        let me = this, rst = [];
        let FLOW_NODE_STR = me.isEx?JV.NODE_FLOW_INFO_EX:JV.NODE_FLOW_INFO;
        let tab = rptTpl[FLOW_NODE_STR][JV.NODE_FLOW_COLUMN];
        let band = bands[tab[JV.PROP_BAND_NAME]];
        if (band) {
            let pageStatus = me.pageStatusLst[page - 1];
            if (pageStatus[band[JV.BAND_PROP_DISPLAY_TYPE]]) {
                if (tab[JV.PROP_TEXT]) {
                    rst.push(JpcTextHelper.outputText(tab[JV.PROP_TEXT], band, unitFactor, 1, 0, 1, 0, me.multiCols, multiColIdx));
                }
                if (tab[JV.PROP_TEXTS]) {
                    for (let j = 0; j < tab[JV.PROP_TEXTS].length; j++) {
                        rst.push(JpcTextHelper.outputText(tab[JV.PROP_TEXTS][j], band, unitFactor, 1, 0, 1, 0, me.multiCols, multiColIdx));
                    }
                }
                if (tab[JV.NODE_DISCRETE_INFO]) {
                    rst = rst.concat(JpcDiscreteHelper.outputDiscreteInfo(tab[JV.NODE_DISCRETE_INFO], bands, dataObj, unitFactor, me.pageStatusLst[page - 1], segIdx, me.multiCols, multiColIdx));
                }
            }
        }
        return rst;
    };
    JpcFlowTabResult.outputSegSum = function (rptTpl, dataObj, page, segIdx, bands, unitFactor, controls) {
        let me = this, rst = [];
        let FLOW_NODE_STR = me.isEx?JV.NODE_FLOW_INFO_EX:JV.NODE_FLOW_INFO;
        let tab = rptTpl[FLOW_NODE_STR][JV.NODE_FLOW_SEG_SUM];
        let band = bands[tab[JV.PROP_BAND_NAME]];
        if (band) {
            let pageStatus = me.pageStatusLst[page - 1];
            if (pageStatus[band[JV.BAND_PROP_DISPLAY_TYPE]]) {
                let tab_fields = me.seg_sum_tab_fields;
                for (let i = 0; i < tab_fields.length; i++) {
                    let cellItem = JpcCommonOutputHelper.createCommonOutput(tab_fields[i], me.segSumValLst[segIdx][i], controls);
                    cellItem[JV.PROP_AREA] = JpcAreaHelper.outputArea(tab_fields[i][JV.PROP_AREA], band, unitFactor, 1, 0, 1, 0, me.multiCols, 0, true, false);
                    rst.push(cellItem);
                }
                if (tab[JV.PROP_TEXT]) {
                    rst.push(JpcTextHelper.outputText(tab[JV.PROP_TEXT], band, unitFactor, 1, 0, 1, 0, me.multiCols, 0));
                }
                if (tab[JV.PROP_TEXTS]) {
                    for (let j = 0; j < tab[JV.PROP_TEXTS].length; j++) {
                        rst.push(JpcTextHelper.outputText(tab[JV.PROP_TEXTS][j], band, unitFactor, 1, 0, 1, 0, me.multiCols, 0));
                    }
                }
                if (tab[JV.NODE_DISCRETE_INFO]) {
                    rst = rst.concat(JpcDiscreteHelper.outputDiscreteInfo(tab[JV.NODE_DISCRETE_INFO], bands, dataObj, unitFactor, me.pageStatusLst[page - 1], segIdx, me.multiCols, 0));
                }
            }
        }
        return rst;
    };
    JpcFlowTabResult.outputTabField = function (band, tab_field, data_field, valueIdx, serialIdx, rows, rowIdx, cols, colIdx, unitFactor, isRow, controls, multiColIdx) {
        let me = this,
            rst = JpcCommonOutputHelper.createCommonOutput(tab_field, JpcFieldHelper.getValue(data_field, valueIdx), controls);
        rst[JV.PROP_AREA] = JpcAreaHelper.outputArea(tab_field[JV.PROP_AREA], band, unitFactor, rows, rowIdx, cols, colIdx, me.multiCols, multiColIdx, true, false);
        return rst;
    };

    return JpcFlowTabResult;
};

module.exports = new JpcFlowTabSrv();
