/**
 * Created by Tony on 2018/9/4.
 */

let virtualSummaryOprObj = {
    summaryWorkBook: null,
    summaryParentNode: null,
    iniSpreadJs: function (summaryParentNode) {
        let me = this;
        if (me.summaryWorkBook !== null) {
            me.summaryWorkBook.destroy();
            me.summaryWorkBook = null;
        }
        me.summaryWorkBook = new GC.Spread.Sheets.Workbook($('#rptTplSummaryWorkbook')[0], {sheetCount: 1});
        me.summaryWorkBook.options.tabStripVisible = false;
        me.summaryWorkBook.options.allowCopyPasteExcelStyle = false;
        me.summaryWorkBook.options.allowUserDragDrop = false;
        me.summaryWorkBook.options.allowContextMenu = false;
        let sheet = me.summaryWorkBook.getActiveSheet();
        sheet.options.allowCellOverflow = false;
        sheet.options.clipBoardOptions = GC.Spread.Sheets.ClipboardPasteOptions.values;
        sheet.bind(GC.Spread.Sheets.Events.CellClick, me.onCellEnter);
        me.summaryParentNode = summaryParentNode;
    },
    restoreSummary: function () {
        let me = this;
        let rptTpl = (zTreeOprObj.currentNode)?zTreeOprObj.currentNode.rptTpl:null;
        me.private_setup_control_options(false);
        me.setupSummary(rptTpl, me.summaryParentNode);
    },
    setupSummary: function (rptTpl, summaryParentNode) {
        let me = this, columnParentNode = null;
        let selectedBand = visualCommonOprObj.getBandEx(summaryParentNode[JV.PROP_BAND_NAME], rptTpl);
        if (summaryParentNode && selectedBand) {
            me.private_setup_control_options(false);
            let preNode = summaryParentNode.getPreNode();
            while (preNode) {
                if (preNode[JV.PROP_NAME] === JV.NODE_FLOW_COLUMN) {
                    columnParentNode = preNode;
                    break;
                } else {
                    preNode = preNode.getPreNode();
                }
            }
            let fieldNode = summaryParentNode.items[0], textNode = summaryParentNode.items[1];
            if (columnParentNode) {
                let yColumnPos = [], xPos = [], ySummaryPos = [0]
                    // , xSummaryPos = [0]
                ;
                let sheet = me.summaryWorkBook.getActiveSheet();
                let columnBand = visualCommonOprObj.getBandEx(columnParentNode[JV.PROP_BAND_NAME], rptTpl);
                let bandH = Math.round(parseFloat(columnBand[JV.BAND_PROP_HEIGHT]) / 2.54 * 96);
                let bandW = 700;
                let pIdx = JV.PAGES_SIZE_STR.indexOf(rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_PAGE_SIZE]);
                if (pIdx >= 0) {
                    bandW = Math.round(JV.PAGES_SIZE[pIdx][0] * 96 - (parseFloat(rptTpl[JV.NODE_MAIN_INFO][JV.NODE_MARGINS][JV.PROP_LEFT]) + parseFloat(rptTpl[JV.NODE_MAIN_INFO][JV.NODE_MARGINS][JV.PROP_RIGHT])) /2.54*96 );
                    if (rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_ORIENTATION] === JV.ORIENTATION_LANDSCAPE ||
                        rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_ORIENTATION] === JV.ORIENTATION_LANDSCAPE_CHN) {
                        bandW = Math.round(JV.PAGES_SIZE[pIdx][1] * 96 - (parseFloat(rptTpl[JV.NODE_MAIN_INFO][JV.NODE_MARGINS][JV.PROP_LEFT]) + parseFloat(rptTpl[JV.NODE_MAIN_INFO][JV.NODE_MARGINS][JV.PROP_RIGHT])) /2.54*96 );
                    }
                }
                //1. 设置column位置(让用户知道位置，后期无需用户再调)
                for (let itemNode of columnParentNode.items) {
                    visualCommonOprObj.pushPos(itemNode, itemNode[JV.PROP_AREA][JV.PROP_H_CALCULATION], JV.PROP_LEFT, bandW, xPos);
                    visualCommonOprObj.pushPos(itemNode, itemNode[JV.PROP_AREA][JV.PROP_H_CALCULATION], JV.PROP_RIGHT, bandW, xPos);
                    visualCommonOprObj.pushPos(itemNode, itemNode[JV.PROP_AREA][JV.PROP_V_CALCULATION], JV.PROP_TOP, bandH, yColumnPos);
                    visualCommonOprObj.pushPos(itemNode, itemNode[JV.PROP_AREA][JV.PROP_V_CALCULATION], JV.PROP_BOTTOM, bandH, yColumnPos);
                }
                sheet.suspendPaint();
                sheet.clearSelection();
                sheet.setRowCount(yColumnPos.length - 1, GC.Spread.Sheets.SheetArea.colHeader);
                sheet.setColumnCount(xPos.length - 1, GC.Spread.Sheets.SheetArea.viewport);
                // sheet.clear();

                xPos.sort(function(x1, x2){
                    return (x1 - x2);
                });
                yColumnPos.sort(function(y1, y2){
                    return (y1 - y2);
                });
                for (let idx = 1; idx < xPos.length; idx++) {
                    sheet.setColumnWidth(idx - 1, xPos[idx] - xPos[idx - 1]);
                }
                for (let idx = 1; idx < yColumnPos.length; idx++) {
                    sheet.setRowHeight(idx - 1, yColumnPos[idx] - yColumnPos[idx - 1]);
                    sheet.getRange(idx - 1, -1, 1, -1).backColor(undefined);
                }
                for (let itemNode of columnParentNode.items) {
                    visualCommonOprObj.addSpan(itemNode, sheet, bandW, bandH, xPos, yColumnPos, GC.Spread.Sheets.SheetArea.colHeader);
                }
                //2. 设置已有的统计信息
                let sumBandH = Math.round(parseFloat(selectedBand[JV.BAND_PROP_HEIGHT]) / 2.54 * 96);
                for (let fNode of fieldNode.items) {
                    visualCommonOprObj.pushPos(fNode, fNode[JV.PROP_AREA][JV.PROP_V_CALCULATION], JV.PROP_TOP, sumBandH, ySummaryPos);
                    visualCommonOprObj.pushPos(fNode, fNode[JV.PROP_AREA][JV.PROP_V_CALCULATION], JV.PROP_BOTTOM, sumBandH, ySummaryPos);
                }
                for (let tNode of textNode.items) {
                    visualCommonOprObj.pushPos(tNode, tNode[JV.PROP_AREA][JV.PROP_V_CALCULATION], JV.PROP_TOP, sumBandH, ySummaryPos);
                    visualCommonOprObj.pushPos(tNode, tNode[JV.PROP_AREA][JV.PROP_V_CALCULATION], JV.PROP_BOTTOM, sumBandH, ySummaryPos);
                }
                sheet.setRowCount(ySummaryPos.length - 1, GC.Spread.Sheets.SheetArea.viewport);
                for (let idx = 1; idx < ySummaryPos.length; idx++) {
                    sheet.setRowHeight(idx - 1, ySummaryPos[idx] - ySummaryPos[idx - 1]);
                }
                for (let tNode of textNode.items) {
                    visualCommonOprObj.addSpan(tNode, sheet, bandW, sumBandH, xPos, ySummaryPos, GC.Spread.Sheets.SheetArea.viewport);
                }
                for (let fNode of fieldNode.items) {
                    visualCommonOprObj.addSpan(fNode, sheet, bandW, sumBandH, xPos, ySummaryPos, GC.Spread.Sheets.SheetArea.viewport);
                }
                sheet.resumePaint();
            }
        }
    },
    addRow: function () {
        let me = this,
            sheet = me.summaryWorkBook.getActiveSheet();
        sheet.suspendPaint();
        sheet.addRows(sheet.getRowCount() - 1, 1);
        let rc = sheet.getRowCount();
        for (let cc = 0; cc < sheet.getColumnCount(); cc++) {
            visualCommonOprObj.setupCellDft(sheet.getCell(rc - 2, cc));
        }
        sheet.resumePaint();
    },
    deleteRow: function () {
        let me = this,
            sheet = me.summaryWorkBook.getActiveSheet(),
            selectedRanges = sheet.getSelections()
        ;
        sheet.suspendPaint();
        if (selectedRanges.length > 0) {
            sheet.deleteRows(selectedRanges[0].row, 1);
        }
        sheet.resumePaint();
    },
    onCellEnter: function (sender, args) {
        let me = virtualSummaryOprObj,
            sheet = me.summaryWorkBook.getActiveSheet();
        me.setupCfg(sheet, args.row, args.col);
    },
    setupCfg: function (sheet, row, col) {
        let me = virtualSummaryOprObj, cell = sheet.getCell(row, col);
        let font = cell.font();
        // let style = sheet.getStyle(row, col);
        // console.log('font: ' + font);
        me.private_setup_control_options(true);
        //1. 横向
        switch (cell.hAlign()) {
            case GC.Spread.Sheets.HorizontalAlign.left:
                $(`#hOptionLeftSum`)[0].checked = true;
                break;
            case GC.Spread.Sheets.HorizontalAlign.center:
                $(`#hOptionCenterSum`)[0].checked = true;
                break;
            case GC.Spread.Sheets.HorizontalAlign.right:
                $(`#hOptionRightSum`)[0].checked = true;
                break;
            default:
                $(`#hOptionLeftSum`)[0].checked = true;
                break;
        }
        //2. 纵向
        switch (cell.vAlign()) {
            case GC.Spread.Sheets.VerticalAlign.top:
                $(`#vOptionUpSum`)[0].checked = true;
                break;
            case GC.Spread.Sheets.VerticalAlign.center:
                $(`#vOptionCenterSum`)[0].checked = true;
                break;
            case GC.Spread.Sheets.VerticalAlign.bottom:
                $(`#vOptionDownSum`)[0].checked = true;
                break;
            default:
                $(`#vOptionCenterSum`)[0].checked = true;
                break;
        }
        //3. cell type
        if (cell.cellType().typeName === '1') {
            $(`#rdIsText`)[0].checked = true;
        } else {
            $(`#rdIsField`)[0].checked = true; //combo-box cell type name: `7`
        }
        // console.log('cell type: ' + cell.cellType());
        //4. 窄体
        if (font.indexOf('Narrow') > 0) {
            $(`#eleIsNarrowSumEx`)[0].checked = true;
        } else {
            $(`#eleIsNarrowSumEx`)[0].checked = false;
        }
    },
    mergeCells: function () {
        let me = virtualSummaryOprObj,
            sheet = me.summaryWorkBook.getActiveSheet();
        let selectedRanges = sheet.getSelections();
        if (selectedRanges.length > 0) {
            sheet.suspendPaint();
            sheet.addSpan(selectedRanges[0].row, selectedRanges[0].col, selectedRanges[0].rowCount, selectedRanges[0].colCount);
            sheet.resumePaint();
        }
    },
    disMergeCells: function () {
        let me = virtualSummaryOprObj,
            sheet = me.summaryWorkBook.getActiveSheet();
        let selectedRanges = sheet.getSelections();
        let spans = sheet.getSpans();
        if (selectedRanges.length > 0 && spans.length > 0) {
            sheet.suspendPaint();
            let selectedSpans = [];
            for(let i = 0; i < spans.length; i++)
            {
                for (let j = 0; j < selectedRanges.length; j++) {
                    if (spans[i].row >= selectedRanges[j].row && spans[i].col >= selectedRanges[j].col &&
                        spans[i].row <= selectedRanges[j].row + selectedRanges[j].rowCount && spans[i].col <= selectedRanges[j].col + selectedRanges[j].colCount) {
                        selectedSpans.push(spans[i]);
                    }
                }
            }
            for (let span of selectedSpans) {
                sheet.removeSpan(span.row, span.col, GC.Spread.Sheets.SheetArea.viewport);
            }
            sheet.resumePaint();
        }
    },
    changeCellType: function (newType) {
        let me = virtualSummaryOprObj,
            sheet = me.summaryWorkBook.getActiveSheet();
        let selectedRanges = sheet.getSelections();
        if (selectedRanges.length > 0) {
            sheet.suspendPaint();
            let cell = sheet.getCell(selectedRanges[0].row, selectedRanges[0].col);
            visualCommonOprObj.changeCellType(cell, newType);
            sheet.resumePaint();
        }
    },
    changeCellCfg: function () {
        let me = virtualSummaryOprObj,
            sheet = me.summaryWorkBook.getActiveSheet();
        let selectedRanges = sheet.getSelections();
        if (selectedRanges.length > 0) {
            sheet.suspendPaint();
            let cell = sheet.getCell(selectedRanges[0].row, selectedRanges[0].col);
            let hA = GC.Spread.Sheets.HorizontalAlign.left, vA = GC.Spread.Sheets.VerticalAlign.top;
            if ($(`#hOptionCenterSum`)[0].checked) hA = GC.Spread.Sheets.HorizontalAlign.center;
            if ($(`#hOptionRightSum`)[0].checked) hA = GC.Spread.Sheets.HorizontalAlign.right;
            if ($(`#vOptionCenterSum`)[0].checked ) vA = GC.Spread.Sheets.VerticalAlign.center;
            if ($(`#vOptionDownSum`)[0].checked ) vA = GC.Spread.Sheets.VerticalAlign.bottom;
            cell.hAlign(hA);
            cell.vAlign(vA);
            if ($(`#eleIsNarrowSumEx`)[0].checked) {
                cell.font('Arial Narrow');
            } else {
                cell.font('9pt 宋体');
            }
            sheet.resumePaint();
        }
    },
    changeCtrl: function (dom) {
        let me = virtualSummaryOprObj,
            sheet = me.summaryWorkBook.getActiveSheet()
        ;
        let selectedRanges = sheet.getSelections();
        for(let i = 0; i < selectedRanges.length; i++){
            //         let ctrl = me.columnFieldCtrls[selectedRanges[i].col]
            //         ctrl[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_SHRINK]] = 'F';
            //         ctrl[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_SHOW_ZERO]] = 'F';
            //         ctrl[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_WRAP]] = 'F';
            //         ctrl.isNarrow = false;
            //         ctrl.isAutoHeight = false;
            //         if ($("#eleShrinkEx")[0].checked) {
            //             ctrl[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_SHRINK]] = 'T';
            //         }
            //         if ($("#eleShowZeroEx")[0].checked) {
            //             ctrl[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_SHOW_ZERO]] = 'T';
            //         }
            //         if ($("#eleAutoWrapEx")[0].checked) {
            //             ctrl[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_WRAP]] = 'T';
            //         }
            //         if ($("#eleIsNarrowEx")[0].checked) {
            //             ctrl.isNarrow = true;
            //         }
            //         if ($("#eleIsAutoHeightEx")[0].checked) {
            //             ctrl.isAutoHeight = true;
            //         }
            //
            //         if ($("#hOptionLeft")[0].checked) {
            //             ctrl[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_HORIZON]] = JV.OUTPUT_ALIGN.H[0];
            //         } else if ($("#hOptionCenter")[0].checked) {
            //             ctrl[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_HORIZON]] = JV.OUTPUT_ALIGN.H[1];
            //         } else {
            //             ctrl[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_HORIZON]] = JV.OUTPUT_ALIGN.H[2];
            //         }
            //         if ($("#vOptionUp")[0].checked) {
            //             ctrl[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_VERTICAL]] = JV.OUTPUT_ALIGN.V[0];
            //         } else if ($("#vOptionCenter")[0].checked) {
            //             ctrl[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_VERTICAL]] = JV.OUTPUT_ALIGN.V[1];
            //         } else {
            //             ctrl[JV.CONTROL_PROPS[JV.CONTROL_PROP_IDX_VERTICAL]] = JV.OUTPUT_ALIGN.V[2];
            //         }
        }
    },

    private_setup_control_options: function (enable) {
        if (enable) {
            $("#sumFieldControlDiv")[0].style.cursor = "";
            $("#hOptionLeftSum")[0].removeAttribute("disabled");
            $("#hOptionCenterSum")[0].removeAttribute("disabled");
            $("#hOptionRightSum")[0].removeAttribute("disabled");
            $("#vOptionUpSum")[0].removeAttribute("disabled");
            $("#vOptionCenterSum")[0].removeAttribute("disabled");
            $("#vOptionDownSum")[0].removeAttribute("disabled");
            $("#rdIsText")[0].removeAttribute("disabled");
            $("#rdIsField")[0].removeAttribute("disabled");
            $("#eleIsNarrowSumEx")[0].removeAttribute("disabled");
        } else {
            $("#sumFieldControlDiv")[0].style.cursor = "not-allowed";
            $("#hOptionLeftSum")[0].disabled = "disabled" ;
            $("#hOptionCenterSum")[0].disabled = "disabled" ;
            $("#hOptionRightSum")[0].disabled = "disabled" ;
            $("#vOptionUpSum")[0].disabled = "disabled" ;
            $("#vOptionCenterSum")[0].disabled = "disabled" ;
            $("#vOptionDownSum")[0].disabled = "disabled" ;
            $("#rdIsText")[0].disabled = "disabled" ;
            $("#rdIsField")[0].disabled = "disabled" ;
            $("#eleIsNarrowSumEx")[0].disabled = "disabled";
        }
    },
    private_create_field_node: function (sheet, colWidthArr, rowHeightArr, text, rptTpl) {
        let cellValue = text[`text`].toString().slice(1, -1);
        let rst = {"Name": cellValue, "Title": '', "FieldID": -1, "font": "GrandTotal", "control": "Column_Right", "style" : "Default_Normal", "isAutoHeight" : false,
            "area" : {"Left" : 0, "Right" : 100, "Top" : 0, "Bottom" : 100, "H_CalculationType" : "percentage", "V_CalculationType" : "percentage"}
        };
        //1. 设置FieldID
        let hasChkField = false;
        if (rptTpl[JV.NODE_FIELD_MAP][JV.NODE_DETAIL_FIELDS] !== undefined && rptTpl[JV.NODE_FIELD_MAP][JV.NODE_DETAIL_FIELDS].length > 0) {
            for (let field of rptTpl[JV.NODE_FIELD_MAP][JV.NODE_DETAIL_FIELDS]) {
                if (field[JV.PROP_NAME] === cellValue) {
                    rst.FieldID = field[JV.PROP_ID];
                    rst["Title"] = "ID: " + field[JV.PROP_ID];
                    hasChkField = true;
                    break;
                }
            }
        }
        if (!hasChkField && rptTpl[JV.NODE_NO_MAPPING_FIELDS] !== undefined && rptTpl[JV.NODE_NO_MAPPING_FIELDS].length > 0) {
            for (let field of rptTpl[JV.NODE_NO_MAPPING_FIELDS]) {
                if (field[JV.PROP_NAME] === cellValue) {
                    rst.FieldID = field[JV.PROP_ID];
                    rst["Title"] = "ID: " + field[JV.PROP_ID];
                    hasChkField = true;
                    break;
                }
            }
        }
        let cell = sheet.getCell(text.row, text.col);
        //2. 字体
        if (cell.font().indexOf('Narrow') > 0) {
            rst[JV.PROP_FONT] = "Content_Narrow";
        }
        //3. 上下左右位置
        visualCommonOprObj.setupHeightWidth(rst, text, colWidthArr, rowHeightArr);
        return rst;
    },

    applySummaryBack: function () {
        let me = this;
        let rptTpl = (zTreeOprObj.currentNode)?zTreeOprObj.currentNode.rptTpl:null;
        if (rptTpl && me.summaryParentNode) {
            let sheet = me.summaryWorkBook.getActiveSheet();
            let rAmt = sheet.getRowCount(), pixH = [0];
            if (rAmt > 0) {
                let texts = [], colWidthArr = [], rowHeightArr = [];
                //1. 收集text信息
                visualCommonOprObj.collectSheetTxt(sheet, texts, 0, colWidthArr, rowHeightArr);
                for (let node of me.summaryParentNode.items) {
                    dataInfoMapTreeOprObj.treeObj.removeChildNodes(node);
                }
                //2. 重新创建文本及统计指标
                let txtNodes = [], fieldNodes = [];
                for (let text of texts) {
                    if (!stringUtil.isEmptyString(text[`text`]) && text[`text`].indexOf(`{`) === 0) {
                        //创建指标
                        fieldNodes.push(me.private_create_field_node(sheet, colWidthArr, rowHeightArr, text, rptTpl));
                    } else {
                        //创建文本
                        let textNode = visualCommonOprObj.createTxtNode(text, me.columnParentNode, colWidthArr, rowHeightArr);
                        let cell = sheet.getCell(text.row, text.col);
                        if (cell.font().indexOf('Narrow') < 0) {
                            textNode[JV.PROP_FONT] = "GrandTotal";
                        } else {
                            textNode[JV.PROP_FONT] = "Content_Narrow";
                        }
                        textNode[JV.PROP_CONTROL] = "Column";
                        textNode[JV.PROP_STYLE] = "Default_Normal";
                        txtNodes.push(textNode);
                    }
                }
                let fieldNode = me.summaryParentNode.items[0], textNode = me.summaryParentNode.items[1];
                if (txtNodes.length > 0) {
                    dataInfoMapTreeOprObj.treeObj.addNodes(textNode, -1, txtNodes, true);
                }
                if (fieldNodes.length > 0) {
                    dataInfoMapTreeOprObj.treeObj.addNodes(fieldNode, -1, fieldNodes, true);
                }
                //3. 重新设置band高度
                // let selectedBand = visualCommonOprObj.getBandEx(me.summaryParentNode[JV.PROP_BAND_NAME], rptTpl);
                // selectedBand[JV.BAND_PROP_HEIGHT] = (rowHeightArr[rowHeightArr.length - 1] / 96 * 2.54).toFixed(2);
                visualCommonOprObj.changeBandHeight(me.summaryParentNode[JV.PROP_BAND_NAME], (rowHeightArr[rowHeightArr.length - 1] / 96 * 2.54).toFixed(2));
                displayMessage("应用提交成功！", "green", 5000, "id_summary_setup_lbl");
            } else {
                displayMessage("模板行数量不足！", "red", 5000, "id_summary_setup_lbl");
            }
        }
    }

};