'use strict';

import { JV } from './jpc_value_define';
import { JE } from './jpc_rte';
import { JpcFieldHelper } from './helper/jpc_helper_field';
import { JpcBandHelper } from './helper/jpc_helper_band';
import { JpcBand } from './jpc_band';
import { JpcCrossTabHelper } from './helper/jpc_helper_cross_tab';
import { JpcCommonHelper } from './helper/jpc_helper_common';
import { JpcDiscreteHelper } from './helper/jpc_helper_discrete';
import JpcTextHelper from './helper/jpc_helper_text';
import { JpcCommonOutputHelper } from './helper/jpc_helper_common_output';
import { JpcAreaHelper } from './helper/jpc_helper_area';
import {
    Fields,
    IDefProperties,
    ICurrent_RPT,
    ICustomizeCfg,
    IBands,
    IBandDetail,
    IControlCollection,
    IRptTpl,
    IDataObj,
    ICrossTab,
    IGroupField
} from '../interface/basic';
import { IDataObjProps, IPositionProps } from '../interface/enum'
export class JpcCrossTabClass {
    dispValueIdxLst_Row: number[][];
    dispValueIdxLst_Col: any[];
    dispValueIdxLst_Content: number[][][];
    dispSerialIdxLst_Row: number[][];
    col_sum_fields_idx: any[];
    col_sum_fields_value_total: any[][];
    dispSumValueLst_Col: any[];
    page_seg_map: any;
    row_fields_idx: any[];
    row_fields_adhoc_idx: any[];
    col_fields_idx: any[];
    content_fields_idx: any[];
    row_extension_fields_idx: any[];
    row_sum_extension_fields_idx: any[];
    sortedRowSequence: any[];
    sortedColSequence: any[];
    sortedContentSequence: any[];
    crsOrient: number;
    pageStatusLst: any[];
    paging_option: string;

    constructor() {
        this.dispValueIdxLst_Row = [];
        this.dispValueIdxLst_Col = [];
        this.dispValueIdxLst_Content = [];
        this.dispSerialIdxLst_Row = [];
        this.col_sum_fields_idx = [];
        this.col_sum_fields_value_total = [];
        this.dispSumValueLst_Col = [];
        this.page_seg_map = [];
        this.row_fields_idx = [];
        this.row_fields_adhoc_idx = [];
        this.col_fields_idx = [];
        this.content_fields_idx = [];
        this.row_extension_fields_idx = [];
        this.row_sum_extension_fields_idx = [];
        this.sortedRowSequence = [];
        this.sortedColSequence = [];
        this.sortedContentSequence = [];
        this.crsOrient = JV.PAGE_ORIENTATION_V_FIRST;
        this.pageStatusLst = [];
        this.paging_option = JV.PAGING_OPTION_NORMAL;
    };
    sorting(rptTpl: IRptTpl, dataObj: IDataObj, dataSeq: number[][], $CURRENT_RPT: ICurrent_RPT) {
        let me = this;
        //IMPORTANT: the data should be sorted in SQL/NoSQL level!
        me.sortedRowSequence = _SortAndOptimize(rptTpl, dataObj, dataSeq, JV.NODE_CROSS_ROW, me.row_fields_idx, $CURRENT_RPT);
        _SortAndOptimize(rptTpl, dataObj, dataSeq, JV.NODE_CROSS_ROW_AD_HOC, me.row_fields_adhoc_idx, $CURRENT_RPT);
        me.sortedColSequence = _SortAndOptimize(rptTpl, dataObj, dataSeq, JV.NODE_CROSS_COL, me.col_fields_idx, $CURRENT_RPT);
        me.sortedContentSequence = _SortForDisplayContent(rptTpl, me.sortedRowSequence, me.sortedColSequence, me.content_fields_idx);
        JpcFieldHelper.findAndPutDataFieldIdx(rptTpl, rptTpl.交叉表_信息.交叉列合计.cross_field_s, null, me.col_sum_fields_idx, false);
        //pre-sum the data(for col sum display)
        let data_details = dataObj.detail_data,
            data_fields = [];
        for (let i = 0; i < me.col_sum_fields_idx.length; i++) {
            let data_field = null;
            if (typeof me.col_sum_fields_idx[i] === 'object') {
                let exField = JE.F(me.col_sum_fields_idx[i].ID, $CURRENT_RPT);
                if (exField) {
                    data_field = exField.data_field;
                }
            } else {
                data_field = data_details[me.col_sum_fields_idx[i]];
            }
            data_fields.push(data_field);
        }
        for (let i = 0; i < me.sortedRowSequence.length; i++) { //seg level
            if (me.sortedRowSequence[i].length > 0) {
                me.col_sum_fields_value_total.push([]);
                for (let j = 0; j < me.sortedRowSequence[i].length; j++) {
                    let rowGrandTotal = [];
                    for (let di = 0; di < data_fields.length; di++) {
                        rowGrandTotal.push(0.0);
                        for (let k = 0; k < me.sortedRowSequence[i][j].length; k++) {
                            // 3. start to sum
                            let vTtl = parseFloat(JpcFieldHelper.getValue(data_fields[di], me.sortedRowSequence[i][j][k]));
                            if (isNaN(vTtl)) {
                                vTtl = 0;
                            }
                            rowGrandTotal[di] = rowGrandTotal[di] + vTtl;
                        }
                    }
                    me.col_sum_fields_value_total[i].push(rowGrandTotal);
                }
            }

        }
    };
    preSetupPages(rptTpl: IRptTpl, defProperties: IDefProperties, option: string) {
        let me = this, rst = 0;
        me.paging_option = option || JV.PAGING_OPTION_NORMAL;
        //1. original initialize
        let maxRowRec = 1, maxColRec = 1, counterRowRec = 0, counterColRec = 0, pageIdx = 0, segCnt = me.sortedContentSequence.length;
        let pageStatus: boolean[] = [true, true, false, true, false, false, false, false];
        //2. calculate the page info one by one
        let bands = JpcBand.createNew(rptTpl, defProperties);
        function private_resetBandArea() {
            JpcBandHelper.setBandArea(bands, rptTpl, pageStatus, false, false);
            maxRowRec = JpcCrossTabHelper.getMaxRowsPerPage(bands, rptTpl);
            maxColRec = JpcCrossTabHelper.getMaxColsPerPage(bands, rptTpl);
        }
        JpcFieldHelper.findAndPutDataFieldIdx(rptTpl, rptTpl.交叉表_信息.交叉行拓展.cross_field_s, null, me.row_extension_fields_idx, false);
        JpcFieldHelper.findAndPutDataFieldIdx(rptTpl, rptTpl.交叉表_信息.交叉行拓展合计.cross_field_s, null, me.row_sum_extension_fields_idx, false);
        if (me.paging_option === JV.PAGING_OPTION_INFINITY) {
            // 交叉表暂时不支持无限拓展
        } else {
            for (let segIdx = 0; segIdx < segCnt; segIdx++) {
                //2.1. seg level initialize
                private_resetBandArea();
                let orgMaxRowRec = maxRowRec, orgMaxColRec = maxColRec;
                let rowSplitCnt = Math.ceil(1.0 * me.sortedRowSequence[segIdx].length / maxRowRec);
                let colSplitCnt = Math.ceil(1.0 * me.sortedColSequence[segIdx].length / maxColRec);
                pageStatus[JV.STATUS_CROSS_ROW_END] = true;
                private_resetBandArea();
                let hasAdHocRow = !JpcCrossTabHelper.chkTabEnd(JV.NODE_CROSS_ROW_SUM, rptTpl, bands, me.sortedRowSequence, segIdx, (rowSplitCnt - 1) * orgMaxRowRec, maxRowRec);
                if (hasAdHocRow) {
                    hasAdHocRow = !JpcCrossTabHelper.chkTabEnd(JV.NODE_CROSS_ROW_EXT, rptTpl, bands, me.sortedRowSequence, segIdx, (rowSplitCnt - 1) * orgMaxRowRec, maxRowRec);
                }
                pageStatus[JV.STATUS_CROSS_ROW_END] = false;
                pageStatus[JV.STATUS_CROSS_COL_END] = true;
                private_resetBandArea();
                let hasAdHocCol = !JpcCrossTabHelper.chkTabEnd(JV.NODE_CROSS_COL_SUM, rptTpl, bands, me.sortedColSequence, segIdx, (colSplitCnt - 1) * orgMaxColRec, maxColRec);
                pageStatus[JV.STATUS_CROSS_COL_END] = false;
                private_resetBandArea();
                if (hasAdHocRow) rowSplitCnt++;
                if (hasAdHocCol) colSplitCnt++;
                //2.2
                if (rptTpl.主信息.打印页面_信息.cross_display_order === JV.PAGE_ORIENTATION_H_FIRST) {
                    for (let rowIdx = 0; rowIdx < rowSplitCnt; rowIdx++) {
                        pageStatus[JV.STATUS_CROSS_ROW_END] = (rowIdx === (rowSplitCnt - 1));
                        private_resetBandArea();
                        counterRowRec = orgMaxRowRec * rowIdx;
                        let currentSortedRowSequence: any = me.sortedRowSequence;
                        let currentSortedContentSequence: any = me.sortedContentSequence;
                        if (hasAdHocRow && rowIdx === (rowSplitCnt - 1)) {
                            currentSortedRowSequence = null;
                            currentSortedContentSequence = null;
                            counterRowRec = 0;
                        }
                        for (let colIdx = 0; colIdx < colSplitCnt; colIdx++) {
                            pageStatus[JV.STATUS_CROSS_COL_END] = (colIdx === (colSplitCnt - 1));
                            private_resetBandArea();
                            counterColRec = orgMaxColRec * colIdx;
                            let currentSortedColSequence: any = me.sortedColSequence;
                            if (hasAdHocCol && colIdx === (colSplitCnt - 1)) {
                                currentSortedColSequence = null;
                                currentSortedContentSequence = null;
                                counterColRec = 0;
                            }
                            me.pageStatusLst.push(pageStatus.slice(0));
                            pageIdx++;
                            _addTabValue(me.dispValueIdxLst_Row, currentSortedRowSequence, segIdx, counterRowRec, maxRowRec, me.dispSerialIdxLst_Row, me.col_sum_fields_value_total, me.dispSumValueLst_Col);
                            _addTabValue(me.dispValueIdxLst_Col, currentSortedColSequence, segIdx, counterColRec, maxColRec, null, null, null);
                            _addContentValue(me.dispValueIdxLst_Content, currentSortedContentSequence, segIdx, counterRowRec, maxRowRec, counterColRec, maxColRec, me.page_seg_map, pageIdx);
                        }
                    }
                } else {
                    for (let colIdx = 0; colIdx < colSplitCnt; colIdx++) {
                        pageStatus[JV.STATUS_CROSS_COL_END] = (colIdx === (colSplitCnt - 1));
                        private_resetBandArea();
                        counterColRec = orgMaxColRec * colIdx;
                        let currentSortedContentSequence: any = me.sortedContentSequence;
                        let currentSortedColSequence: any = me.sortedColSequence;
                        if (hasAdHocCol && colIdx === (colSplitCnt - 1)) {
                            currentSortedColSequence = null;
                            currentSortedContentSequence = null;
                            counterColRec = 0;
                        }
                        for (let rowIdx = 0; rowIdx < rowSplitCnt; rowIdx++) {
                            pageStatus[JV.STATUS_CROSS_ROW_END] = (rowIdx === (rowSplitCnt - 1));
                            private_resetBandArea();
                            me.pageStatusLst.push(pageStatus.slice(0));
                            pageIdx++;
                            counterRowRec = orgMaxRowRec * rowIdx;
                            let currentSortedRowSequence: any = me.sortedRowSequence;
                            if (hasAdHocRow && rowIdx === (rowSplitCnt - 1)) {
                                currentSortedRowSequence = null;
                                currentSortedContentSequence = null;
                                counterRowRec = 0;
                            }
                            _addTabValue(me.dispValueIdxLst_Row, currentSortedRowSequence, segIdx, counterRowRec, maxRowRec, me.dispSerialIdxLst_Row, me.col_sum_fields_value_total, me.dispSumValueLst_Col);
                            _addTabValue(me.dispValueIdxLst_Col, currentSortedColSequence, segIdx, counterColRec, maxColRec, null, null, null);
                            _addContentValue(me.dispValueIdxLst_Content, currentSortedContentSequence, segIdx, counterRowRec, maxRowRec, counterColRec, maxColRec, me.page_seg_map, pageIdx);
                        }
                    }
                }
                JpcCrossTabHelper.initialPageStatus(pageStatus);
            }
            //3. set pageSeq and return the result
            rst = pageIdx;
        }
        // bands = null;
        return rst;
    };
    outputAsPreviewPage(rptTpl: IRptTpl, bands: IBands, controls: IControlCollection, $CURRENT_RPT: ICurrent_RPT, customizeCfg: ICustomizeCfg) {
        let me = this, rst: any[] = [];
        let pageStatus: boolean[] = [true, true, true, true, true, true, true, true];
        me.pageStatusLst.push(pageStatus);
        // JpcFieldHelper.findAndPutDataFieldIdx(rptTpl, rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_CONTENT][JV.PROP_FLOW_FIELDS], null, me.disp_fields_idx, false);
        JpcBandHelper.setBandArea(bands, rptTpl, pageStatus, true, false);
        let maxRowRec = JpcCrossTabHelper.getMaxRowsPerPage(bands, rptTpl);
        let maxColRec = JpcCrossTabHelper.getMaxColsPerPage(bands, rptTpl);
        let unitFactor = JpcCommonHelper.getUnitFactor(rptTpl);
        //1. 交叉行
        rst = rst.concat(me.outputPreviewRowTab(rptTpl, bands, controls, $CURRENT_RPT, customizeCfg, maxRowRec, unitFactor));
        //2. 交叉列
        rst = rst.concat(me.outputPreviewColTab(rptTpl, bands, controls, $CURRENT_RPT, customizeCfg, maxColRec, unitFactor));
        //3. 交叉数据
        rst = rst.concat(me.outputPreviewContent(rptTpl, bands, controls, $CURRENT_RPT, customizeCfg, maxRowRec, maxColRec, unitFactor));
        //4. 交叉行拓展
        rst = rst.concat(me.outputPreviewTabExt(rptTpl, bands, controls, $CURRENT_RPT, customizeCfg, maxColRec, unitFactor));
        //5. 交叉行拓展合计
        rst = rst.concat(me.outputPreviewSumTabExt(rptTpl, bands, controls, $CURRENT_RPT, customizeCfg, unitFactor));
        //6. 交叉列合计
        rst = rst.concat(me.outputPreviewTabSum(rptTpl, bands, controls, $CURRENT_RPT, customizeCfg, maxRowRec, '交叉列合计', unitFactor));
        //7. 离散
        rst = rst.concat(JpcDiscreteHelper.outputPreviewDiscreteInfo(rptTpl.交叉表_信息.离散信息, bands, unitFactor, pageStatus));
        return rst;
    };
    outputPreviewContent(rptTpl: IRptTpl, bands: IBands, controls: IControlCollection, $CURRENT_RPT: ICurrent_RPT, customizeCfg: ICustomizeCfg, maxRowRec: number, maxColRec: number, unitFactor: number) {
        return this.private_OutputPreviewCommon(rptTpl, bands, controls, $CURRENT_RPT, customizeCfg, maxRowRec, maxColRec, rptTpl.交叉表_信息.交叉数据, unitFactor);
    };
    outputPreviewRowTab(rptTpl: IRptTpl, bands: IBands, controls: IControlCollection, $CURRENT_RPT: ICurrent_RPT, customizeCfg: ICustomizeCfg, maxRowRec: number, unitFactor: number) {
        let rst = this.private_OutputPreviewCommon(rptTpl, bands, controls, $CURRENT_RPT, customizeCfg, maxRowRec, 1, rptTpl.交叉表_信息.交叉行, unitFactor);
        rst = rst.concat(this.private_OutputPreviewCommon(rptTpl, bands, controls, $CURRENT_RPT, customizeCfg, maxRowRec, 1, rptTpl.交叉表_信息.交叉行AD_HOC, unitFactor));
        return rst;
    };
    outputPreviewColTab(rptTpl: IRptTpl, bands: IBands, controls: IControlCollection, $CURRENT_RPT: ICurrent_RPT, customizeCfg: ICustomizeCfg, maxColRec: number, unitFactor: number) {
        return this.private_OutputPreviewCommon(rptTpl, bands, controls, $CURRENT_RPT, customizeCfg, 1, maxColRec, rptTpl.交叉表_信息.交叉列, unitFactor);
    };
    outputPreviewTabExt(rptTpl: IRptTpl, bands: IBands, controls: IControlCollection, $CURRENT_RPT: ICurrent_RPT, customizeCfg: ICustomizeCfg, maxColRec: number, unitFactor: number) {
        //交叉行拓展
        return this.private_OutputPreviewCommon(rptTpl, bands, controls, $CURRENT_RPT, customizeCfg, 1, maxColRec, rptTpl.交叉表_信息.交叉行拓展, unitFactor);
    };
    outputPreviewSumTabExt(rptTpl: IRptTpl, bands: IBands, controls: IControlCollection, $CURRENT_RPT: ICurrent_RPT, customizeCfg: ICustomizeCfg, unitFactor: number) {
        //交叉行拓展合计
        return this.private_OutputPreviewCommon(rptTpl, bands, controls, $CURRENT_RPT, customizeCfg, 1, 1, rptTpl.交叉表_信息.交叉行拓展合计, unitFactor);
    };
    outputPreviewTabSum(rptTpl: IRptTpl, bands: IBands, controls: IControlCollection, $CURRENT_RPT: ICurrent_RPT, customizeCfg: ICustomizeCfg, maxRowRec: number, tabNodeName: string, unitFactor: number) {
        return this.private_OutputPreviewCommon(rptTpl, bands, controls, $CURRENT_RPT, customizeCfg, maxRowRec, 1, rptTpl.交叉表_信息[tabNodeName], unitFactor);
    };
    private_OutputPreviewCommon(rptTpl: IRptTpl, bands: IBands, controls: IControlCollection, $CURRENT_RPT: ICurrent_RPT, customizeCfg: ICustomizeCfg, maxRowRec: number, maxColRec: number, tab: ICrossTab, unitFactor: number) {
        let me = this, rst = [];
        let band = (tab) ? bands[tab.BandName] : null;
        if (band) {
            let tab_fields = tab.cross_field_s;
            for (let rowIdx = 0; rowIdx < maxRowRec; rowIdx++) {
                for (let i = 0; i < tab_fields.length; i++) {
                    let tab_field = tab_fields[i];
                    if (!(tab_field.Hidden)) {
                        for (let colIdx = 0; colIdx < maxColRec; colIdx++) {
                            if (tab_field.isSerial) {
                                rst.push(me.outputTabField(band, tab_field, [rowIdx + 1], 0, -1, maxRowRec, rowIdx, maxColRec, colIdx, unitFactor, false, controls));
                            } else {
                                rst.push(me.outputTabField(band, tab_field, null, -1, -1, maxRowRec, rowIdx, maxColRec, colIdx, unitFactor, false, controls));
                            }
                        }
                    }
                }
                if (tab.text_s) {
                    for (let j = 0; j < tab.text_s.length; j++) {
                        for (let colIdx = 0; colIdx < maxColRec; colIdx++) {
                            rst.push(JpcTextHelper.outputText(tab.text_s[j], band, unitFactor, maxRowRec, rowIdx, maxColRec, colIdx, 1, 0));
                        }
                    }
                }
            }
        }
        return rst;
    };
    outputAsSimpleJSONPage(rptTpl: IRptTpl, dataObj: IDataObj, page: number, bands: IBands, controls: IControlCollection, $CURRENT_RPT: ICurrent_RPT, customizeCfg: ICustomizeCfg) {
        let me = this, rst: any = [], tabRstLst = [];
        let unitFactor = JpcCommonHelper.getUnitFactor(rptTpl);
        if (me.paging_option === JV.PAGING_OPTION_INFINITY) {
            // 交叉式表暂时不支持无限扩展功能
        } else {
            let segIdx = JpcCommonHelper.getSegIdxByPageIdx(page, me.page_seg_map);
            //1 calculate the band position
            JpcBandHelper.setBandArea(bands, rptTpl, me.pageStatusLst[page - 1], false, false);
            //2. start to output detail-part
            //2.1 Row-Tab
            //tabRstLst.push(me.outputRowTab(rptTpl, dataObj, page, bands, unitFactor, controls, $CURRENT_RPT, customizeCfg));
            tabRstLst.push(me.outputRowTabCommon(rptTpl, dataObj, page, bands, JV.NODE_CROSS_ROW, me.row_fields_idx, unitFactor, controls, $CURRENT_RPT, customizeCfg));
            tabRstLst.push(me.outputRowTabCommon(rptTpl, dataObj, page, bands, JV.NODE_CROSS_ROW_AD_HOC, me.row_fields_adhoc_idx, unitFactor, controls, $CURRENT_RPT, customizeCfg));
            //2.2 Col-Tab
            tabRstLst.push(me.outputColTab(rptTpl, dataObj, page, bands, unitFactor, controls, $CURRENT_RPT, customizeCfg));
            //2.3 Content-Tab
            tabRstLst.push(me.outputContent(rptTpl, dataObj, page, bands, unitFactor, controls, $CURRENT_RPT, customizeCfg));
            //2.4 Sum-Tab Row
            //2.4 Sum-tab Col
            tabRstLst.push(me.outputTabSum(rptTpl, dataObj, page, bands, unitFactor, JV.NODE_CROSS_COL_SUM, controls, $CURRENT_RPT, customizeCfg));
            //2.x row tab ext
            tabRstLst.push(me.outputTabExt(rptTpl, dataObj, page, bands, unitFactor, controls, $CURRENT_RPT, customizeCfg));
            tabRstLst.push(me.outputSumTabExt(rptTpl, dataObj, page, bands, unitFactor, segIdx, controls, $CURRENT_RPT, customizeCfg));
            //2.5 Discrete
            tabRstLst.push(JpcDiscreteHelper.outputDiscreteInfo(rptTpl.交叉表_信息.离散信息, bands, dataObj, unitFactor, me.pageStatusLst[page - 1], segIdx, 1, 0, $CURRENT_RPT, customizeCfg));
        }
        for (let i = 0; i < tabRstLst.length; i++) {
            rst = rst.concat(tabRstLst[i]);
            tabRstLst[i] = null;
        }
        return rst;
    };
    outputTabSum(rptTpl: IRptTpl, dataObj: IDataObj, page: number, bands: IBands, unitFactor: number, tabNodeName: string, controls: IControlCollection, $CURRENT_RPT: ICurrent_RPT, customizeCfg: ICustomizeCfg) {
        let me = this, rst: any = [],
            tab = rptTpl.交叉表_信息[tabNodeName],
            band = bands[tab.BandName];
        if (band) {
            let pageStatus = me.pageStatusLst[page - 1];
            if (pageStatus[(band.DisplayType) as number] === true) {
                let tab_fields = tab.cross_field_s;
                for (let i = 0; i < me.dispSumValueLst_Col[page - 1].length; i++) {
                    if (i === 0) {
                        for (let tfIdx = 0; tfIdx < tab_fields.length; tfIdx++) {
                            let map_data_field = JE.F(tab_fields[tfIdx].FieldID, $CURRENT_RPT);
                            JpcFieldHelper.resetFormat(tab_fields[tfIdx], map_data_field, customizeCfg);
                        }
                    }
                    if (me.dispSumValueLst_Col[page - 1][i] !== null) {
                        for (let j = 0; j < me.dispSumValueLst_Col[page - 1][i].length; j++) {
                            let tab_field = tab_fields[j];
                            let val = me.dispSumValueLst_Col[page - 1][i][j];
                            let cellItem = JpcCommonOutputHelper.createCommonOutput(tab_field, val, controls);
                            cellItem.area = JpcAreaHelper.outputArea(tab_field[JV.PROP_AREA], band, unitFactor, me.dispSumValueLst_Col[page - 1].length, i, 1, 0, 1, 0, true, false);
                            rst.push(cellItem);
                        }
                    } else {
                        let sumL = 1;
                        for (let si = 0; si < me.dispSumValueLst_Col.length; si++) {
                            if (me.dispSumValueLst_Col[si][0] !== null) {
                                sumL = me.dispSumValueLst_Col[si][0].length;
                                break;
                            }
                        }
                        for (let j = 0; j < sumL; j++) {
                            let tab_field = tab_fields[j];
                            let val = null;
                            let cellItem = JpcCommonOutputHelper.createCommonOutput(tab_field, val, controls);
                            cellItem.area = JpcAreaHelper.outputArea(tab_field[JV.PROP_AREA], band, unitFactor, me.dispSumValueLst_Col[page - 1].length, i, 1, 0, 1, 0, true, false);
                            rst.push(cellItem);
                        }
                    }
                }
            }
        }
        return rst;
    };
    outputTabExt(rptTpl: IRptTpl, dataObj: IDataObj, page: number, bands: IBands, unitFactor: number, controls: IControlCollection, $CURRENT_RPT: ICurrent_RPT, customizeCfg: ICustomizeCfg) {
        let me = this, rst: any = [], firstTextOutput = true,
            tab = rptTpl.交叉表_信息.交叉行拓展;
        let band = bands[tab.BandName];
        if (band) {
            let pageStatus = me.pageStatusLst[page - 1];
            if (pageStatus[(band.DisplayType) as number] === true) {
                let tab_fields = tab.cross_field_s,
                    data_details = dataObj[IDataObjProps.detail_data],
                    valuesIdx = me.dispValueIdxLst_Col[page - 1];
                for (let i = 0; i < me.row_extension_fields_idx.length; i++) {
                    let tab_field = tab_fields[i];
                    let data_field = null;
                    let map_data_field = JE.F(tab_field.FieldID, $CURRENT_RPT);
                    if (typeof me.row_extension_fields_idx[i] !== 'object') {
                        data_field = data_details[me.row_extension_fields_idx[i]];
                    } else {
                        if (map_data_field) {
                            data_field = map_data_field.data_field;
                        }
                    }

                    if (!(tab_field.Hidden)) {
                        let cols = valuesIdx.length;
                        for (let colIdx = 0; colIdx < cols; colIdx++) {
                            if (colIdx === 0) JpcFieldHelper.resetFormat(tab_field, map_data_field, customizeCfg);
                            rst.push(me.outputTabField(band, tab_field, data_field, valuesIdx[colIdx], -1, 1, 0, cols, colIdx, unitFactor, false, controls));
                            //2. output texts if has
                            if (firstTextOutput) {
                                if (tab.text) {
                                    rst.push(JpcTextHelper.outputText(tab.text, band, unitFactor, 1, 0, cols, colIdx, 1, 0));
                                }
                                if (tab.text_s) {
                                    for (let j = 0; j < tab.text_s.length; j++) {
                                        rst.push(JpcTextHelper.outputText(tab.text_s[j], band, unitFactor, 1, 0, cols, colIdx, 1, 0));
                                    }
                                }
                            }
                        }
                        firstTextOutput = false;
                    }
                }
            }
        }
        return rst;
    };
    outputSumTabExt(rptTpl: IRptTpl, dataObj: IDataObj, page: number, bands: IBands, unitFactor: number, segIdx: number, controls: IControlCollection, $CURRENT_RPT: ICurrent_RPT, customizeCfg: ICustomizeCfg) {
        let me = this, rst = [],
            tab = rptTpl.交叉表_信息.交叉行拓展合计;
        let band = bands[tab.BandName];
        if (band) {
            let pageStatus = me.pageStatusLst[page - 1];
            if (pageStatus[(band.DisplayType) as number] === true && pageStatus[6] === true) {
                let tab_fields = tab.cross_field_s,
                    data_details = dataObj[IDataObjProps.detail_data],
                    data_fields = [];
                for (let i = 0; i < me.row_sum_extension_fields_idx.length; i++) {
                    // let data_field = data_details[me.row_sum_extension_fields_idx[i]];
                    let tab_field = tab_fields[i];
                    let data_field = null;
                    let map_data_field = JE.F(tab_field.FieldID, $CURRENT_RPT);
                    if (typeof me.row_sum_extension_fields_idx[i] !== 'object') {
                        data_field = data_details[me.row_sum_extension_fields_idx[i]];
                    } else {
                        if (map_data_field) {
                            data_field = map_data_field.data_field;
                        }
                    }
                    JpcFieldHelper.resetFormat(tab_field, map_data_field, customizeCfg);
                    data_fields.push(data_field);
                }
                //2. initialize grand total value
                let rowGrandTotal = [];
                for (let di = 0; di < data_fields.length; di++) {
                    rowGrandTotal[di] = 0.0;
                    //3. start to sum
                    for (let i = 0; i < me.sortedColSequence[segIdx].length; i++) {
                        //me.sortedColSequence[segIdx][i][0] //this is the data field value index!
                        rowGrandTotal[di] = rowGrandTotal[di] + 1.0 * parseFloat(JpcFieldHelper.getValue(data_fields[di], me.sortedColSequence[segIdx][i][0]));
                    }
                }
                //4. output
                for (let di = 0; di < tab_fields.length; di++) {
                    let tab_field = tab_fields[di];
                    if (!tab_field.Hidden) {
                        let val = rowGrandTotal[di];
                        let cellItem = JpcCommonOutputHelper.createCommonOutput(tab_field, val, controls);
                        cellItem.area = JpcAreaHelper.outputArea(tab_field.area, band, unitFactor, 1, 0, 1, 0, 1, 0, false, false);
                        rst.push(cellItem);
                    }
                }
                //output texts if has
                if (tab.text) {
                    rst.push(JpcTextHelper.outputText(tab.text, band, unitFactor, 1, 0, 1, 0, 1, 0));
                }
                if (tab.text_s) {
                    for (let j = 0; j < tab.text_s.length; j++) {
                        rst.push(JpcTextHelper.outputText(tab.text_s[j], band, unitFactor, 1, 0, 1, 0, 1, 0));
                    }
                }
            }
        }
        return rst;
    };
    outputContent(rptTpl: IRptTpl, dataObj: IDataObj, page: number, bands: IBands, unitFactor: number, controls: IControlCollection, $CURRENT_RPT: ICurrent_RPT, customizeCfg: ICustomizeCfg) {
        let me = this, rst: any = [];
        let tab = rptTpl.交叉表_信息.交叉数据;
        let band = bands[tab.BandName];
        if (band) {
            let pageStatus = me.pageStatusLst[page - 1];
            if (pageStatus[(band.DisplayType) as number] === true) {
                let tab_fields = tab.cross_field_s;
                let data_details = dataObj[IDataObjProps.detail_data];
                let contentValuesIdx = me.dispValueIdxLst_Content[page - 1];
                let flexiblePrecisionRefObj: any = null, flexibleRefField = null, precision_ref_data = null;
                for (let i = 0; i < tab_fields.length; i++) {
                    let tab_field = tab_fields[i];
                    let data_field = null;
                    let map_data_field = JE.F(tab_field.FieldID, $CURRENT_RPT);
                    if (typeof me.content_fields_idx[i] !== 'object') {
                        data_field = data_details[me.content_fields_idx[i]];
                    } else {
                        if (map_data_field) {
                            data_field = map_data_field.data_field;
                        }
                    }
                    if (!(tab_field.Hidden)) {
                        let rows = contentValuesIdx.length;
                        for (let rowIdx = 0; rowIdx < rows; rowIdx++) {
                            let cols = contentValuesIdx[rowIdx].length;
                            for (let colIdx = 0; colIdx < cols; colIdx++) {
                                if (map_data_field && map_data_field.Precision && map_data_field.flexiblePrecisionRefObj && map_data_field.Precision.flexibleRefFieldID) {
                                    if (flexiblePrecisionRefObj === null) {
                                        flexiblePrecisionRefObj = {};
                                        flexibleRefField = JE.F(map_data_field.Precision.flexibleRefFieldID, $CURRENT_RPT);
                                        if (flexibleRefField && flexibleRefField.DataSeq) precision_ref_data = dataObj[map_data_field.DataNodeName][flexibleRefField.DataSeq];
                                        for (let decimalObj of map_data_field.flexiblePrecisionRefObj) {
                                            flexiblePrecisionRefObj["refUnit_" + decimalObj.unit] = decimalObj.decimal;
                                        }
                                    }
                                    JpcFieldHelper.resetFlexibleFormat(tab_field, precision_ref_data, flexiblePrecisionRefObj, contentValuesIdx[rowIdx][colIdx], customizeCfg);
                                } else {
                                    if (colIdx === 0) JpcFieldHelper.resetFormat(tab_field, map_data_field, customizeCfg);
                                }
                                rst.push(me.outputTabField(band, tab_field, data_field, contentValuesIdx[rowIdx][colIdx], -1, rows, rowIdx, cols, colIdx, unitFactor, true, controls));
                            }
                        }
                    }
                }
            }
        }
        return rst;
    };
    outputColTab(rptTpl: IRptTpl, dataObj: IDataObj, page: number, bands: IBands, unitFactor: number, controls: IControlCollection, $CURRENT_RPT: ICurrent_RPT, customizeCfg: ICustomizeCfg) {
        let me = this, rst: any = [], firstTextOutput = true;
        let tab = rptTpl.交叉表_信息.交叉列;
        let band = bands[tab.BandName];
        if (band) {
            let pageStatus = me.pageStatusLst[page - 1];
            if (pageStatus[(band.DisplayType) as number] === true) {
                let tab_fields = tab.cross_field_s;
                let data_details = dataObj[IDataObjProps.detail_data];
                let valuesIdx = me.dispValueIdxLst_Col[page - 1];
                let flexiblePrecisionRefObj: any = null, flexibleRefField = null, precision_ref_data = null;
                for (let i = 0; i < me.col_fields_idx.length; i++) {
                    let tab_field = tab_fields[i];
                    if (!(tab_field.Hidden)) {
                        let mergedRst = [];
                        let data_field = null;
                        let map_data_field = JE.F(tab_field.FieldID, $CURRENT_RPT);
                        if (typeof me.col_fields_idx[i] !== 'object') {
                            data_field = data_details[me.col_fields_idx[i]];
                        } else {
                            if (map_data_field) {
                                data_field = map_data_field.data_field;
                            }
                        }
                        let cols = valuesIdx.length;
                        for (let colIdx = 0; colIdx < cols; colIdx++) {
                            if (map_data_field && map_data_field.Precision && map_data_field.flexiblePrecisionRefObj && map_data_field.Precision.flexibleRefFieldID) {
                                if (flexiblePrecisionRefObj === null) {
                                    flexiblePrecisionRefObj = {};
                                    flexibleRefField = JE.F(map_data_field.Precision.flexibleRefFieldID, $CURRENT_RPT);
                                    if (flexibleRefField && flexibleRefField.DataSeq) precision_ref_data = dataObj[map_data_field.DataNodeName][flexibleRefField.DataSeq];
                                    for (let decimalObj of map_data_field.flexiblePrecisionRefObj) {
                                        flexiblePrecisionRefObj["refUnit_" + decimalObj.unit] = decimalObj.decimal;
                                    }
                                }
                                JpcFieldHelper.resetFlexibleFormat(tab_field, precision_ref_data, flexiblePrecisionRefObj, valuesIdx[colIdx], customizeCfg);
                            } else {
                                if (colIdx === 0) JpcFieldHelper.resetFormat(tab_field, map_data_field, customizeCfg);
                            }
                            mergedRst.push(me.outputTabField(band, tab_field, data_field, valuesIdx[colIdx], -1, 1, 0, cols, colIdx, unitFactor, false, controls));
                            //rst.push(me.outputTabField(band, tab_field, data_field, valuesIdx[colIdx], -1, 1, 0, cols, colIdx, unitFactor, false, controls));
                            //2. output texts
                            if (firstTextOutput) {
                                if (tab.text) {
                                    // mergedRst.push(JpcTextHelper.outputText(tab.text, band, unitFactor, 1, 0, cols, colIdx, 1, 0));
                                    rst.push(JpcTextHelper.outputText(tab.text, band, unitFactor, 1, 0, cols, colIdx, 1, 0));
                                }
                                if (tab.text_s) {
                                    for (let j = 0; j < tab.text_s.length; j++) {
                                        // mergedRst.push(JpcTextHelper.outputText(tab.text_s[j], band, unitFactor, 1, 0, cols, colIdx, 1, 0));
                                        rst.push(JpcTextHelper.outputText(tab.text_s[j], band, unitFactor, 1, 0, cols, colIdx, 1, 0));
                                    }
                                }
                            }
                        }
                        firstTextOutput = false;
                        //判断是否需要合并
                        if (tab_field.isMerge && mergedRst.length > 1) {
                            let lastCell = mergedRst[mergedRst.length - 1];
                            for (let mergeIdx = mergedRst.length - 2; mergeIdx >= 0; mergeIdx--) {
                                if (lastCell.Value === mergedRst[mergeIdx].Value) {
                                    mergedRst[mergeIdx].area.Right = lastCell.area.Right;
                                    mergedRst.splice(mergeIdx + 1, 1);
                                }
                                lastCell = mergedRst[mergeIdx];
                            }
                        }
                        rst = rst.concat(mergedRst);
                    }
                }
            }
        }
        return rst;
    };
    outputRowTabCommon(rptTpl: IRptTpl, dataObj: IDataObj, page: number, bands: IBands, tabStr: string, rowFieldsIdxArr: any[], unitFactor: number, controls: IControlCollection, $CURRENT_RPT: ICurrent_RPT, customizeCfg: ICustomizeCfg) {
        let me = this, rst = [];
        let tab = rptTpl.交叉表_信息[tabStr];
        let band = (tab) ? bands[tab.BandName] : null;
        if (band) {
            let pageStatus = me.pageStatusLst[page - 1];
            if (pageStatus[(band.DisplayType) as number] === true) {
                let tab_fields = tab.cross_field_s;
                let data_details = dataObj[IDataObjProps.detail_data];
                let valuesIdx = me.dispValueIdxLst_Row[page - 1];
                let serialsIdx = me.dispSerialIdxLst_Row[page - 1];
                let flexiblePrecisionRefObj: any = null, flexibleRefField = null, precision_ref_data = null;
                for (let i = 0; i < rowFieldsIdxArr.length; i++) {
                    let tab_field = tab_fields[i];
                    if (!(tab_field.Hidden)) {
                        let data_field = null;
                        let map_data_field = JE.F(tab_field.FieldID, $CURRENT_RPT);
                        if (typeof rowFieldsIdxArr[i] !== 'object') {
                            data_field = data_details[rowFieldsIdxArr[i]];
                        } else {
                            if (map_data_field) {
                                data_field = map_data_field.data_field;
                            }
                        }
                        let rows = valuesIdx.length;
                        for (let rowIdx = 0; rowIdx < rows; rowIdx++) {
                            if (map_data_field && map_data_field.Precision && map_data_field.flexiblePrecisionRefObj && map_data_field.Precision.flexibleRefFieldID) {
                                if (flexiblePrecisionRefObj === null) {
                                    flexiblePrecisionRefObj = {};
                                    flexibleRefField = JE.F(map_data_field.Precision.flexibleRefFieldID, $CURRENT_RPT);
                                    if (flexibleRefField && flexibleRefField.DataSeq) precision_ref_data = dataObj[map_data_field.DataNodeName][flexibleRefField.DataSeq];
                                    for (let decimalObj of map_data_field.flexiblePrecisionRefObj) {
                                        flexiblePrecisionRefObj["refUnit_" + decimalObj.unit] = decimalObj.decimal;
                                    }
                                }
                                JpcFieldHelper.resetFlexibleFormat(tab_field, precision_ref_data, flexiblePrecisionRefObj, valuesIdx[rowIdx], customizeCfg);
                            } else {
                                if (rowIdx === 0) JpcFieldHelper.resetFormat(tab_field, map_data_field, customizeCfg);
                            }
                            rst.push(me.outputTabField(band, tab_field, data_field, valuesIdx[rowIdx], serialsIdx[rowIdx], rows, rowIdx, 1, 0, unitFactor, true, controls));
                        }
                    }
                }
            }
        }
        return rst;
    };
    //暂定
    outputTabField(band: IBandDetail, tab_field: Fields, data_field: any, valueIdx: number, serialIdx: number, rows: number, rowIdx: number, cols: number, colIdx: number, unitFactor: number, isRow: boolean, controls: IControlCollection) {
        let rst = null;
        if (isRow === true && tab_field.isSerial && tab_field.isSerial === true) {
            if (serialIdx >= 0) {
                rst = JpcCommonOutputHelper.createCommonOutput(tab_field, serialIdx + 1, null);
            } else rst = JpcCommonOutputHelper.createCommonOutput(tab_field, "", controls);
        } else {
            rst = JpcCommonOutputHelper.createCommonOutput(tab_field, JpcFieldHelper.getValue(data_field, valueIdx), controls);
        }
        //position
        if (isRow === true) {
            rst.area = JpcAreaHelper.outputArea(tab_field.area, band, unitFactor, rows, rowIdx, cols, colIdx, 1, 0, true, false);
        } else {
            rst.area = JpcAreaHelper.outputArea(tab_field.area, band, unitFactor, rows, rowIdx, cols, colIdx, 1, 0, false, false);
        }
        return rst;
    };
};
function _addTabValue(tabValuedIdxLst: number[][], sortedSequence: number[][][], segIdx: number, preRec: number, nextRec: number, dispSerialIdxLst: any, sorted_sum_value_Lst: any, rst_sum_value_Lst: any) {
    if (tabValuedIdxLst) {
        let serial1stTier = null;
        if (dispSerialIdxLst) serial1stTier = [];
        let pgseg1stTier = [];
        let sumVal = [];
        let sumValL = 1;
        if (sortedSequence) {
            let arrDupVals = sortedSequence[segIdx];
            let arrDupSumVals = null;
            if (sorted_sum_value_Lst !== null) {
                arrDupSumVals = sorted_sum_value_Lst[segIdx];
                sumValL = arrDupSumVals[0].length;
            }

            for (let i = 0; i < nextRec; i++) {
                if (arrDupVals.length <= preRec + i) {
                    pgseg1stTier[i] = JV.BLANK_VALUE_INDEX;
                    sumVal[i] = [];
                    for (let ei = 0; ei < sumValL; ei++) {
                        sumVal[i][ei] = null;
                    }
                    if (serial1stTier !== null) {
                        serial1stTier[i] = JV.BLANK_VALUE_INDEX;
                    }
                    continue;
                }
                let duplicateValueArr = arrDupVals[preRec + i];
                pgseg1stTier[i] = duplicateValueArr[0];
                if (arrDupSumVals !== null) sumVal[i] = arrDupSumVals[preRec + i];

                if (serial1stTier !== null) {
                    serial1stTier[i] = preRec + i;
                }
            }
            tabValuedIdxLst.push(pgseg1stTier);
            if (dispSerialIdxLst !== null) {
                dispSerialIdxLst.push(serial1stTier);
            }
            if (sorted_sum_value_Lst !== null && rst_sum_value_Lst !== null) {
                rst_sum_value_Lst.push(sumVal);
            }
        } else {
            //should push blank value index rather than null
            for (let i = 0; i < nextRec; i++) {
                pgseg1stTier[i] = JV.BLANK_VALUE_INDEX;
                sumVal[i] = null;
                if (serial1stTier !== null) {
                    serial1stTier[i] = JV.BLANK_VALUE_INDEX;
                }
            }
            tabValuedIdxLst.push(pgseg1stTier);
            if (dispSerialIdxLst !== null) {
                dispSerialIdxLst.push(serial1stTier);
            }
            if (sorted_sum_value_Lst !== null && rst_sum_value_Lst !== null) {
                rst_sum_value_Lst.push(sumVal);
            }
        }
    }
};

function _addContentValue(dispValueIdxLst_Content: number[][][], sortedContentSequence: string[][], segIdx: number, counterRowRec: number, maxRowRec: number, counterColRec: number, maxColRec: number, page_seg_map: [number, number][], pageIdx: number) {
    if (dispValueIdxLst_Content !== null) {
        page_seg_map.push([pageIdx, segIdx]);
        let arrContents: any[] = [];
        if (sortedContentSequence !== null) {
            let arrAllContent = sortedContentSequence[segIdx];
            for (let i = 0; i < maxRowRec; i++) {
                arrContents.push([]);
                for (let j = 0; j < maxColRec; j++) {
                    if (arrAllContent.length <= counterRowRec + i || arrAllContent[counterRowRec + i].length <= counterColRec + j) {
                        arrContents[i][j] = JV.BLANK_VALUE_INDEX;
                    } else {
                        arrContents[i][j] = arrAllContent[counterRowRec + i][counterColRec + j];
                    }
                }
            }
            dispValueIdxLst_Content.push(arrContents);
        } else {
            //should push blank value index rather than null
            for (let i = 0; i < maxRowRec; i++) {
                arrContents.push([]);
                for (let j = 0; j < maxColRec; j++) {
                    arrContents[i][j] = JV.BLANK_VALUE_INDEX;
                }
            }
            dispValueIdxLst_Content.push(arrContents);
        }
    }
};

function _SortAndOptimize(rptTpl: IRptTpl, dataObj: IDataObj, dataSeq: number[][], sortTab: string, rstFieldsIdx: any[], $CURRENT_RPT: ICurrent_RPT) {
    let result = [];
    let tab = rptTpl.交叉表_信息[sortTab];
    if (tab) {
        let sIDX = 0;
        //1. prepare and sort by tab-field
        let fields: any[] = [];
        JpcFieldHelper.findAndPutDataFieldIdx(rptTpl, tab.cross_field_s, fields, rstFieldsIdx, false);
        let data_details = dataObj[IDataObjProps.detail_data];
        JpcCrossTabHelper.sortTabFields(fields, rstFieldsIdx, data_details, dataSeq, $CURRENT_RPT);
        //2. distinguish sort tab fields value
        let b1 = false;
        for (let i = 0; i < dataSeq.length; i++) {
            sIDX = 0;
            let segArr: any[] = [];
            if (dataSeq[i].length === 1) {
                JpcCrossTabHelper.pushToSeg(segArr, dataSeq, i, 0, 1);
            } else {
                for (let j = 1; j < dataSeq[i].length; j++) {
                    b1 = false;
                    for (let k = 0; k < rstFieldsIdx.length; k++) {
                        if (fields[k].hasOwnProperty(JV.TAB_FIELD_PROP_SORT)) {
                            //只有被选择了作为排序字段的才进入排序及优化
                            if (typeof (rstFieldsIdx[k]) === 'object') {
                                let map_data_field = JE.F(rstFieldsIdx[k].ID, $CURRENT_RPT);
                                if (map_data_field && map_data_field.data_field[dataSeq[i][j - 1]] !== map_data_field.data_field[dataSeq[i][j]]) {
                                    b1 = true;
                                    break;
                                }
                            } else {
                                if (data_details[rstFieldsIdx[k]][dataSeq[i][j - 1]] !== data_details[rstFieldsIdx[k]][dataSeq[i][j]]) {
                                    b1 = true;
                                    break;
                                }
                            }
                        }
                    }
                    if (b1) {
                        JpcCrossTabHelper.pushToSeg(segArr, dataSeq, i, sIDX, j);
                        sIDX = j;
                        if (j === dataSeq[i].length - 1) {
                            JpcCrossTabHelper.pushToSeg(segArr, dataSeq, i, j, dataSeq[i].length);
                        }
                    } else if (j === dataSeq[i].length - 1) {
                        JpcCrossTabHelper.pushToSeg(segArr, dataSeq, i, sIDX, dataSeq[i].length);
                    }
                }
            }
            if (segArr.length > 0) result.push(segArr);
        }
    }
    return result;
}

function _SortForDisplayContent(rptTpl: IRptTpl, rowSeq: number[][][], colSeq: number[][][], rstFieldsIdx: any[]) {
    let result = [];
    let tab = rptTpl.交叉表_信息.交叉数据;
    if (tab) {
        JpcFieldHelper.findAndPutDataFieldIdx(rptTpl, tab.cross_field_s, [], rstFieldsIdx, false);
    }
    for (let i = 0; i < rowSeq.length; i++) {
        let rl = rowSeq[i], cl = colSeq[i];
        let ds: number[][] = [];
        //1. initialize to blank value index
        for (let j = 0; j < rl.length; j++) {
            ds.push([]);
            for (let k = 0; k < cl.length; k++) {
                ds[j].push(JV.BLANK_VALUE_INDEX);
            }
        }
        //2. then fill up the right index
        for (let j = 0; j < rl.length; j++) {
            let ra = rl[j];
            for (let k = 0; k < ra.length; k++) {
                let colIdx = JpcCrossTabHelper.getColIDX(cl, ra[k]);
                if (colIdx >= 0) {
                    ds[j][colIdx] = ra[k];
                }
            }
        }
        result.push(ds);
    }
    return result;
};