/**
 * Created by Mai on 2017/4/1.
 */

var TREE_SHEET_CONTROLLER = {
    createNew: function (tree, sheet, setting, loadSheetHeader = true) {
        var controller = function () {
            this.tree = tree;
            this.sheet = sheet;
            this.setting = setting;
            this.event = {
                refreshBaseActn: null,
                treeSelectedChanged: null
            };
            if(loadSheetHeader){
                TREE_SHEET_HELPER.loadSheetHeader(this.setting, this.sheet);
            }
        };

        controller.prototype.showTreeData = function () {
            //
            var that = this;
            TREE_SHEET_HELPER.showTreeData(this.setting, this.sheet, this.tree);
            this.sheet.unbind(GC.Spread.Sheets.Events.SelectionChanged);
            this.sheet.bind(GC.Spread.Sheets.Events.SelectionChanged, function (e, info) {
                that.setTreeSelected(that.tree.items[info.newSelections[0].row]);
            });
        };

        controller.prototype.insert = function () {
            var newNode = null, that = this,  sels = this.sheet.getSelections();
            if (this.tree) {
                if (this.tree.selected) {
                    newNode = this.tree.insert(this.tree.selected.getParentID(), this.tree.selected.getNextSiblingID());
                } else {
                    newNode = this.tree.insert();
                }
                if (newNode) {
                    TREE_SHEET_HELPER.massOperationSheet(this.sheet, function () {
                        that.sheet.addRows(newNode.serialNo(), 1);
                        TREE_SHEET_HELPER.refreshTreeNodeData(that.setting, that.sheet, [newNode], false);
                        that.setTreeSelected(newNode);
                        that.sheet.setSelection(newNode.serialNo(), sels[0].col, 1, 1);
                        that.sheet.showRow(newNode.serialNo(), GC.Spread.Sheets.VerticalPosition.center);
                        if(typeof cbTools !== 'undefined'){
                            cbTools.refreshFormulaNodes();
                        }
                    });
                }
            }
        };
        controller.prototype.insertByID = function (ID) {
            var newNode = null, that = this,  sels = this.sheet.getSelections();
            if (this.tree) {
                if (this.tree.selected) {
                    newNode = this.tree.insertByID(ID, this.tree.selected.getParentID(), this.tree.selected.getNextSiblingID());
                } else {
                    newNode = this.tree.insertByID(ID);
                }
                if (newNode) {
                    TREE_SHEET_HELPER.massOperationSheet(this.sheet, function () {
                        that.sheet.addRows(newNode.serialNo(), 1);
                        TREE_SHEET_HELPER.refreshTreeNodeData(that.setting, that.sheet, [newNode], false);
                        that.setTreeSelected(newNode);
                        that.sheet.setSelection(newNode.serialNo(), sels[0].col, 1, 1);
                        //that.sheet.showRow(newNode.serialNo(), GC.Spread.Sheets.VerticalPosition.center);
                    });
                }
            }
            return newNode;
        };
        controller.prototype.delete = function () {
            var that = this, sels = this.sheet.getSelections();
            if (this.tree.selected) {
                if (this.tree.delete(this.tree.selected)) {
                    TREE_SHEET_HELPER.massOperationSheet(this.sheet, function () {
                        that.sheet.deleteRows(sels[0].row, that.tree.selected.posterityCount() + 1);
                        that.setTreeSelected(that.tree.items[sels[0].row] ? that.tree.items[sels[0].row] : that.tree.items[that.tree.items.length - 1]);
                    });
                    if(typeof cbTools !== 'undefined'){
                        cbTools.refreshFormulaNodes();
                    }
                }
            }
        };
        controller.prototype.m_delete = function (nodes, beginRow = null) {//删除选中的多行节点
            var that = this, sels = this.sheet.getSelections();
            if (this.tree.selected) {
                if (this.tree.m_delete(nodes)) {
                    TREE_SHEET_HELPER.massOperationSheet(this.sheet, function () {
                        let rowCount = 0;
                        for(let node of nodes){
                            rowCount = rowCount+node.posterityCount() + 1;
                        }
                        if(beginRow){
                            sels[0].row = beginRow;
                        }
                        that.sheet.deleteRows(sels[0].row, rowCount);
                        if(sels[0].row >=  that.tree.items.length){
                            sels[0].row = that.tree.items.length-1;
                            sels[0].colCount = 1;
                        }
                        that.setTreeSelected(that.tree.items[sels[0].row]);
                        that.sheet.setSelection(sels[0].row,sels[0].col,1,sels[0].colCount);
                    });
                    if(typeof cbTools !== 'undefined'){
                        cbTools.refreshFormulaNodes();
                    }
                }
            }
        };
        controller.prototype.singleDelete = function () {//只删除当前节点，不删除子节点
            var that = this, sels = this.sheet.getSelections();
            if (this.tree.selected) {
                if (this.tree.singleDelete(this.tree.selected)) {
                    TREE_SHEET_HELPER.massOperationSheet(this.sheet, function () {
                        that.sheet.deleteRows(sels[0].row,1);
                        that.setTreeSelected(that.tree.items[sels[0].row]);
                    });
                }
            }
        };

        controller.prototype.deleteNode = function (node,next) {
            var that = this;
            if (node){
                var row = node.serialNo();
                if (this.tree.delete(node)) {
                    TREE_SHEET_HELPER.massOperationSheet(this.sheet, function () {
                        that.sheet.deleteRows(row,1);
                        next?that.setTreeSelected(that.tree.items[row]):"";
                    });
                    if(typeof cbTools !== 'undefined'){
                        cbTools.refreshFormulaNodes();
                    }
                }
            }
        };
        controller.prototype.upLevel = function () {
            var that = this;
            if (this.tree.selected) {
                if (this.tree.selected.upLevel()) {
                    TREE_SHEET_HELPER.massOperationSheet(this.sheet, function () {
                        TREE_SHEET_HELPER.refreshNodesVisible([that.tree.selected], that.sheet, true);
                        that.sheet.showRow(that.tree.selected.serialNo(), GC.Spread.Sheets.VerticalPosition.center);
                        if (that.event.refreshBaseActn) {
                            that.event.refreshBaseActn(that.tree);
                        }
                    });
                }
            }
        };
        controller.prototype.multiUpLevel = function (nodes) {
            nodes.forEach(node => node.upLevel());
            TREE_SHEET_HELPER.massOperationSheet(this.sheet, () => {
                TREE_SHEET_HELPER.refreshNodesVisible(nodes, this.sheet, true);
                this.sheet.showRow(nodes[0].serialNo(), GC.Spread.Sheets.VerticalPosition.center);
                if (this.event.refreshBaseActn) {
                    this.event.refreshBaseActn(this.tree);
                }
            });
        };
        controller.prototype.downLevel = function () {
            var that = this;
            if (this.tree.selected) {
                if (this.tree.selected.downLevel()) {
                    TREE_SHEET_HELPER.massOperationSheet(that.sheet, function () {
                        TREE_SHEET_HELPER.refreshNodesVisible([that.tree.selected.parent], that.sheet, true);
                        that.sheet.showRow(that.tree.selected.serialNo(), GC.Spread.Sheets.VerticalPosition.center);
                        if (that.event.refreshBaseActn) {
                            that.event.refreshBaseActn(that.tree);
                        }
                    });
                }
            }
        };
        controller.prototype.multiDownLevel = function (nodes) {
            nodes.forEach(node => node.downLevel());
            const firstNode = nodes[0];
            TREE_SHEET_HELPER.massOperationSheet(this.sheet, () => {
                TREE_SHEET_HELPER.refreshNodesVisible([firstNode.parent], this.sheet, true);
                this.sheet.showRow(firstNode.serialNo(), GC.Spread.Sheets.VerticalPosition.center);
                if (this.event.refreshBaseActn) {
                    this.event.refreshBaseActn(this.tree);
                }
            });
        };
        controller.prototype.upMove = function () {
            var that = this, sels = this.sheet.getSelections();
            if (this.tree.selected) {
                TREE_SHEET_HELPER.massOperationSheet(this.sheet, function () {
                TREE_SHEET_HELPER.refreshChildrenVisiable(that.sheet,that.tree,that.tree.selected,that.tree.selected.serialNo(),true);//为了处理移动前子项是隐藏的情况，先把所有的列设置为显示
                TREE_SHEET_HELPER.refreshChildrenVisiable(that.sheet,that.tree,that.tree.selected.preSibling,that.tree.selected.preSibling.serialNo(),true);
                    if (that.tree.selected.upMove()) {
                        TREE_SHEET_HELPER.refreshTreeNodeData(that.setting, that.sheet, [that.tree.selected, that.tree.selected.nextSibling], true);
                        TREE_SHEET_HELPER.refreshChildrenVisiable(that.sheet,that.tree,that.tree.selected,that.tree.selected.serialNo());
                        TREE_SHEET_HELPER.refreshChildrenVisiable(that.sheet,that.tree,that.tree.selected.nextSibling,that.tree.selected.nextSibling.serialNo());
                        that.sheet.setSelection(that.tree.selected.serialNo(), sels[0].col, 1, 1);
                        if (that.event.refreshBaseActn) {
                            that.event.refreshBaseActn(that.tree);
                        }
                    }
                });
            }
        };
        controller.prototype.multiUpMove = function (nodes) {
            TREE_SHEET_HELPER.massOperationSheet(this.sheet, () => {
                const { row, col, rowCount, colCount } = this.sheet.getSelections()[0];
                nodes.forEach(node => {
                    TREE_SHEET_HELPER.refreshChildrenVisiable(this.sheet, this.tree, node, node.serialNo(), true); //为了处理移动前子项是隐藏的情况
                });
                const preNode = nodes[0].preSibling;
                TREE_SHEET_HELPER.refreshChildrenVisiable(this.sheet, this.tree, preNode, preNode.serialNo(), true);
                nodes.forEach(node => node.upMove());
                TREE_SHEET_HELPER.refreshTreeNodeData(this.setting, this.sheet, [...nodes, preNode], true);
                nodes.forEach(node => TREE_SHEET_HELPER.refreshChildrenVisiable(this.sheet, this.tree, node, node.serialNo()));
                TREE_SHEET_HELPER.refreshChildrenVisiable(this.sheet, this.tree, preNode, preNode.serialNo());
                this.sheet.setSelection(row - preNode.posterityCount() - 1, col, rowCount, colCount);
                if (this.event.refreshBaseActn) {
                    this.event.refreshBaseActn(this.tree);
                }
            });
        };
        controller.prototype.multiDownMove = function (nodes) {
            TREE_SHEET_HELPER.massOperationSheet(this.sheet, () => {
                const { row, col, rowCount, colCount } = this.sheet.getSelections()[0];
                nodes.forEach(node => {
                    TREE_SHEET_HELPER.refreshChildrenVisiable(this.sheet, this.tree, node, node.serialNo(), true); //为了处理移动前子项是隐藏的情况
                });
                const nextNode = nodes[nodes.length - 1].nextSibling;
                TREE_SHEET_HELPER.refreshChildrenVisiable(this.sheet, this.tree, nextNode, nextNode.serialNo(), true);
                for (let i = nodes.length - 1; i >= 0; i--) {
                    nodes[i].downMove();
                }
                TREE_SHEET_HELPER.refreshTreeNodeData(this.setting, this.sheet, [...nodes, nextNode], true);
                nodes.forEach(node => TREE_SHEET_HELPER.refreshChildrenVisiable(this.sheet, this.tree, node, node.serialNo()));
                TREE_SHEET_HELPER.refreshChildrenVisiable(this.sheet, this.tree, nextNode, nextNode.serialNo());
                this.sheet.setSelection(row + nextNode.posterityCount() + 1, col, rowCount, colCount);
                if (this.event.refreshBaseActn) {
                    this.event.refreshBaseActn(this.tree);
                }
            });
        };
        controller.prototype.downMove = function () {
            var that = this, sels = this.sheet.getSelections();
            if (this.tree.selected) {
                TREE_SHEET_HELPER.massOperationSheet(this.sheet, function () {
                    TREE_SHEET_HELPER.refreshChildrenVisiable(that.sheet,that.tree,that.tree.selected,that.tree.selected.serialNo(),true);//为了处理移动前子项是隐藏的情况，先把所有的列设置为显示
                    TREE_SHEET_HELPER.refreshChildrenVisiable(that.sheet,that.tree,that.tree.selected.nextSibling,that.tree.selected.nextSibling.serialNo(),true);
                    if (that.tree.selected.downMove()) {
                        TREE_SHEET_HELPER.refreshTreeNodeData(that.setting, that.sheet, [that.tree.selected, that.tree.selected.preSibling], true);
                        TREE_SHEET_HELPER.refreshChildrenVisiable(that.sheet,that.tree,that.tree.selected,that.tree.selected.serialNo());
                        TREE_SHEET_HELPER.refreshChildrenVisiable(that.sheet,that.tree,that.tree.selected.preSibling,that.tree.selected.preSibling.serialNo());
                        that.sheet.setSelection(that.tree.selected.serialNo(), sels[0].col, 1, 1);
                        if (that.event.refreshBaseActn) {
                            that.event.refreshBaseActn(that.tree);
                        }
                    }
                });
            }
        };

        controller.prototype.refreshTreeNode = function (nodes,recursive,autoFit) {
            var that = this;
            TREE_SHEET_HELPER.massOperationSheet(this.sheet, function () {
                TREE_SHEET_HELPER.refreshTreeNodeData(that.setting, that.sheet, nodes, recursive,autoFit)
            })
        }

        controller.prototype.setTreeSelected = function (node) {
            if (this.event.beforeTreeSelectedChange) {
                this.event.beforeTreeSelectedChange(this.tree.selected);
            }
            this.tree.selected = node;
            if (this.event.refreshBaseActn) {
                this.event.refreshBaseActn(this.tree);
            }
            if (this.event.treeSelectedChanged) {
                this.event.treeSelectedChanged(this.tree.selected);
            }
        }

        controller.prototype.bind = function (eventName, eventFun) {
            this.event[eventName] = eventFun;
        };

        // 获取有效的选中同层节点
        // 如果选中的节点内，有比第一个选中节点深度小的节点，则此选中范围内无有效节点
        // 如果没用上述的情况，则有效选中节点为，跟第一个选中节点深度相同的节点
        controller.prototype.getValidNodesWithinSelection = function () {
            const selection = this.sheet.getSelections()[0];
            if (!selection || !commonUtil.isDef(selection.row)) {
                return [];
            }
            const nodes = [];
            let firstNode;
            let firstNodeDepth;
            const maxRow = selection.row + selection.rowCount;
            for (let row = selection.row; row < maxRow; row++) {
                const node = this.tree.items[row];
                if (!node) {
                    return [];
                }
                const depth = node.depth();
                if (!firstNode) {
                    firstNode = node;
                    firstNodeDepth = firstNode.depth();
                }
                if (depth < firstNodeDepth) {
                    return [];
                }
                if (depth === firstNodeDepth) {
                    nodes.push(node);
                }
            }
            return nodes;
        };

        return new controller();
    },
    eventName: {
        refreshBaseActn: 'refreshBaseActn',
        beforeTreeSelectedChange: 'beforeTreeSelectedChange',
        treeSelectedChanged: 'treeSelectedChanged',
        cellDoubleClick: 'cellDoubleClick'
    }
};
