'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 { JpcFlowTabHelper } from './helper/jpc_helper_flow_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 * as strUtil from '../public/stringUtil';
import { fontWidthMap } from './helper/jpc_helper_font_width';
import {
    Fields,
    IDefProperties,
    ICurrent_RPT,
    ICustomizeCfg,
    IBands,
    IBandDetail,
    IControlCollection,
    ICell,
    IMergePos,
    IGrpLine,
    ITab,
    IGrpPageInfo,
    IRptTpl,
    IDataObj,
    IGroupField,
    IPageCellObj,
    IPageAreaObj,
    IControlSubCollection,

} from '../interface/basic'
import { combinedGridFormula } from './formulasFun';

export class JpcFlowTabClass {
    isEx: boolean;
    paging_option: string;
    segments: number[][];
    dispValueIdxLst: number[][][];
    page_seg_map: number[][];
    disp_fields_idx: number[];
    disp_fields_ex_idx: number[];
    seg_sum_fields_idx: any[];
    seg_sum_tab_fields: any[];
    page_sum_fields_idx: any[];
    page_sum_tab_fields: any[];
    auto_height_fields_idx: [number, Fields][];//那些被标记为判断自动行高的指标集合
    auto_height_info: number[][];
    group_check_fields: Fields[];
    group_sum_fields: Fields[];
    group_sum_values: Fields[];
    group_node_info: number[][]; //记录在哪个seg及到哪条记录后有group sum信息
    group_lines_amt: number;    //每group一次占用多少行，计算page信息会用到
    pageStatusLst: boolean[][];
    groupSumValLst: any[];
    segSumValLst: any[];
    pageSumValLst: any[];
    multiCols: number;
    pagesAmt: number;

    constructor(isEx: boolean) {
        //初始化
        this.isEx = isEx;
        this.paging_option = JV.PAGING_OPTION_NORMAL;
        this.segments = [];
        this.dispValueIdxLst = [];
        this.page_seg_map = [];
        this.disp_fields_idx = [];
        this.disp_fields_ex_idx = [];
        this.seg_sum_fields_idx = [];
        this.seg_sum_tab_fields = [];
        this.page_sum_fields_idx = [];
        this.page_sum_tab_fields = [];

        this.auto_height_fields_idx = [];//那些被标记为判断自动行高的指标集合
        this.auto_height_info = [];
        this.group_check_fields = [];
        this.group_sum_fields = [];
        this.group_sum_values = [];
        // this.group_sum_values = null; 因为在后面初始化时会先把该变量设置为[],所以这里直接修改为[] ,by lish
        this.group_node_info = []; //记录在哪个seg及到哪条记录后有group sum信息
        // this.group_node_info = null; 因为在后面初始化时会先把该变量设置为[],所以这里直接修改为[]  ,by lish
        this.group_lines_amt = 0;    //每group一次占用多少行，计算page信息会用到

        this.pageStatusLst = [];
        this.groupSumValLst = [];
        this.segSumValLst = [];
        this.pageSumValLst = [];
        this.multiCols = 1;
        this.pagesAmt = 0;
    };
    sorting(rptTpl: IRptTpl, dataObj: IDataObj, dataSeq: number[][], $CURRENT_RPT: ICurrent_RPT) {
        let me = this;
        // let FLOW_NODE_STR = me.isEx?'流水式表_拓展信息':'流水式表_信息';
        //因为rptTpl[FLOW_NODE_STR的写法不兼容ts，所以把变量改为flow_node_str代替
        let flow_node_str = me.isEx ? rptTpl.流水式表_拓展信息 : rptTpl.流水式表_信息;
        if (flow_node_str.流水式表_段统计信息) JpcFieldHelper.findAndPutDataFieldIdx(rptTpl, flow_node_str.流水式表_段统计信息.sum_field_s, me.seg_sum_tab_fields, me.seg_sum_fields_idx, me.isEx);
        if (flow_node_str.流水式表_页统计信息) JpcFieldHelper.findAndPutDataFieldIdx(rptTpl, flow_node_str.流水式表_页统计信息.sum_field_s, me.page_sum_tab_fields, me.page_sum_fields_idx, me.isEx);
        if (flow_node_str.流水式表_分组信息) {
            JpcFieldHelper.findAndPutDataFieldIdx(rptTpl, flow_node_str.流水式表_分组信息.group_field_s, me.group_check_fields, null, me.isEx);
            if (flow_node_str.流水式表_分组信息.group_lines) {
                for (let grpLine of flow_node_str.流水式表_分组信息.group_lines) {
                    if (grpLine.SumKey_S && grpLine.SumKey_S.length > 0) {
                        JpcFieldHelper.findAndPutDataFieldIdx(rptTpl, grpLine.SumKey_S, me.group_sum_fields, null, me.isEx);
                    }
                }
            }
            for (let grp_sum_f of me.group_sum_fields) {
                grp_sum_f.SumKey = `grp_sum_key_` + grp_sum_f.FieldID;
            }
        }
        JpcFieldHelper.findAutoHeightFieldIdx(rptTpl, flow_node_str.流水式表_数据.flow_field_s, me.auto_height_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)
        //考虑到实际会有离散指标的汇总，这些离散指标数据是通过计算式后得来的，这种情况下，不适宜在sorting阶段进行汇总统计，现挪到preSetupPages阶段处理
    };
    sumSeg(dataObj: IDataObj, $CURRENT_RPT: ICurrent_RPT) {
        let me = this;
        let data_details = me.isEx ? dataObj.detail_data_ex : dataObj.detail_data,
            data_fields = [];
        for (let i = 0; i < me.seg_sum_fields_idx.length; i++) {
            if (typeof (me.seg_sum_fields_idx[i]) === "object") {
                let exField = JE.F(me.seg_sum_fields_idx[i][JV.PROP_ID], $CURRENT_RPT);
                if (exField) {
                    data_fields.push(exField.data_field);
                } else {
                    data_fields.push(null);
                }
            } else {
                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);
                    let precisionAmt = 4;
                    let sum_field = JE.F(me.seg_sum_tab_fields[di][JV.PROP_FIELD_ID], $CURRENT_RPT);
                    if (sum_field && sum_field.Precision && sum_field.Precision.type === `fixed`) {
                        precisionAmt = sum_field.fixedPrecisionNum;
                    } else {
                        let flowF = me.seg_sum_tab_fields[di];
                        if (flowF && !strUtil.isEmptyString(flowF[JV.PROP_FORMAT])) {
                            let idx = flowF[JV.PROP_FORMAT].indexOf('.');
                            if (idx >= 0) {
                                precisionAmt = flowF[JV.PROP_FORMAT].length - idx - 1;
                            }
                        }
                    }
                    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]);
                        let sv = JpcFieldHelper.getValue(data_fields[di], me.segments[i][j]);
                        if (sv) {
                            rowGrandTotal[di] = rowGrandTotal[di] + parseFloat(parseFloat(sv).toFixed(precisionAmt));
                        }
                    }
                }
                me.segSumValLst.push(rowGrandTotal);
            }
        }
    };
    sumUpGrp(rptTpl: IRptTpl, $CURRENT_RPT: ICurrent_RPT, dataObj: IDataObj, segIdx: number, preGrpIdx: number, nexGrpIdx: number) {
        let me = this, segDataIdx = me.segments[segIdx];
        for (let j = 0; j < me.group_sum_fields.length; j++) {
            let sum_field: IGroupField | null = JE.F(me.group_sum_fields[j].FieldID, $CURRENT_RPT);
            if (sum_field) {
                let data_field = null;
                if (sum_field.data_field) {
                    data_field = sum_field.data_field
                } else {
                    data_field = dataObj[sum_field.DataNodeName][sum_field.DataSeq];
                }
                let sumV = 0, precisionAmt = 4;
                for (let si = preGrpIdx; si <= nexGrpIdx; si++) {
                    if (sum_field.Precision && sum_field.Precision.type === `fixed`) {
                        precisionAmt = sum_field.fixedPrecisionNum;
                    } else {
                        let flowF = me.group_sum_fields[j]; //调整后，me.group_sum_fields[j]就是group lines下数组SumKey_S的元素值，无需再找
                        if (flowF && !strUtil.isEmptyString(flowF.Format)) {
                            let idx = flowF.Format.indexOf('.');
                            if (idx >= 0) {
                                precisionAmt = flowF.Format.length - idx - 1;
                            }
                        }
                    }
                    //sumV += parseFloat(JpcFieldHelper.getValue(data_field, segDataIdx[si]));
                    sumV += parseFloat(parseFloat(JpcFieldHelper.getValue(data_field, segDataIdx[si])).toFixed(precisionAmt));
                }
                // me.group_sum_values[segIdx][j].push(sumV);
                me.group_sum_values[segIdx][me.group_sum_fields[j].SumKey].push(sumV);
            }
        }
        me.group_node_info[segIdx].push(nexGrpIdx);
    };
    setupGroupingData(rptTpl: IRptTpl, dataObj: IDataObj, $CURRENT_RPT: ICurrent_RPT) {
        let me = this;
        if (me.group_check_fields.length > 0 && me.group_sum_fields.length > 0) {
            me.group_sum_values = [];
            me.group_node_info = [];
            // let CURRENT_FLOW_INFO = (me.isEx)?'流水式表_拓展信息':'流水式表_信息';
            let current_flow_info = me.isEx ? rptTpl.流水式表_拓展信息 : rptTpl.流水式表_信息;
            me.group_lines_amt = current_flow_info.流水式表_分组信息.group_lines.length;
            //
            let preGrpIdx = 0, nexGrpIdx = 0;
            for (let segIdx = 0; segIdx < me.segments.length; segIdx++) {
                let segDataIdx = me.segments[segIdx];
                // me.group_sum_values.push([]);
                me.group_sum_values.push({} as Fields);
                me.group_node_info.push([]);
                for (let j = 0; j < me.group_sum_fields.length; j++) {
                    // me.group_sum_values[segIdx].push([]);
                    me.group_sum_values[segIdx][me.group_sum_fields[j].SumKey] = [];
                    // me.group_node_info[segIdx].push([]);
                }
                for (let di = 0; di < segDataIdx.length; di++) {
                    let hasDiff = false;
                    if (di >= 1) {
                        for (let i = 0; i < me.group_check_fields.length; i++) {
                            let grp_field = JE.F(me.group_check_fields[i].FieldID, $CURRENT_RPT);
                            if (grp_field) {
                                let data_field = null;
                                if (grp_field.data_field) {
                                    data_field = grp_field.data_field
                                } else {
                                    data_field = dataObj[grp_field.DataNodeName][grp_field.DataSeq];
                                }
                                let v1 = JpcFieldHelper.getValue(data_field, segDataIdx[di]), v2 = JpcFieldHelper.getValue(data_field, segDataIdx[di - 1]);
                                if (v1 !== v2) {
                                    hasDiff = true;
                                    break;
                                }
                            }
                        }
                    }
                    if (hasDiff) {
                        //then sum up the fields
                        me.sumUpGrp(rptTpl, $CURRENT_RPT, dataObj, segIdx, preGrpIdx, nexGrpIdx);
                        nexGrpIdx = di;
                        preGrpIdx = di;
                        if (di === segDataIdx.length - 1) {
                            me.sumUpGrp(rptTpl, $CURRENT_RPT, dataObj, segIdx, preGrpIdx, nexGrpIdx);
                        }
                    } else if (di === segDataIdx.length - 1) {
                        me.sumUpGrp(rptTpl, $CURRENT_RPT, dataObj, segIdx, preGrpIdx, di);
                    } else {
                        nexGrpIdx = di;
                    }
                }
            }
        }
    };
    setupAutoHeightData(bands: IBands, segIdx: number, rptTpl: IRptTpl, dataObj: IDataObj, $CURRENT_RPT: ICurrent_RPT, defProperties: IDefProperties) {
        let me = this;
        if (me.auto_height_fields_idx.length > 0) {
            // let CURRENT_FLOW_INFO = (me.isEx)?'流水式表_拓展信息':'流水式表_信息';
            let current_flow_info = me.isEx ? rptTpl.流水式表_拓展信息 : rptTpl.流水式表_信息;
            let band = bands[current_flow_info.流水式表_数据.BandName];
            let data_details = me.isEx ? dataObj.detail_data_ex : dataObj.detail_data;
            let tab_fields = current_flow_info.流水式表_数据.flow_field_s;
            let adHocAutoHeightStyleStr = [];
            let reg1 = new RegExp('\n\r', 'g'), reg2 = new RegExp('\r\n', 'g'),
                reg3 = new RegExp('\n', 'g'), reg4 = new RegExp('\r', 'g');
            // let doc = new PDFKit({autoFirstPage: false});
            let fonts = defProperties.fonts;
            let fontCache: any = {};
            let private_get_font = function (fontKey: string) {
                let rst = null;
                if (fontCache[fontKey]) {
                    rst = fontCache[fontKey];
                } else {
                    for (let i = 0; i < fonts.length; i++) {
                        if (fonts[i].ID === fontKey) {
                            fontCache[fontKey] = fonts[i];
                            rst = fonts[i];
                            break;
                        }
                    }
                }
                return rst;
            };
            let private_get_max_lines_of_the_record = function (theRecIdx: number) {
                let rst = 1;
                let maxAmt = 1;
                for (let loop = 0; loop < me.auto_height_fields_idx.length; loop++) {
                    let tab_field = me.auto_height_fields_idx[loop][1];
                    let data_field = null,
                        map_data_field = JE.F(tab_field.FieldID, $CURRENT_RPT);
                    if (me.auto_height_fields_idx[loop][0] !== JV.BLANK_FIELD_INDEX && (typeof me.auto_height_fields_idx[loop][0] !== 'object')) {
                        data_field = data_details[me.auto_height_fields_idx[loop][0]];
                    } else {
                        if (map_data_field) {
                            data_field = map_data_field.data_field;
                        }
                    }
                    if (data_field) {
                        let value = JpcFieldHelper.getValue(data_field, theRecIdx);
                        let area = JpcAreaHelper.outputArea(tab_field.area, band, 1, 1, 0, 1, 0, 1, 0, false, false);
                        if (value !== null && value !== undefined) {
                            value = value.replace('\t', '');
                            value = value.replace(reg1, '|').replace(reg2, '|').replace(reg3, '|').replace(reg4, '|');
                        } else {
                            value = '';
                        }
                        JpcFieldHelper.setValue(data_field, theRecIdx, value);
                        let values = value.split('|');
                       // if (values.length > rst) rst = values.length; // 考虑到紧凑输出，不能那么快设置rst
                        let font = private_get_font(tab_field.font);
                        let chkFontName = '宋体';
                        let chkFontHeight = 12;
                        if (font) {
                            chkFontName = font[JV.FONT_PROPS[0]];
                            chkFontHeight = parseFloat(font[JV.FONT_PROPS[JV.FONT_PROP_IDX_HEIGHT]]);
                        }
                        let hasSplitStr = false, splitStrArr = [];
                        let accAmt = 0;
                        // let chnW = doc.widthOfString('一'), otherW = doc.widthOfString('_');
                        let chnW = fontWidthMap.getFontWidth(chkFontName, chkFontHeight, '宽'), otherW = fontWidthMap.getFontWidth(chkFontName, chkFontHeight, '窄');
                        for (let i = 0; i < values.length; i++) {
                            let amt = JpcCommonHelper.getStringLinesInArea(area, values[i], chnW, otherW);
                            accAmt += amt;
                            if (amt > 1) {
                                hasSplitStr = true;
                                splitStrArr.push(i);
                            }
                        }
                        
                        if (accAmt > 3) {
                            // 新优化，计算实际能显示完的真正行数
                            const rowHeight = JpcFlowTabHelper.getRowHeight(bands, rptTpl, me.isEx);
                            let tmpFV = ((chkFontHeight + JV.CLOSE_OUTPUT_ROW_BUFFER) * accAmt) / rowHeight;
                            let tmpAmt = Math.floor(tmpFV);
                            if (Math.ceil(tmpFV) > tmpAmt) {
                                tmpAmt++;
                            }
                            if (maxAmt < tmpAmt) maxAmt = tmpAmt;
                        } else {
                            if (maxAmt < accAmt) maxAmt = accAmt;
                        }
                        if (hasSplitStr) {
                            let newValArr: any = [];
                            for (let i = 0; i < values.length; i++) {
                                if (splitStrArr.indexOf(i) < 0) {
                                    newValArr.push(values[i]);
                                } else {
                                    newValArr = newValArr.concat(JpcCommonHelper.splitString(area, values[i], chnW, otherW));
                                }
                            }
                            JpcFieldHelper.setValue(data_field, theRecIdx, newValArr.join('|'));
                            splitStrArr = [];
                            newValArr = [];
                        }
                        //备注： 如果outputType是excel类型，那么就只保留原始的分行符，无需介入分行，由excel本身去处理分行，只需要保留足够的空间即可。
                        //      根据最新需求，暂时不考虑excel类型输出,换回原来逻辑
                    }
                }
                if (rst < maxAmt) rst = maxAmt; // 最后才设置最大结果
                return rst;
            };
            for (let tabField of tab_fields) {
                if (adHocAutoHeightStyleStr.indexOf(tabField.style) < 0) {
                    adHocAutoHeightStyleStr.push(tabField.style);
                }
            }
            if (adHocAutoHeightStyleStr.length > 0) {
                if (!(rptTpl.style_collection)) {
                    rptTpl.style_collection = [];
                }
                for (let styleStr of adHocAutoHeightStyleStr) {
                    let adHocStyle1 = { "ID": styleStr + "_AutoHeightMerge_Top" };
                    let adHocStyle2 = { "ID": styleStr + "_AutoHeightMerge_Middle" };
                    let adHocStyle3 = { "ID": styleStr + "_AutoHeightMerge_Bottom" };
                    rptTpl.style_collection.push(adHocStyle1);
                    rptTpl.style_collection.push(adHocStyle2);
                    rptTpl.style_collection.push(adHocStyle3);
                }
            }
            //这里先记录下来每一Segment里的每一条record占用行的数量（普通是1行高度，超过1就表示需要调整行数了）
            let infoArr: any = [];
            me.auto_height_info.push(infoArr);
            let segArr = me.segments[segIdx];
            for (let i = 0; i < segArr.length; i++) {
                infoArr.push(private_get_max_lines_of_the_record(segArr[i]));
            }
        }
    };
    preSetupPages(rptTpl: IRptTpl, dataObj: IDataObj, defProperties: IDefProperties, option: string, $CURRENT_RPT: ICurrent_RPT, followTabEx: any) {
        //换一种思路来整理流水式数据
        let me = this, rst = 1, counterRowRec = 0, counterRowRecEx = 0, maxRowRec = 1, pageIdx = 0, currentRecAmt = 0;
        me.paging_option = option || JV.PAGING_OPTION_NORMAL;
        let current_flow_info = me.isEx ? rptTpl.流水式表_拓展信息 : rptTpl.流水式表_信息;
        JpcFieldHelper.findAndPutDataFieldIdx(rptTpl, current_flow_info.流水式表_数据.flow_field_s, null, me.disp_fields_idx, me.isEx);
        if (followTabEx) {
            JpcFieldHelper.findAndPutDataFieldIdx(rptTpl, rptTpl.流水式表_拓展信息.流水式表_数据.flow_field_s, null, me.disp_fields_ex_idx, true);
        }
        //根据实际情况，统计前要先根据format整理好小数位数，否则会出现显示的数据的累计与最后统计的结果不一致
        me.setupGroupingData(rptTpl, dataObj, $CURRENT_RPT);
        if (followTabEx) {
            followTabEx.setupGroupingData(rptTpl, dataObj, $CURRENT_RPT);
        }
        me.sumSeg(dataObj, $CURRENT_RPT); //考虑到实际会有离散指标的汇总，这些离散指标数据是通过计算式后得来的，这种情况下，不适宜在sorting阶段进行汇总统计，现统一挪到这里处理
        const bands = JpcBand.createNew(rptTpl, defProperties);
        if (me.paging_option === JV.PAGING_OPTION_INFINITY) {
            rst = me.segments.length;
            const pageStatus = [true, true, false, true, true, true, true, true];
            const grpPageInfo: any = {};
            let pageIdx = 0;
            for (let segIdx = 0; segIdx < me.segments.length; segIdx++) {
                // 备注：有break flow的情况下 连续输出 要考虑段(seg)的多页输出问题
                if (segIdx === me.segments.length - 1) {
                    pageStatus[JV.STATUS_REPORT_END] = true;
                }
                if (segIdx > 0) {
                    pageStatus[JV.STATUS_REPORT_START] = false;
                }
                const grpSeqInfo = (me.group_node_info) ? me.group_node_info[segIdx] : null;
                const grpRecAmt = (grpSeqInfo) ? (grpSeqInfo.length * me.group_lines_amt) : 0;
                grpPageInfo.segGrpRecStartIdx = 0;
                grpPageInfo.insertedGrpRecAmt = 0;
                grpPageInfo.preAddPageGrpInfo = [];
                grpPageInfo.group_lines_amt = me.group_lines_amt;
                JpcBandHelper.setBandArea(bands, rptTpl, pageStatus, !me.isEx, me.isEx);
                maxRowRec = JpcFlowTabHelper.getMaxRowsPerPage(bands, rptTpl, me.isEx);
                me.setupAutoHeightData(bands, segIdx, rptTpl, dataObj, $CURRENT_RPT, defProperties);
                let adHocAutoHeightAmt = 0;
                if (me.auto_height_info.length > 0) {
                    for (let loop = 0; loop < me.auto_height_info[segIdx].length; loop++) {
                        adHocAutoHeightAmt += (me.auto_height_info[segIdx][loop] - 1);
                    }
                }
                me.pageStatusLst.push(pageStatus.slice(0));
                pageIdx++;
                const rowAmt = Math.max(maxRowRec, me.segments[segIdx].length + adHocAutoHeightAmt);
                _addPageValue(me.dispValueIdxLst, me.segments[segIdx], grpSeqInfo, 0, rowAmt, me.page_seg_map, segIdx, pageIdx, grpPageInfo, false, me.auto_height_info, 0);
            }
            //目前不支持flowTabEx
        } 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 (current_flow_info.多列显示数量) {
                me.multiCols = 1 * current_flow_info.多列显示数量;
            }
            let grpPageInfo: any = {};
            let prePageLeftAutoHeightRecAmt = 0; //考虑自动行高的跨页情况
            function private_resetBandArea() {
                JpcBandHelper.setBandArea(bands, rptTpl, pageStatus, !me.isEx, me.isEx);
                maxRowRec = JpcFlowTabHelper.getMaxRowsPerPage(bands, rptTpl, me.isEx);
            }
            let handledRowAmt = 0; //handledRowAmt纪录的是真正处理过的显示行数，包含了空白行，主要是为分页用（自动行高）
            let segRestRecAmt = 0; //一般情况下为0，只有在特殊情况下才需要，如09-x表中，正常流水一页显示不了的时候，就有大问题了
            function private_addPage(segIdx: number, grpSeqInfo: any, isFollow: boolean, isMix: boolean, mixSplitPoint: number) {
                private_resetBandArea();
                me.pageStatusLst.push(pageStatus.slice(0));
                currentRecAmt += maxRowRec; //在自动行高的场景下，currentRecAmt在后面还需要调整
                handledRowAmt += maxRowRec;
                let redundantRecAmt = 0;
                pageIdx++;
                function private_chk_handle_rec_amt(dv: any[], isEx: boolean) {
                    if ((dv[1] === JV.DISPLAY_VAL_TYPE_NORMAL) || (dv[1] === JV.DISPLAY_VAL_TYPE_AUTO_HEIGHT && dv[3] === dv[4] - 1)) {
                        if (isEx) { counterRowRecEx++ } else counterRowRec++;
                    } else if (dv[1] === JV.DISPLAY_VAL_TYPE_AUTO_HEIGHT) {
                        redundantRecAmt++;
                    }
                }
                let restRecAmt = 0;
                if (isMix) {
                    //先处理上半部分
                    prePageLeftAutoHeightRecAmt = _addPageValue(me.dispValueIdxLst, me.segments[segIdx], grpSeqInfo, counterRowRec, mixSplitPoint, me.page_seg_map, segIdx, pageIdx, grpPageInfo, false, me.auto_height_info, prePageLeftAutoHeightRecAmt);
                    for (let dv of me.dispValueIdxLst[me.dispValueIdxLst.length - 1]) {
                        private_chk_handle_rec_amt(dv, false);
                    }
                    //再处理下半部分
                    restRecAmt = maxRowRec - me.dispValueIdxLst[me.dispValueIdxLst.length - 1].length; //备注：在一些极端条件下，mixSplitPoint这个分割点不合适处理下半部分数据，以实际生成的value-index数量为准
                    _addPageValue(me.dispValueIdxLst, followTabEx.segments[segIdx], null, counterRowRecEx, restRecAmt, me.page_seg_map, segIdx, pageIdx, null, true, null, 0);
                    for (let dv of me.dispValueIdxLst[me.dispValueIdxLst.length - 1]) {
                        private_chk_handle_rec_amt(dv, true);
                    }
                    //合并到一页中
                    me.page_seg_map.splice(me.page_seg_map.length - 1, 1);
                    let vl = me.dispValueIdxLst[me.dispValueIdxLst.length - 2];
                    for (let item of me.dispValueIdxLst[me.dispValueIdxLst.length - 1]) {
                        vl.push(item);
                    }
                    me.dispValueIdxLst.splice(me.dispValueIdxLst.length - 1, 1);
                } else if (isFollow) {
                    prePageLeftAutoHeightRecAmt = _addPageValue(me.dispValueIdxLst, followTabEx.segments[segIdx], null, counterRowRecEx, maxRowRec, me.page_seg_map, segIdx, pageIdx, null, true, null, 0);
                    for (let dv of me.dispValueIdxLst[me.dispValueIdxLst.length - 1]) {
                        private_chk_handle_rec_amt(dv, true);
                    }
                } else {
                    prePageLeftAutoHeightRecAmt = _addPageValue(me.dispValueIdxLst, me.segments[segIdx], grpSeqInfo, counterRowRec, maxRowRec, me.page_seg_map, segIdx, pageIdx, grpPageInfo, false, me.auto_height_info, prePageLeftAutoHeightRecAmt);
                    for (let dv of me.dispValueIdxLst[me.dispValueIdxLst.length - 1]) {
                        private_chk_handle_rec_amt(dv, false);
                    }
                }
                currentRecAmt -= redundantRecAmt; //在自动行高调整场景下，需要减去冗余的数量
                if (restRecAmt < 0) {
                    currentRecAmt -= restRecAmt;
                    segRestRecAmt = restRecAmt;
                }
            }
            for (let segIdx = 0; segIdx < me.segments.length; segIdx++) {
                let grpSeqInfo = (me.group_node_info) ? me.group_node_info[segIdx] : null;
                let grpRecAmt = (grpSeqInfo) ? (grpSeqInfo.length * me.group_lines_amt) : 0;
                let grpRecAmtEx = 0;
                let accAutoHeightAmt = 0; //累计的自动行高数量
                handledRowAmt = 0; //初始化每一段的已处理纪录行数
                segRestRecAmt = 0;
                if (followTabEx && followTabEx.group_node_info) {
                    grpRecAmtEx = followTabEx.group_node_info.length * followTabEx.group_lines_amt;
                }
                grpPageInfo.segGrpRecStartIdx = 0;
                grpPageInfo.insertedGrpRecAmt = 0;
                grpPageInfo.preAddPageGrpInfo = [];
                grpPageInfo.group_lines_amt = me.group_lines_amt;
                pageStatus[JV.STATUS_SEGMENT_START] = true;
                private_resetBandArea();
                me.setupAutoHeightData(bands, segIdx, rptTpl, dataObj, $CURRENT_RPT, defProperties);
                let threshold = 0;
                currentRecAmt = 0;
                counterRowRec = 0;
                counterRowRecEx = 0;
                let ttlSegRecAmtNormal = me.segments[segIdx].length + grpRecAmt; //正常的segment下的数据长度累计(含grouping data)
                let ttlSegRecAmt = (followTabEx) ? (me.segments[segIdx].length + grpRecAmt + followTabEx.segments[segIdx].length + grpRecAmtEx) : (me.segments[segIdx].length + grpRecAmt); //所有的segment下的数据长度累计(包括ex部分)
                let adHocAutoHeightAmt = 0;
                let normalContentAmt = 0;
                let exBuffer = 0;
                let adHocAutoHeightGrpStartIdx = 0;
                if (me.auto_height_fields_idx.length > 0) {
                    for (let loop = 0; loop < me.auto_height_info[segIdx].length; loop++) {
                        adHocAutoHeightAmt += (me.auto_height_info[segIdx][loop] - 1);
                        normalContentAmt++;
                        if (me.group_node_info && me.group_node_info[segIdx]) {
                            if (me.group_node_info[segIdx][adHocAutoHeightGrpStartIdx] === loop) {
                                adHocAutoHeightGrpStartIdx++;
                            }
                        }
                    }
                    ttlSegRecAmtNormal += adHocAutoHeightAmt;
                    ttlSegRecAmt += adHocAutoHeightAmt;
                    if (adHocAutoHeightAmt > 0) exBuffer = grpRecAmt;
                }
                //自动行高调整在多流水合并方式时，只支持前部分(后期需要再加)
                while (true) {
                    if (currentRecAmt > 0) pageStatus[JV.STATUS_SEGMENT_START] = false;
                    if (pageIdx > 0) pageStatus[JV.STATUS_REPORT_START] = false;
                    private_resetBandArea(); // 这里得预先算maxRowRec（实际数据情况，会有章首页框，在章数据多的情况下，章第二页开始就得补上章首页框不显示遗留下来的row）
                    //开始判断各种scenarios
                    adHocAutoHeightAmt = 0;
                    if (me.auto_height_fields_idx.length > 0) {
                        adHocAutoHeightAmt -= prePageLeftAutoHeightRecAmt;
                        //for (let loop = currentRecAmt; loop < me.auto_height_info[segIdx].length; loop++) {
                        for (let loop = currentRecAmt; loop < currentRecAmt + maxRowRec; loop++) {
                            if (me.auto_height_info[segIdx].length > loop) {
                                adHocAutoHeightAmt += (me.auto_height_info[segIdx][loop] - 1);
                            } else {
                                break;
                            }
                        }
                    }
                    if ((ttlSegRecAmtNormal < ttlSegRecAmt) || (followTabEx !== null)) {
                        //有流水拓展，并且是follow mode
                        if (currentRecAmt + accAutoHeightAmt + exBuffer + maxRowRec > ttlSegRecAmtNormal) {
                            // if (currentRecAmt + accAutoHeightAmt + adHocAutoHeightAmt + maxRowRec > ttlSegRecAmtNormal) {
                            // if (currentRecAmt + adHocAutoHeightAmt >= ttlSegRecAmtNormal) {
                            if (currentRecAmt + accAutoHeightAmt + adHocAutoHeightAmt >= ttlSegRecAmtNormal) {
                                //纯 followTabEx 数据
                                // if (currentRecAmt + adHocAutoHeightAmt + maxRowRec >= ttlSegRecAmt) {
                                if (currentRecAmt + accAutoHeightAmt + adHocAutoHeightAmt + maxRowRec >= ttlSegRecAmt) {
                                    pageStatus[JV.STATUS_SEGMENT_END] = true;
                                    private_resetBandArea();
                                    let hasAdHocRow = !JpcFlowTabHelper.chkSegEnd(bands, rptTpl, ttlSegRecAmt, currentRecAmt + adHocAutoHeightAmt, maxRowRec, me.isEx);
                                    if (hasAdHocRow) {
                                        //add page info(pre segment end)
                                        pageStatus[JV.STATUS_SEGMENT_END] = false;
                                        private_addPage(segIdx, null, true, false, -1);
                                    }
                                    //add page info
                                    pageStatus[JV.STATUS_SEGMENT_END] = true;
                                    private_addPage(segIdx, null, true, false, -1);
                                } else {
                                    private_addPage(segIdx, null, true, false, -1);
                                }
                            } else {
                                //混合数据
                                // if (currentRecAmt + adHocAutoHeightAmt + maxRowRec >= ttlSegRecAmt) {
                                if (currentRecAmt + accAutoHeightAmt + adHocAutoHeightAmt + maxRowRec >= ttlSegRecAmt) {
                                    pageStatus[JV.STATUS_SEGMENT_END] = true;
                                    private_resetBandArea();
                                    let hasAdHocRow = !JpcFlowTabHelper.chkSegEnd(bands, rptTpl, ttlSegRecAmt, currentRecAmt + adHocAutoHeightAmt, maxRowRec, me.isEx);
                                    if (hasAdHocRow) {
                                        //add page info(pre segment end)
                                        pageStatus[JV.STATUS_SEGMENT_END] = false;
                                        private_addPage(segIdx, grpSeqInfo, false, true, ttlSegRecAmtNormal);
                                    }
                                    //add page info
                                    pageStatus[JV.STATUS_SEGMENT_END] = true;
                                    // if (currentRecAmt + adHocAutoHeightAmt >= ttlSegRecAmtNormal) {
                                    if (currentRecAmt + accAutoHeightAmt + adHocAutoHeightAmt >= ttlSegRecAmtNormal) {
                                        //纯 followTabEx 数据啦
                                        private_addPage(segIdx, null, true, false, -1);
                                    } else {
                                        // private_addPage(segIdx, grpSeqInfo, false, true, ttlSegRecAmtNormal);
                                        //在这里要考虑如果有多页正常的流水数据情况，那么就得考虑这页有多少条普通流水记录，不应该一刀切地用ttlSegRecAmtNormal
                                        let splitPoint = ttlSegRecAmtNormal - handledRowAmt ;
                                        private_addPage(segIdx, grpSeqInfo, false, true, splitPoint);
                                    }
                                } else {
                                    //在这里要考虑如果有多页正常的流水数据情况，那么就得考虑这页有多少条普通流水记录，不应该一刀切地用ttlSegRecAmtNormal
                                    let splitPoint = ttlSegRecAmtNormal - handledRowAmt;
                                    // if (splitPoint > (exBuffer + maxRowRec)) {
                                    //     splitPoint = splitPoint % (exBuffer + maxRowRec);
                                    // }
                                    private_addPage(segIdx, grpSeqInfo, false, true, splitPoint);
                                }
                            }
                        } else {
                            //纯followTab数据
                            private_addPage(segIdx, grpSeqInfo, false, false, -1);
                        }
                    } else {
                        //普通流水数据情况
                        if (handledRowAmt + maxRowRec >= ttlSegRecAmt) {
                            //备注： 理论上自动行高是没有上限的，有可能正常一页的数据可以拓展到3页及以上，在此极端情况下，必须做一些限制判断，否则会出现缺页情况。
                            // 2018-08-04 其实之前的判断逻辑完全是自找麻烦，而且还不够正确。其实只需要判断已经处理了多少行纪录(所有的都算，包括空白行)，
                            // 与总的seg纪录数想比较，就很容易得到结果，而且能处理极端边界的情况。
                            pageStatus[JV.STATUS_SEGMENT_END] = true;
                            // pageStatus[JV.STATUS_REPORT_END] = true;
                            pageStatus[JV.STATUS_REPORT_END] = (segIdx === me.segments.length - 1);
                            private_resetBandArea();
                            let hasAdHocRow = ((adHocAutoHeightAmt > maxRowRec) || !JpcFlowTabHelper.chkSegEnd(bands, rptTpl, ttlSegRecAmt, handledRowAmt, maxRowRec, me.isEx));
                            // !JpcFlowTabHelper.chkSegEnd(bands, rptTpl, ttlSegRecAmt, currentRecAmt + adHocAutoHeightAmt, maxRowRec, me.isEx));

                            if (hasAdHocRow) {
                                //add page info(pre segment end)
                                pageStatus[JV.STATUS_SEGMENT_END] = false;
                                pageStatus[JV.STATUS_REPORT_END] = false;
                                private_addPage(segIdx, grpSeqInfo, false, false, -1);
                                pageStatus[JV.STATUS_REPORT_START] = false;
                                pageStatus[JV.STATUS_SEGMENT_START] = false;
                            }
                            //add page info
                            pageStatus[JV.STATUS_SEGMENT_END] = true;
                            pageStatus[JV.STATUS_REPORT_END] = (segIdx === me.segments.length - 1);
                            private_addPage(segIdx, grpSeqInfo, false, false, -1);
                            pageStatus[JV.STATUS_SEGMENT_END] = false; // 加完章统计页后，记得把章尾页设置为false
                        } else {
                            private_addPage(segIdx, grpSeqInfo, false, false, -1);
                        }
                    }
                    //检测是否可退出
                    // if ((currentRecAmt + accAutoHeightAmt + adHocAutoHeightAmt >= ttlSegRecAmt) && (pageIdx % me.multiCols === 0)) {
                    if (handledRowAmt >= (ttlSegRecAmt + segRestRecAmt) && (pageIdx % me.multiCols === 0)) {
                        //备注：这里必须得考虑多栏的情况，否则会造成pageStatus出界的问题
                        break;
                    }
                    accAutoHeightAmt += adHocAutoHeightAmt;
                    //控制阈值，超过阈值则强制退出，防止死循环
                    threshold++;
                    if (threshold > 1000) {
                        console.log("Hey! There may be a dead loop here!!!");
                        break;
                    }
                }
            }
            // console.log(me.auto_height_info);
            // console.log(me.dispValueIdxLst);
            rst = Math.ceil(pageIdx / me.multiCols);
        }
        me.pagesAmt = rst;
        return rst;
    };
    outputAsPreviewPage(rptTpl: IRptTpl, bands: IBands, controls: IControlCollection, $CURRENT_RPT: ICurrent_RPT) {
        let me = this, rst: any[] = [], vIdx = [];
        //只预览第一页的数据
        let pageStatus = [true, true, true, true, true, true, true, true];
        me.pageStatusLst.push(pageStatus);
        JpcFieldHelper.findAndPutDataFieldIdx(rptTpl, rptTpl.流水式表_信息.流水式表_数据.flow_field_s, null, me.disp_fields_idx, false);
        JpcBandHelper.setBandArea(bands, rptTpl, pageStatus, true, false);
        let maxRowRec = JpcFlowTabHelper.getMaxRowsPerPage(bands, rptTpl, false);
        for (let i = 0; i < maxRowRec; i++) {
            vIdx.push([-1, JV.DISPLAY_VAL_TYPE_NORMAL, JV.BLANK_VALUE_INDEX]);
        }
        let unitFactor = JpcCommonHelper.getUnitFactor(rptTpl);
        // 2.2 Column tab
        rst = rst.concat(me.outputColumn(rptTpl, null, 1, 0, bands, unitFactor, 0, $CURRENT_RPT, null));
        // 2.1 Content-Tab
        rst = rst.concat(me.outputPreviewContent(rptTpl, bands, unitFactor, controls, pageStatus, maxRowRec));
        // 2.3 Sum Seg
        rst = rst.concat(me.outputPreviewSegSum(rptTpl, bands, unitFactor, controls, pageStatus));
        // 2.4 Sum Page
        rst = rst.concat(me.outputPreviewPageSum(rptTpl, bands, unitFactor, controls, pageStatus));
        // 2.5 Group
        // 2.6 Discrete
        rst = rst.concat(JpcDiscreteHelper.outputPreviewDiscreteInfo(rptTpl.流水式表_信息.离散信息, bands, unitFactor, pageStatus));
        return rst;
    };
    outputPreviewContent(rptTpl: IRptTpl, bands: IBands, unitFactor: number, controls: IControlCollection, pageStatus: boolean[], maxRec: number) {
        let me = this, rst = [];
        let tab = rptTpl.流水式表_信息.流水式表_数据;
        let band = bands[tab.BandName];
        if (band) {
            if (pageStatus[(band.DisplayType) as number]) {
                let tab_fields = tab.flow_field_s;
                for (let rowIdx = 0; rowIdx < maxRec; rowIdx++) {
                    for (let i = 0; i < tab_fields.length; i++) {
                        let tab_field = tab_fields[i];
                        if (!(tab_field.Hidden)) {
                            rst.push(me.outputTabField(band, tab_field, null, -1, -1, maxRec, rowIdx, 1, 0, unitFactor, false, controls, 0));
                        }
                    }
                }
            }
        }
        return rst;
    };
    outputPreviewSegSum(rptTpl: IRptTpl, bands: IBands, unitFactor: number, controls: IControlCollection, pageStatus: boolean[]) {
        let rst: any[] = [];
        let tab = rptTpl.流水式表_信息.流水式表_段统计信息;
        let band = bands[tab.BandName];
        if (band) {
            if (pageStatus[(band.DisplayType) as number]) {
                rst = rst.concat(JpcDiscreteHelper.outputPreviewSumInfoOutput(band, unitFactor, tab));
            }
        }
        return rst;
    };
    outputPreviewPageSum(rptTpl: IRptTpl, bands: IBands, unitFactor: number, controls: IControlCollection, pageStatus: boolean[]) {
        let rst: any[] = [];
        let tab = rptTpl.流水式表_信息.流水式表_页统计信息;
        let band = bands[tab.BandName];
        if (band) {
            if (pageStatus[(band.DisplayType) as number]) {
                rst = rst.concat(JpcDiscreteHelper.outputPreviewSumInfoOutput(band, unitFactor, tab));
            }
        }
        return rst;
    };
    outputAsSimpleJSONPage(rptTpl: IRptTpl, dataObj: IDataObj, page: number, bands: IBands, controls: IControlCollection, adHocMergePos: IMergePos, $CURRENT_RPT: ICurrent_RPT, customizeCfg: ICustomizeCfg) {
        let me = this, rst: any[] = [], tabRstLst = [];
        // let FLOW_NODE_STR = me.isEx?'流水式表_拓展信息':'流水式表_信息';
        let flow_node_str = me.isEx ? rptTpl.流水式表_拓展信息 : rptTpl.流水式表_信息;
        let unitFactor = JpcCommonHelper.getUnitFactor(rptTpl);
        if (me.paging_option === "infinity") {
            const segIdx = page - 1;
            // 1 calculate the band position
            JpcBandHelper.setBandArea(bands, rptTpl, me.pageStatusLst[page - 1], !me.isEx, me.isEx);
            const maxRowRec = JpcFlowTabHelper.getMaxRowsPerPage(bands, rptTpl, me.isEx);
            // 2. then reset the band height
            const tab = rptTpl.流水式表_信息.流水式表_数据;
            const flowContentBand = bands[tab.BandName];
            let adHocAutoHeightAmt = 0;
            if (me.auto_height_info.length > 0) {
                for (let loop = 0; loop < me.auto_height_info[segIdx].length; loop++) {
                    adHocAutoHeightAmt += (me.auto_height_info[segIdx][loop] - 1);
                }
            }
            const rowAmt = Math.max(maxRowRec, me.segments[segIdx].length + adHocAutoHeightAmt); // 如不满一页，则需要填充满一页
            const actH = JpcFlowTabHelper.getActualContentAreaHeight(bands, rptTpl, me.segments, rowAmt, page, me.isEx);
            const offsetY = actH - (flowContentBand.Bottom - flowContentBand.Top);
            JpcBandHelper.resetBandPos(rptTpl.布局框_集合, bands, flowContentBand, 0, offsetY);
            // 2.1 Content-Tab
            tabRstLst.push(me.outputContent(rptTpl, dataObj, page, bands, unitFactor, controls, 0, $CURRENT_RPT, customizeCfg));
            // 2.2 Column tab
            tabRstLst.push(me.outputColumn(rptTpl, dataObj, page, segIdx, bands, unitFactor, 0, $CURRENT_RPT, customizeCfg));
            // 2.3 Sum Seg
            tabRstLst.push(me.outputSegSum(rptTpl, dataObj, page, segIdx, bands, unitFactor, controls, $CURRENT_RPT, customizeCfg));
            // 2.4 Sum Page
            tabRstLst.push(me.outputPageSum(rptTpl, dataObj, page, segIdx, bands, unitFactor, controls, $CURRENT_RPT, customizeCfg));
            // 2.5 Group
            // 2.6 Discrete
            tabRstLst.push(JpcDiscreteHelper.outputDiscreteInfo(flow_node_str.离散信息, bands, dataObj, unitFactor, me.pageStatusLst[page - 1], segIdx, 1, 0, $CURRENT_RPT, customizeCfg));
            // 3. reset merge band position
            if (bands.MergeBand && adHocMergePos) {
                const mergedBand = bands.MergeBand;
                let arr = [];
                arr.push(parseInt(mergedBand.Left.toFixed(0)));
                adHocMergePos.Left = arr;
                arr = [];
                arr.push(parseInt(mergedBand.Right.toFixed(0)));
                adHocMergePos.Right = arr;
                arr = [];
                arr.push(parseInt(mergedBand.Top.toFixed(0)));
                adHocMergePos.Top = arr;
                arr = [];
                arr.push(parseInt((mergedBand.Bottom).toFixed(0)));
                adHocMergePos.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, customizeCfg));
                // 2.2 Column tab
                tabRstLst.push(me.outputColumn(rptTpl, dataObj, actualPage, segIdx, bands, unitFactor, pi, $CURRENT_RPT, customizeCfg));
                // 2.3 Sum Seg
                tabRstLst.push(me.outputSegSum(rptTpl, dataObj, actualPage, segIdx, bands, unitFactor, controls, $CURRENT_RPT, customizeCfg));
                // 2.4 Sum Page
                tabRstLst.push(me.outputPageSum(rptTpl, dataObj, actualPage, segIdx, bands, unitFactor, controls, $CURRENT_RPT, customizeCfg));
                // 2.5 Group
                // 2.6 Discrete
                if (pi === 0) {
                    tabRstLst.push(JpcDiscreteHelper.outputDiscreteInfo(flow_node_str.离散信息, bands, dataObj, unitFactor, me.pageStatusLst[actualPage - 1], segIdx, 1, pi, $CURRENT_RPT, customizeCfg));
                }
            }
        }
        for (let i = 0; i < tabRstLst.length; i++) {
            rst = rst.concat(tabRstLst[i]);
            tabRstLst[i] = null;
        }
        return rst;
    };
    outputContent(rptTpl: IRptTpl, dataObj: IDataObj, page: number, bands: IBands, unitFactor: number, controls: IControlCollection, multiColIdx: number, $CURRENT_RPT: ICurrent_RPT, customizeCfg: ICustomizeCfg) {
        let me = this, rst: any[] = [], prepareObj =<IPageAreaObj>{};
        // let FLOW_NODE_STR = me.isEx?'流水式表_拓展信息':'流水式表_信息';
        let flow_node_str = me.isEx ? rptTpl.流水式表_拓展信息 : rptTpl.流水式表_信息;
        let tab = flow_node_str.流水式表_数据;
        let tabEx = (rptTpl.流水式表_拓展信息) ? rptTpl.流水式表_拓展信息.流水式表_数据 : null;
        let verticalCombinePos = [], horizonCombinePos = []; //合并特性用
        let band = bands[tab.BandName];
        if (band) {
            let pageStatus = me.pageStatusLst[page - 1];
            if (pageStatus[(band.DisplayType) as number]) {
                let tab_fields = tab.flow_field_s;
                let tab_fields_ex = tabEx ? tabEx.flow_field_s : null;
                let data_details = me.isEx ? dataObj.detail_data_ex : dataObj.detail_data;
                let data_details_ex = $CURRENT_RPT.isFollowMode ? dataObj.detail_data_ex : null;
                let contentValuesIdx = me.dispValueIdxLst[page - 1];
                let page_sum_data_fields = [];
                for (let i = 0; i < me.page_sum_fields_idx.length; i++) {
                    if (typeof (me.page_sum_fields_idx[i]) === "object") {
                        let exField = JE.F(me.page_sum_fields_idx[i][JV.PROP_ID], $CURRENT_RPT);
                        if (exField) {
                            page_sum_data_fields.push(exField.data_field);
                        } else {
                            page_sum_data_fields.push(null);
                        }
                    } else {
                        let data_field = data_details[me.page_sum_fields_idx[i]];
                        page_sum_data_fields.push(data_field);
                    }
                }
                let rowGrandTotal = [];
                for (let di = 0; di < page_sum_data_fields.length; di++) {
                    rowGrandTotal.push(0.0);
                }
                //normal content
                let flexiblePrecisionRefObj: any = null, flexibleRefField = null, precision_ref_data = null;
                for (let rowIdx = 0; rowIdx < contentValuesIdx.length; rowIdx++) {
                    for (let fieldIdx = 0; fieldIdx < tab_fields.length; fieldIdx++) {
                        let tab_field = tab_fields[fieldIdx];
                        let data_field = null,
                            map_data_field = JE.F(tab_field.FieldID, $CURRENT_RPT);
                        if (me.disp_fields_idx[fieldIdx] !== JV.BLANK_FIELD_INDEX && (typeof me.disp_fields_idx[fieldIdx] !== 'object')) {
                            data_field = data_details[me.disp_fields_idx[fieldIdx]];
                        } else {
                            if (map_data_field) {
                                data_field = map_data_field.data_field;
                            }
                        }
                        if (map_data_field && map_data_field.Precision && map_data_field.flexiblePrecisionRefObj) {
                            if (flexiblePrecisionRefObj === null) {
                                flexiblePrecisionRefObj = {};
                                if (map_data_field.Precision.flexibleRefFieldID)
                                    flexibleRefField = JE.F(map_data_field.Precision.flexibleRefFieldID, $CURRENT_RPT);
                                if (flexibleRefField) 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][2], customizeCfg);
                        } else {
                            if (rowIdx === 0) JpcFieldHelper.resetFormat(tab_field, map_data_field, customizeCfg);
                        }
                        if (!(tab_field.Hidden)) {
                            if (contentValuesIdx[rowIdx][0] !== JV.TYPE_FOLLOW_MODE && contentValuesIdx[rowIdx][1] === JV.DISPLAY_VAL_TYPE_NORMAL) {
                                rst.push(me.outputTabField(band, tab_field, data_field, contentValuesIdx[rowIdx][2], -1, contentValuesIdx.length, rowIdx, 1, 0, unitFactor, false, controls, multiColIdx));
                            } else if (contentValuesIdx[rowIdx][1] === JV.DISPLAY_VAL_TYPE_AUTO_HEIGHT) {
                                if (contentValuesIdx[rowIdx][4] === 1) {
                                    //等效于普通输出
                                    rst.push(me.outputTabField(band, tab_field, data_field, contentValuesIdx[rowIdx][2], -1, contentValuesIdx.length, rowIdx, 1, 0, unitFactor, false, controls, multiColIdx));
                                } else {
                                    //这里需要做些style调整(中间的那些横杠线去掉)
                                    let cellItem = me.outputAutoHeightTabField(band, tab_field, data_field, contentValuesIdx[rowIdx], contentValuesIdx.length, rowIdx, 1, 0, unitFactor, true, controls, multiColIdx);
                                    rst.push(cellItem);
                                    if (contentValuesIdx[rowIdx][3] === 0 || rowIdx === 0) {
                                        cellItem.style = cellItem.style + '_AutoHeightMerge_Top';
                                    } else if (contentValuesIdx[rowIdx][3] === contentValuesIdx[rowIdx][4] - 1) {
                                        cellItem.style = cellItem.style + '_AutoHeightMerge_Bottom';
                                    } else {
                                        cellItem.style = cellItem.style + '_AutoHeightMerge_Middle';
                                    }
                                    prepareAutoHeightCells(prepareObj, cellItem, rst.length - 1, rst);
                                }
                            }
                        }
                        if (rowIdx === 0 && tab_field.combineType !== undefined && tab_field.combineType !== null) {
                            let rstCellItem = rst[rst.length - 1];
                            let cbfPos = [];
                            cbfPos.push(rstCellItem.area.Left);
                            cbfPos.push(rstCellItem.area.Right);
                            if (tab_field.combineType === 'vertical') {
                                verticalCombinePos.push(cbfPos);
                            } else if (tab_field.combineType === 'horizon') {
                                horizonCombinePos.push(cbfPos);
                            }
                        }
                    }
                    if (tab_fields_ex && contentValuesIdx[rowIdx][0] === 1) {
                        for (let idx_ex = 0; idx_ex < tab_fields_ex.length; idx_ex++) {
                            let tab_fieldex = tab_fields_ex[idx_ex];
                            let data_fieldex = null, map_data_fieldex = JE.F(tab_fieldex.FieldID, $CURRENT_RPT);
                            if (data_details_ex && me.disp_fields_ex_idx[idx_ex] !== JV.BLANK_FIELD_INDEX && (typeof me.disp_fields_ex_idx[idx_ex] !== 'object')) {
                                data_fieldex = data_details_ex[me.disp_fields_ex_idx[idx_ex]];
                            } else {
                                if (map_data_fieldex) {
                                    data_fieldex = map_data_fieldex.data_field;
                                }
                            }
                            if (map_data_fieldex && map_data_fieldex.Precision && map_data_fieldex.flexiblePrecisionRefObj) {
                                if (flexiblePrecisionRefObj === null) {
                                    flexiblePrecisionRefObj = {};
                                    if (map_data_fieldex.Precision.flexibleRefFieldID)
                                        flexibleRefField = JE.F(map_data_fieldex.Precision.flexibleRefFieldID, $CURRENT_RPT);
                                    for (let decimalObj of map_data_fieldex.flexiblePrecisionRefObj) {
                                        flexiblePrecisionRefObj["refUnit_" + decimalObj.unit] = decimalObj.decimal;
                                    }
                                }
                                JpcFieldHelper.resetFlexibleFormat(tab_fieldex, flexibleRefField, flexiblePrecisionRefObj, contentValuesIdx[rowIdx][2], customizeCfg);
                            } else {
                                if (rowIdx === 0) JpcFieldHelper.resetFormat(tab_fieldex, map_data_fieldex, customizeCfg);
                            }
                            if (!(tab_fieldex.Hidden)) {
                                if (contentValuesIdx[rowIdx][0] === 1 && contentValuesIdx[rowIdx][1] === 0) {
                                    rst.push(me.outputTabField(band, tab_fieldex, data_fieldex, contentValuesIdx[rowIdx][2], -1, contentValuesIdx.length, rowIdx, 1, 0, unitFactor, false, controls, multiColIdx));
                                }
                            }
                        }
                    }
                    //page sum content
                    for (let di = 0; di < page_sum_data_fields.length; di++) {
                        if (contentValuesIdx[rowIdx][1] === 0 ||
                            contentValuesIdx[rowIdx][1] === 2 && contentValuesIdx[rowIdx][3] === 0) {
                            let precisionAmt = 4;
                            let sum_field = JE.F(me.page_sum_tab_fields[di].FieldID, $CURRENT_RPT);
                            if (sum_field && sum_field.Precision && sum_field.Precision.type === `fixed`) {
                                precisionAmt = sum_field.fixedPrecisionNum;
                            } else {
                                let flowF = me.page_sum_tab_fields[di];
                                if (flowF && !strUtil.isEmptyString(flowF.Format)) {
                                    let idx = flowF.Format.indexOf('.');
                                    if (idx >= 0) {
                                        precisionAmt = flowF.Format.length - idx - 1;
                                    }
                                }
                            }
                            // rowGrandTotal[di] = rowGrandTotal[di] + 1.0 * JpcFieldHelper.getValue(page_sum_data_fields[di], contentValuesIdx[rowIdx][2]);
                            if (contentValuesIdx[rowIdx][2] >= 0) {
                                let psv = JpcFieldHelper.getValue(page_sum_data_fields[di], contentValuesIdx[rowIdx][2]);
                                if (psv) {
                                    rowGrandTotal[di] = rowGrandTotal[di] + parseFloat(parseFloat(psv).toFixed(precisionAmt));
                                }
                            }
                        }
                    }
                }
                me.pageSumValLst.push(rowGrandTotal);
                //grouping content
                let grpCntIdx = 0;
                for (let rowIdx = 0; rowIdx < contentValuesIdx.length; rowIdx++) {
                    if (contentValuesIdx[rowIdx][1] === 1) {
                        for (let grpIdx = 0; grpIdx < flow_node_str.流水式表_分组信息.group_lines.length; grpIdx++) {
                            if (contentValuesIdx[rowIdx][3] === grpIdx) {
                                let grp_line = flow_node_str.流水式表_分组信息.group_lines[grpIdx];
                                if (page === 1) {
                                    if (grp_line.SumKey_S && grp_line.SumKey_S.length > 0) {
                                        for (let grp_sum_field of grp_line.SumKey_S) {
                                            if (grp_sum_field.FieldID) {
                                                let map_field = JE.F(grp_sum_field.FieldID, $CURRENT_RPT);
                                                JpcFieldHelper.resetFormat(grp_sum_field, map_field, customizeCfg);
                                            }
                                        }
                                    }
                                }
                                let lineRst = me.outputTabGrpLine(band, grp_line, page, contentValuesIdx[rowIdx], contentValuesIdx.length, rowIdx, 1, 0, unitFactor, true, controls, multiColIdx, grpCntIdx, $CURRENT_RPT);
                                rst = rst.concat(lineRst);
                            }
                        }
                        grpCntIdx++;
                    }
                }
            }
        }
        //合并自动换行的格子，直接把第一个格子的值一个一个递增为目标值，并且把被合并的格子的id纪录下来，准备在下面进行删除
        //（本来是一行一个格子的，此处通过表示对值进行递增）
        let eliminateCells = combineAutoHeightCells(prepareObj, page, controls);
        for (let idIdx = eliminateCells.length - 1; idIdx >= 0; idIdx--) {
            rst.splice(eliminateCells[idIdx], 1);
        }
        me.checkCombineEvent(JV.RUN_TYPE_BEFORE_COMBINE, verticalCombinePos, horizonCombinePos, rst, $CURRENT_RPT);
        me.combinePageCells(rst, verticalCombinePos, horizonCombinePos);
        me.checkCombineEvent(JV.RUN_TYPE_AFTER_COMBINE, verticalCombinePos, horizonCombinePos, rst, $CURRENT_RPT);
        return rst;
    };
    combinePageCells(rstPageCells: ICell[], verticalCombinePos: number[][], horizonCombinePos: number[][]) {
        // let me = this;
        //备注：纵向合并要考虑以下因素：
        //     如果有多个column纵向合并，需要总体考虑分割，
        //     假如：第一列的前3个数据(1、2、3)是相同的，第二列中第2、3、4行数据相同，那么第二列只能合并2、3行的数据，不能合并到第四行
        //     同理如此类推第三列...n列
        if (verticalCombinePos.length > 0 || horizonCombinePos.length > 1) {
            let cacheObj: any = { vCache: {}, hCache: {}, hCacheStr: [] };
            let removeCellIds = [];
            for (let vPosArr of verticalCombinePos) {
                let pStr = "_" + vPosArr[0] + "_" + vPosArr[1];
                cacheObj.vCache[pStr] = [];
            }
            //horizonCombinePos不需要预记
            for (let idx = 0; idx < rstPageCells.length; idx++) {
                let cell = rstPageCells[idx];
                for (let vPosArr of verticalCombinePos) {
                    if (cell.area.Left === vPosArr[0] && cell.area.Right === vPosArr[1]) {
                        cacheObj.vCache["_" + vPosArr[0] + "_" + vPosArr[1]].push(idx);
                    }
                }
                for (let hPosArr of horizonCombinePos) {
                    if (cell.area.Left === hPosArr[0] && cell.area.Right === hPosArr[1]) {
                        let hpStr = "_" + cell.area.Top + "_" + cell.area.Bottom;
                        if (cacheObj.hCacheStr.indexOf(hpStr) < 0) {
                            cacheObj.hCache[hpStr] = [];
                            cacheObj.hCacheStr.push(hpStr);
                        }
                        cacheObj.hCache[hpStr].push(idx);
                    }
                }
            }
            if (verticalCombinePos.length > 0) {
                let preColMergePosArr: any[] = []; //见上面备注描述，纪录当前列的分割坐标集合情况
                let private_chk_in_pre_merge = function (preIdx: number, newCell: any) {
                    let rst = true;
                    if (preIdx >= 0 && preIdx < preColMergePosArr.length) {
                        for (let mergeArea of preColMergePosArr[preIdx]) {
                            if (newCell.area[JV.PROP_TOP] >= mergeArea[0] && newCell.area[JV.PROP_TOP] < mergeArea[1]) {
                                rst = (newCell.area.Bottom <= mergeArea[1]);
                                break;
                            }
                        }
                    }
                    return rst;
                };
                for (let vidx = 0; vidx < verticalCombinePos.length; vidx++) {
                    let vPosArr = verticalCombinePos[vidx];
                    let pStr = "_" + vPosArr[0] + "_" + vPosArr[1];
                    //rstPageCells的结果已经是按顺序排列了，这里不用再排序
                    if (cacheObj.vCache[pStr] && cacheObj.vCache[pStr].length > 0) {
                        let preCell = rstPageCells[cacheObj.vCache[pStr][0]];
                        if (vidx === 0) {
                            //这里要处理下
                            let minY = 10000, maxY = 0;
                            for (let preCIdx = 0; preCIdx < cacheObj.vCache[pStr].length; preCIdx++) {
                                if (minY > rstPageCells[cacheObj.vCache[pStr][preCIdx]].area.Top) minY = rstPageCells[cacheObj.vCache[pStr][preCIdx]].area.Top;
                                if (maxY < rstPageCells[cacheObj.vCache[pStr][preCIdx]].area.Bottom) maxY = rstPageCells[cacheObj.vCache[pStr][preCIdx]].area.Bottom;
                            }
                            preColMergePosArr.push([[minY, maxY]]);
                        }
                        let dtlColMergePosArr: any[] = [];
                        preColMergePosArr.push(dtlColMergePosArr);
                        for (let cIdx = 1; cIdx < cacheObj.vCache[pStr].length; cIdx++) {
                            if (preCell.Value === "") {
                                dtlColMergePosArr.push([preCell.area.Top, preCell.area.Bottom]);
                                preCell = rstPageCells[cacheObj.vCache[pStr][cIdx]];
                            } else {
                                if (preCell.Value === rstPageCells[cacheObj.vCache[pStr][cIdx]].Value) {
                                    let bkBottom = preCell.area.Bottom;
                                    preCell.area.Bottom = rstPageCells[cacheObj.vCache[pStr][cIdx]].area.Bottom;
                                    if (private_chk_in_pre_merge(vidx, preCell)) {
                                        removeCellIds.push(cacheObj.vCache[pStr][cIdx]);
                                        if (cIdx === cacheObj.vCache[pStr].length - 1) {
                                            dtlColMergePosArr.push([preCell.area.Top, preCell.area.Bottom]);
                                        }
                                    } else {
                                        preCell.area.Bottom = bkBottom;
                                        dtlColMergePosArr.push([preCell.area.Top, preCell.area.Bottom]);
                                        preCell = rstPageCells[cacheObj.vCache[pStr][cIdx]];
                                    }
                                } else {
                                    dtlColMergePosArr.push([preCell.area.Top, preCell.area.Bottom]);
                                    preCell = rstPageCells[cacheObj.vCache[pStr][cIdx]];
                                }
                            }
                        }
                    }
                }
            }
            if (horizonCombinePos.length > 1) {
                if (cacheObj.hCacheStr.length > 0) {
                    for (let hStr of cacheObj.hCacheStr) {
                        let preCell = rstPageCells[cacheObj.hCache[hStr][0]];
                        for (let cIdx = 1; cIdx < cacheObj.hCache[hStr].length; cIdx++) {
                            if (preCell.Value === "") {
                                preCell = rstPageCells[cacheObj.hCache[hStr][cIdx]];
                            } else {
                                if (preCell.Value === rstPageCells[cacheObj.hCache[hStr][cIdx]].Value) {
                                    if (preCell.area.Right < rstPageCells[cacheObj.hCache[hStr][cIdx]].area.Right) {
                                        preCell.area.Right = rstPageCells[cacheObj.hCache[hStr][cIdx]].area.Right;
                                    } else {
                                        preCell.area.Left = rstPageCells[cacheObj.hCache[hStr][cIdx]].area.Left;
                                    }
                                    removeCellIds.push(cacheObj.hCache[hStr][cIdx]);
                                } else {
                                    preCell = rstPageCells[cacheObj.hCache[hStr][cIdx]];
                                }
                            }
                        }
                    }
                }
            }
            if (removeCellIds.length > 0) {
                //排序，保证一定的顺序，不能用默认的方式(默认方式是针对字符串的简单排序)
                removeCellIds.sort(function (idx1, idx2) {
                    return parseInt(idx1) - parseInt(idx2);
                });
                for (let idx = removeCellIds.length - 1; idx >= 0; idx--) {
                    rstPageCells.splice(removeCellIds[idx], 1);
                }
            }
        }
    };
    checkCombineEvent($RUN_TYPE: String, $VER_COMB_ARRAY: number[][], $HOR_COMB_ARRAY: any[], $CURRENT_CELL_ITEMS: ICell[], $CURRENT_RPT: ICurrent_RPT) {
        const {
            $JE,
            $JV,
            P,
            F,
            D,
            L,
            getCurrentPage,
            getTotalPage,
            setFieldValue,
            setFieldValueArray,
            removeFieldValue,
            insertFieldValue,
            setData,
            getNumberArray,
            copyPrecision,
            copyFixedPrecisionNum,
            copyProperty,
            setDate,
            DLength,
            isEmptyString,
            trim,
            leftTrim,
            rightTrim,
            comdify,
            convertToCaptionNum,
            convertStrToBoolean,
            formatNumber,
            reportDate 
        }=$CURRENT_RPT.formulasObject;
        
        
        if ($CURRENT_RPT.formulas) {
            for (let execFmlIdx = 0; execFmlIdx < $CURRENT_RPT.formulas.length; execFmlIdx++) {
                if ($CURRENT_RPT.formulas[execFmlIdx].run_type === $RUN_TYPE) {
                    let expression = $CURRENT_RPT.formulas[execFmlIdx].expression;
                    if (expression) {
                        let $ME = $CURRENT_RPT.formulas[execFmlIdx];
                        try {
                            eval(expression);
                        } catch (ex) {
                            console.log(ex);
                        }
                    }
                }
            }
        }
        return {
            $JE,
            $JV,
            P,
            F,
            D,
            L,
            getCurrentPage,
            getTotalPage,
            setFieldValue,
            setFieldValueArray,
            removeFieldValue,
            insertFieldValue,
            setData,
            getNumberArray,
            copyPrecision,
            copyFixedPrecisionNum,
            copyProperty,
            setDate,
            DLength,
            isEmptyString,
            trim,
            leftTrim,
            rightTrim,
            comdify,
            convertToCaptionNum,
            convertStrToBoolean,
            formatNumber,
            reportDate 
        }
    };
    outputColumn(rptTpl: IRptTpl, dataObj: IDataObj | null, page: number, segIdx: number, bands: IBands, unitFactor: number, multiColIdx: number, $CURRENT_RPT: ICurrent_RPT, customizeCfg: ICustomizeCfg | null) {
        let me = this, rst: any = [];
        // let FLOW_NODE_STR = me.isEx?'流水式表_拓展信息':'流水式表_信息';
        let flow_node_str = me.isEx ? rptTpl.流水式表_拓展信息 : rptTpl.流水式表_信息;
        let tab = flow_node_str.流水式表_列;
        let band = bands[tab.BandName];
        if (band) {
            let pageStatus = me.pageStatusLst[page - 1];
            if (pageStatus[(band.DisplayType) as number]) {
                rst = rst.concat(me.commonTabRestOutput(dataObj, page, segIdx, bands, band, unitFactor, tab, multiColIdx, $CURRENT_RPT, customizeCfg));
            }
        }
        return rst;
    };
    outputSegSum(rptTpl: IRptTpl, dataObj: IDataObj, page: number, segIdx: number, bands: IBands, unitFactor: number, controls: IControlCollection, $CURRENT_RPT: ICurrent_RPT, customizeCfg: ICustomizeCfg) {
        let me = this, rst: any = [];
        // let FLOW_NODE_STR = me.isEx?'流水式表_拓展信息':'流水式表_信息';
        let flow_node_str = me.isEx ? rptTpl.流水式表_拓展信息 : rptTpl.流水式表_信息;
        let tab = flow_node_str.流水式表_段统计信息;
        let refTab = flow_node_str.流水式表_数据;
        let refTabEx = (rptTpl.流水式表_拓展信息) ? rptTpl.流水式表_拓展信息.流水式表_数据 : null;
        let band = bands[tab.BandName];
        if (band) {
            let pageStatus = me.pageStatusLst[page - 1];
            if (pageStatus[(band.DisplayType) as number]) {
                let ref_tab_fields = refTab.flow_field_s;
                let ref_tab_fields_ex = refTabEx ? refTabEx.flow_field_s : null;
                let tab_fields = me.seg_sum_tab_fields;
                for (let i = 0; i < tab_fields.length; i++) {
                    if (ref_tab_fields_ex && !JpcFieldHelper.resetSumFormat(ref_tab_fields, tab_fields[i])) {
                        if (!JpcFieldHelper.resetSumFormat(ref_tab_fields_ex, tab_fields[i])) {
                            let map_data_field = JE.F(tab_fields[i][JV.PROP_FIELD_ID], $CURRENT_RPT);
                            JpcFieldHelper.resetFormat(tab_fields[i], map_data_field, customizeCfg)
                            //如果都找不到，就得靠自己的Format属性了
                        }
                    }
                    let sumVal = 0;
                    if (me.segSumValLst[segIdx] && me.segSumValLst[segIdx].length > i) {
                        sumVal = me.segSumValLst[segIdx][i];
                    }
                    //备注：考虑到有时候会出现没有数据可合计的scenario,得有容错处理
                    let cellItem = JpcCommonOutputHelper.createCommonOutput(tab_fields[i], sumVal, controls);
                    cellItem.area = JpcAreaHelper.outputArea(tab_fields[i].area, band, unitFactor, 1, 0, 1, 0, me.multiCols, 0, false, false);
                    rst.push(cellItem);
                }
                rst = rst.concat(me.commonTabRestOutput(dataObj, page, segIdx, bands, band, unitFactor, tab, 0, $CURRENT_RPT, customizeCfg));
            }
        }
        return rst;
    };
    //每页的合计
    outputPageSum(rptTpl: IRptTpl, dataObj: IDataObj, page: number, segIdx: number, bands: IBands, unitFactor: number, controls: IControlCollection, $CURRENT_RPT: ICurrent_RPT, customizeCfg: ICustomizeCfg) {
        let me = this, rst: any = [];
        // let FLOW_NODE_STR = me.isEx?'流水式表_拓展信息':'流水式表_信息';
        let flow_node_str = me.isEx ? rptTpl.流水式表_拓展信息 : rptTpl.流水式表_信息;
        let tab = flow_node_str.流水式表_页统计信息;
        let refTab = flow_node_str.流水式表_数据;
        let refTabEx = (rptTpl.流水式表_拓展信息) ? rptTpl.流水式表_拓展信息.流水式表_数据 : null;
        let band = bands[tab.BandName];
        if (band) {
            let pageStatus = me.pageStatusLst[page - 1];
            if (pageStatus[(band.DisplayType) as number]) {
                let ref_tab_fields = refTab.flow_field_s;
                let ref_tab_fields_ex = refTabEx ? refTabEx.flow_field_s : null;
                let tab_fields = me.page_sum_tab_fields;
                for (let i = 0; i < tab_fields.length; i++) {
                    if (!JpcFieldHelper.resetSumFormat(ref_tab_fields, tab_fields[i])) {
                        if (ref_tab_fields_ex && !JpcFieldHelper.resetSumFormat(ref_tab_fields_ex, tab_fields[i])) {
                            let map_data_field = JE.F(tab_fields[i][JV.PROP_FIELD_ID], $CURRENT_RPT);
                            JpcFieldHelper.resetFormat(tab_fields[i], map_data_field, customizeCfg)
                            //如果都找不到，就得靠自己的Format属性了
                        }
                    }
                    let cellItem = JpcCommonOutputHelper.createCommonOutput(tab_fields[i], me.pageSumValLst[page - 1][i], controls);
                    cellItem.area = JpcAreaHelper.outputArea(tab_fields[i].area, band, unitFactor, 1, 0, 1, 0, me.multiCols, 0, false, false);
                    rst.push(cellItem);
                }
                rst = rst.concat(me.commonTabRestOutput(dataObj, page, segIdx, bands, band, unitFactor, tab, 0, $CURRENT_RPT, customizeCfg));
            }
        }
        return rst;
    };
    outputTabField(band: IBandDetail, tab_field: Fields, data_field: string[] | null, valueIdx: number, serialIdx: number, rows: number, rowIdx: number, cols: number, colIdx: number, unitFactor: number, isRow: boolean, controls: IControlCollection, multiColIdx: number) {
        let me = this,
            rst = JpcCommonOutputHelper.createCommonOutput(tab_field, JpcFieldHelper.getValue(data_field, valueIdx), controls);
        rst.area = JpcAreaHelper.outputArea(tab_field.area, band, unitFactor, rows, rowIdx, cols, colIdx, me.multiCols, multiColIdx, isRow, false);
        return rst;
    };
    outputAutoHeightTabField(band: IBandDetail, tab_field: Fields, data_field: string[], contentValInfo: number[], rows: number, rowIdx: number, cols: number, colIdx: number, unitFactor: number, isRow: boolean, controls: IControlCollection, multiColIdx: number) {
        let me = this;
        let showText = JpcFieldHelper.getValue(data_field, contentValInfo[2]);
        if (tab_field.isAutoHeight) {
            let textArr: any[] = [];
            if (showText) {
                textArr = textArr.concat(showText.split('|'));
            }
                        /*
            if (contentValInfo[3] < textArr.length && contentValInfo[3] >= 0) {
                showText = textArr[contentValInfo[3]];
            }
            else {
                showText = '';
            }
 /*/
            // 因新逻辑要优化自动行高，不再是一个折行占用1row，而是: 
            // a. 根据实际情况，设置了一个实际的行数值(比如共有10行，根据行高情况，可能只设置了6行的高度，在setupAutoHeightData方法里处理)
            // b. 这里最大的难题在于跨页分配(预估会有来回调整，目前采用按比例分配原则)
            // c. 还有个问题就是多个自动行高指标的问题
            const ACT_ROWS = contentValInfo[4]; //经实际计算，能容纳所有数据的实际行数
            const CURRENT_ROW = contentValInfo[3]; //从0开始
            const QUOTA_Rate = textArr.length / ACT_ROWS; //每行显示的加权系数(超过2的话，表示给的行高太多了，需要另外一些特殊处理，后期有需要再加)
            if (textArr.length <= 3 || ACT_ROWS > textArr.length) {
                //表示这个一定是附属的autoheight指标，或者数据就只有3行(假如数据3行精简成2行，但刚好处于分页状态，那么无论是前一页或后一页，显示上都很纠结(多出来的一行放哪好？)，所以新逻辑的起点要3行以上，少了就不折腾了，老老实实地一个萝卜一个坑)
                if (CURRENT_ROW < textArr.length && CURRENT_ROW >= 0) {
                    showText = textArr[CURRENT_ROW];
                } else {
                    showText = '';
                }
            } else {
                //这里不管是不是附属autoheight指标,有足够的条件单独处理
                if (QUOTA_Rate >= 3) {
                    console.log('压缩率太高了，模板的行高设置小一点')
                    //压缩超过一半空间的话，说明给的行高度太高了，需要另外一些特殊处理，后期有需要再加
                } else {
                    //正常的压缩比例
                    let startIdx = 0, endIdx = 0;
                    if (CURRENT_ROW > 0) {
                        endIdx = Math.round((CURRENT_ROW + 1) * QUOTA_Rate) - 1;
                        let preEndIdx = 0;
                        if (CURRENT_ROW > 1) {
                            //重定位 preEndIdx
                            preEndIdx = Math.round(CURRENT_ROW * QUOTA_Rate) - 1;
                        }
                        startIdx = preEndIdx + 1;
                    }
                    //按比例分配
                    showText = textArr[startIdx];
                    for (let idx = startIdx + 1; idx <= endIdx; idx++) {
                        showText += `|${textArr[idx]}`;
                    }
                }
                
            }
            //*/
            let rst = JpcCommonOutputHelper.createCommonOutput(tab_field, showText, controls);
            rst.area = JpcAreaHelper.outputArea(tab_field.area, band, unitFactor, rows, rowIdx, cols, colIdx, me.multiCols, multiColIdx, true, false);
            rst.isAutoHeight = true;
            return rst;
        } else {
            if (contentValInfo[3] > 0) showText = '';
            let rst = JpcCommonOutputHelper.createCommonOutput(tab_field, showText, controls);
            rst.area = JpcAreaHelper.outputArea(tab_field.area, band, unitFactor, rows, rowIdx, cols, colIdx, me.multiCols, multiColIdx, true, false);
            rst.isAutoHeight = false;
            return rst;
        }
    };
    outputTabGrpLine(band: IBandDetail, grp_line: IGrpLine, page: number, grpValueIdx: number[], rows: number, rowIdx: number, cols: number, colIdx: number, unitFactor: number, isRow: boolean, controls: IControlCollection, multiColIdx: number, grpCntIdx: number, $CURRENT_RPT: ICurrent_RPT) {
        let me = this, rst = [];
        if (grp_line.SumKey_S) {
            let segIdx = JpcCommonHelper.getSegIdxByPageIdx(page, me.page_seg_map);
            let curSegGrpSum = me.group_sum_values[segIdx];
            for (let sumFieldNode of grp_line.SumKey_S) {
                // let value = curSegGrpSum[sumFieldNode[JV.PROP_SUM_KEY]][grpValueIdx[2]];
                let value = curSegGrpSum[`grp_sum_key_` + sumFieldNode.FieldID][grpValueIdx[2]];
                let sumFldRst = JpcTextHelper.outputDirectValue(sumFieldNode, value, band, unitFactor, rows, rowIdx, cols, colIdx, me.multiCols, multiColIdx);
                rst.push(sumFldRst);
            }
        }
        if (grp_line.text_s) {
            for (let txt of grp_line.text_s) {
                me.checkGrpTxtOutEvent(JV.RUN_TYPE_BEFORE_GROUP_TEXT_OUT, txt, grpCntIdx, $CURRENT_RPT);
                rst.push(JpcTextHelper.outputText(txt, band, unitFactor, rows, rowIdx, cols, colIdx, me.multiCols, multiColIdx));
                // me.combinePageCells(rst, verticalCombinePos, horizonCombinePos);
                // 可能会有一个After，但意义不大，用不着
            }
        }
        if (grp_line.discrete_field_s) {
            //暂时不支持
        }
        if (grp_line.param_s) {
            //暂时不支持
        }
        // console.log(rst);
        return rst;
    };
    checkGrpTxtOutEvent($RUN_TYPE: string, $TEXT: Fields, $TIMES: number, $CURRENT_RPT: ICurrent_RPT) {
        combinedGridFormula($RUN_TYPE, $TEXT, $TIMES, $CURRENT_RPT);
    };
    commonTabRestOutput(dataObj: IDataObj | null, page: number, segIdx: number, bands: IBands, band: IBandDetail, unitFactor: number, tab: ITab, multiColIdx: number, $CURRENT_RPT: ICurrent_RPT, customizeCfg: ICustomizeCfg | null) {
        let me = this, rst = [];
        if (tab.text) {
            rst.push(JpcTextHelper.outputText(tab.text, band, unitFactor, 1, 0, 1, 0, me.multiCols, multiColIdx));
        }
        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, me.multiCols, multiColIdx));
            }
        }
        if (tab.离散信息) {
            rst = rst.concat(JpcDiscreteHelper.outputDiscreteInfo(tab.离散信息, bands, dataObj, unitFactor, me.pageStatusLst[page - 1], segIdx, 1, 0, $CURRENT_RPT, customizeCfg));
        }
        return rst;
    };
};

function _addPageValue(ValuedIdxLst: number[][][], sortedSequence: number[], grpSequenceInfo: any, startRecIdx: number, maxRecPerPage: number, page_seg_map: number[][],
    segIdx: number, pageIdx: number, grpPageInfo: IGrpPageInfo | null, isFollow: boolean, segAutoHeightInfo: number[][] | null, prePageLeftAutoHeightRecAmt: number) {
    let vIdx = [], vFirstIdx = [], preAmt = 0, insertedGrpAmt = 0, grp_lines = 0, followMode = (isFollow) ? JV.TYPE_FOLLOW_MODE : -1, nextPageAutoHeightRecAmt = 0;
    if (grpSequenceInfo && grpPageInfo) {
        if (grpPageInfo.preAddPageGrpInfo.length > 0) {
            for (let grpLineIdx of grpPageInfo.preAddPageGrpInfo) {
                //vIdx.push([followMode, JV.DISPLAY_VAL_TYPE_GROUP, grpPageInfo.segGrpRecStartIdx, grpLineIdx]);
                vFirstIdx.push([followMode, JV.DISPLAY_VAL_TYPE_GROUP, grpPageInfo.segGrpRecStartIdx, grpLineIdx]);
            }
            grpPageInfo.segGrpRecStartIdx++;
        }
        preAmt = grpPageInfo.preAddPageGrpInfo.length;
        grpPageInfo.preAddPageGrpInfo = [];
        grp_lines = grpPageInfo.group_lines_amt;
    }
    let autoHeightAmt = 0;
    let private_addAutoHeightPageValue = function (vi: number) {
        let couldBreak = false, startIdx = 0;
        let ttlValAmt = 0;
        if (segAutoHeightInfo && segAutoHeightInfo[segIdx].length > startRecIdx + vi) {
            ttlValAmt = segAutoHeightInfo[segIdx][startRecIdx + vi];
        }
        if (prePageLeftAutoHeightRecAmt > 0 && vi === 0) {
            startIdx = prePageLeftAutoHeightRecAmt;
        }
        for (let subValIdx = startIdx; subValIdx < ttlValAmt; subValIdx++) {
            vIdx.push([followMode, JV.DISPLAY_VAL_TYPE_AUTO_HEIGHT, sortedSequence[startRecIdx + vi], subValIdx, ttlValAmt]);
            autoHeightAmt++;
            if (autoHeightAmt >= maxRecPerPage) {
                nextPageAutoHeightRecAmt = (subValIdx + 1) % ttlValAmt;
                couldBreak = true;
                break;
            }
        }
        return couldBreak;
    };
    let private_inner_add_grp_rec = function (vi: number) {
        let hasFullGrp = true, couldBreak = false;
        if (grpPageInfo) {
            for (let i = 0; i < grp_lines; i++) {
                if (vIdx.length >= maxRecPerPage) {
                    for (let j = i; j < grp_lines; j++) {
                        grpPageInfo.preAddPageGrpInfo.push(j);
                    }
                    //准备要跳出去了
                    hasFullGrp = false;
                    break;
                } else {
                    vIdx.push([followMode, JV.DISPLAY_VAL_TYPE_GROUP, grpPageInfo.segGrpRecStartIdx, i]);
                }
            }
            //3. 进位下一个group信息所在位置
            if (hasFullGrp) {
                grpPageInfo.insertedGrpRecAmt++;
                insertedGrpAmt++;
                grpPageInfo.segGrpRecStartIdx++;
            } else {
                couldBreak = true;
            }
        }
        return couldBreak;
    };
    let private_normal_add_rec = function (vi: number) {
        let couldBreak = false;
        if (segAutoHeightInfo && segAutoHeightInfo.length > 0) {
            if (segAutoHeightInfo[segIdx].length > startRecIdx + vi) {
                couldBreak = private_addAutoHeightPageValue(vi);
                // if (couldBreak) break;
            } else if (vIdx.length < maxRecPerPage) {
                vIdx.push([followMode, JV.DISPLAY_VAL_TYPE_NORMAL, JV.BLANK_VALUE_INDEX]);
            }
        } else {
            if (sortedSequence.length > startRecIdx + vi) {
                vIdx.push([followMode, JV.DISPLAY_VAL_TYPE_NORMAL, sortedSequence[startRecIdx + vi]]);
            } else {
                vIdx.push([followMode, JV.DISPLAY_VAL_TYPE_NORMAL, JV.BLANK_VALUE_INDEX]);
            }
        }
        return couldBreak;
    };
    for (let vi = 0; (vi + insertedGrpAmt * grp_lines) < maxRecPerPage - preAmt; vi++) {
        if (grpSequenceInfo && grpPageInfo) {
            if ((startRecIdx + vi) === grpSequenceInfo[grpPageInfo.segGrpRecStartIdx]) {
                //表示这里要插入grouping信息啦！
                let couldBreak = false;
                //1. 首先push正常的记录(要考虑自动行高调整的分支)
                if (segAutoHeightInfo && segAutoHeightInfo.length > 0) {
                    couldBreak = private_addAutoHeightPageValue(vi);
                } else {
                    vIdx.push([followMode, JV.DISPLAY_VAL_TYPE_NORMAL, sortedSequence[startRecIdx + vi]]);
                }
                //2. 然后就要push grouping记录了
                if (private_inner_add_grp_rec(vi)) break;
                if (couldBreak) break;
            } else {
                //备注： 在有group的情况下，如果grpPageInfo[JV.PROP_SEG_GRP_IDX] 范围大于 grpSequenceInfo.length，则表示已经到最后了，不要再加空白数据了
                //      ！！！但这是在有ex数据的情况下！！！
                if (grpPageInfo.segGrpRecStartIdx < grpSequenceInfo.length) {
                    if (private_normal_add_rec(vi)) break;
                } else {
                    //还得判断是否是普通的流水数据情况，这里可以用isFollow来进行判断，暂时不需要特意加新参数(以后如isFollow的意义有变化则需要调整)
                    if (!isFollow) {
                        if (private_normal_add_rec(vi)) break;
                    } else {
                        break;
                    }
                }
            }
        } else {
            if (private_normal_add_rec(vi)) break;
        }
    }
    if (vFirstIdx.length > 0) {
        vIdx = vIdx.concat(vFirstIdx);
        //备注： 在一开始就加grp的情况下，这些数据应该放在后面才对
    }
    page_seg_map.push([pageIdx, segIdx]);
    ValuedIdxLst.push(vIdx);
    return nextPageAutoHeightRecAmt;
}

function push_cell(pageCellObj: IPageCellObj, cell: ICell, cellIdx: number) {
    let key = cell.area.Left + '_' + cell.area.Right;
    if (!pageCellObj[key]) {
        pageCellObj[key] = [];
    }
    let cellArr = pageCellObj[key];
    cellArr.push({ "cellIdx": cellIdx, "cell": cell });
}

function prepareAutoHeightCells(prepareObj: IPageAreaObj | {}, cellItem: ICell, cellIdx: number, cellsArr: ICell[]) {
    if (prepareObj) {
        if ((prepareObj as IPageAreaObj).cellsArr === undefined) {
            (prepareObj as IPageAreaObj).cellsArr = cellsArr;
            (prepareObj as IPageAreaObj).pageCellObj = {};
        }
        push_cell((prepareObj as IPageAreaObj).pageCellObj, cellItem, cellIdx);
    }
}

function setupControl(mergeCell: ICell, controls: IControlCollection) {
    let orgCtrl = null;
    if (typeof mergeCell.control === "string") {
        orgCtrl = controls[mergeCell.control];
        mergeCell.control = <IControlSubCollection>{
            "Shrink": "T",
            "ShrinkFirst": orgCtrl.ShrinkFirst,
            "CloseOutput": orgCtrl.CloseOutput,
            "ShowZero": orgCtrl.ShowZero,
            "Horizon": orgCtrl.Horizon,
            "Vertical": orgCtrl.Vertical,
            "Wrap": (mergeCell.isAutoHeight) ? 'T' : 'F',
            "VerticalForExcel": "center"
        };
    } else {
        mergeCell.control.Shrink = "T";
        mergeCell.control.Vertical = "top";
        mergeCell.control.Wrap = (mergeCell.isAutoHeight) ? 'T' : 'F',
            mergeCell.control.VerticalForExcel = "center";
        orgCtrl = mergeCell.control;
    }
    if (mergeCell.isAutoHeight) {
        mergeCell.control.VerticalForExcel = 'justify';
        // mergeCell.control["Vertical"] = 'center';
    } else {
        mergeCell.control.VerticalForExcel = 'center';
        // mergeCell.control["Vertical"] = 'top';
    }
    return orgCtrl;
}

function combineAutoHeightCells(prepareObj: IPageAreaObj , page: number, controls: IControlCollection) {
    // 该方法主要是用来生成自动合并的格子的，本来是已经生成了一行一个格子的，但现在需要把可以自动合并的格子进行中整合，在这里进行这个动作
    // 最后输出的是被合并的格子的index，在外面再剔除
    let rst = [];
    if (prepareObj.cellsArr) {
        //merge cells' value and area
        //备注： 系统逻辑已经把Cell的顺序放好，无需再做排序。
        for (let mergeKey in prepareObj.pageCellObj) {
            let sameColCells = prepareObj.pageCellObj[mergeKey]; //左右位置相同的Cell先放在一起，统一处理
            if (sameColCells.length > 1) {
            //    这里获取第一个被合并的cell的数据
                let firstMergeCell = sameColCells[0].cell ;
                firstMergeCell.style = firstMergeCell.style.slice(0, firstMergeCell.style.indexOf("_AutoHeightMerge")); //首先还原original style
                //生成原始对象，并且把对象中的control属性转化为对象
                let orgCtrl = setupControl(firstMergeCell, controls);
                let validValueAmt = 0, fullValidValueAmt = 0;
                for (let i = 1; i < sameColCells.length; i++) {
                    let mergeCell = sameColCells[i].cell;
                    //含有“_AutoHeightMerge_Top”的都是每个自动合并的cell的第一行（项）
                    if (mergeCell.style.indexOf("_AutoHeightMerge_Top") < 0) {
                        fullValidValueAmt++;
                        //merge into the firstMergeCell! position & value
                        firstMergeCell.area.Bottom = mergeCell.area.Bottom;
                        if (mergeCell.Value) {
                            firstMergeCell.Value = firstMergeCell.Value + "|" + mergeCell.Value;
                            validValueAmt++;
                        }
                        rst.push(sameColCells[i].cellIdx); //记下Cell的位置，在函数外消除
                        //如果到了最后一条数据，得判断firstMergeCell是否满格（即数据是满的，有可能有些格数据也有折行但不是自动行高判断指标）
                        //不满格的cell的Vertical强制设置为 'center'
                        if (i === sameColCells.length - 1 && validValueAmt !== fullValidValueAmt && (fullValidValueAmt / validValueAmt > 2.5)) {
                            if (typeof firstMergeCell.control !== 'string') {
                                firstMergeCell.control.VerticalForExcel = 'center';
                            }
                        }
                    } else {
                        //碰到新开始的自动行高行，判断原先的firstMergeCell是否满格（即数据是满的，有可能有些格数据也有折行但不是自动行高判断指标）
                        //不满格的cell的Vertical强制设置为 'center'
                        if (validValueAmt !== fullValidValueAmt && (fullValidValueAmt / validValueAmt > 2.5)) {
                            if (typeof firstMergeCell.control !== 'string') {
                                firstMergeCell.control.VerticalForExcel = 'center';
                            }
                        }
                        firstMergeCell = <ICell>sameColCells[i].cell;
                        firstMergeCell.style = firstMergeCell.style.slice(0, firstMergeCell.style.indexOf("_AutoHeightMerge"));
                        orgCtrl = setupControl(firstMergeCell, controls);
                        validValueAmt = 0;
                        fullValidValueAmt = 0;
                    }
                }
            }
        }
        rst.sort(function (i1, i2) {
            return (i1 > i2) ? 1 : -1;
        });
    }
    return rst;
}
