/**
 * Created by Mai on 2017/6/21.
 */

var projectObj = {
    project: null,
    mainSpread: null,
    mainController: null,
    gljSpreed:null,
    beforeMainTreeSelectedChange: function (node) {
        if (node) {
            subViewObj.saveComments(node);
        }
    },
    checkCommonField: function (editingText, colSetting) {
        let value;
        if (colSetting.data.decimal) {
            value = Number(editingText);
            if (number_util.isNumber(value)) {
                value = value.toDecimal(colSetting.data.decimal);
            } else {
                value = null;
                alert('当前输入的数据类型不正确，请重新输入。');
            }
        } else {
            value = editingText;
        }
        return value;
    },
    checkQuantityField: function (editingText, colSetting) {
        let value = Number(editingText);
        if (!value) {
            try {
                let exp = new Expression('');
                exp.Expression(editingText);
                value = Number(exp.Evaluate());
            } catch (error) {
                value = null;
            }
        }
        if (value) {
            value = value.toDecimal(colSetting.data.decimal);
        } else {
            value = null;
            alert('当前输入的数据类型不正确，请重新输入。');
        }
        return value;
    },
    checkSpreadEditingText: function (editingText, colSetting) {
        if (colSetting.data.field === 'quantity') {
            return this.checkQuantityField(editingText, colSetting);
        } else {
            return this.checkCommonField(editingText, colSetting);
        }
    },
    mainSpreadEditEnded: function (sender, info) {
        let project = projectObj.project;
        let node = project.mainTree.items[info.row];
        let colSetting = projectObj.mainController.setting.cols[info.col];
        let fieldName = projectObj.mainController.setting.cols[info.col].data.field;
        let value = projectObj.checkSpreadEditingText(info.editingText, colSetting);
        let validate = project.quantity_detail.quantityEditChecking(value,node,fieldName);

        if (colSetting.data.wordWrap) {
            info.sheet.autoFitRow(info.row);
        }
        if (value && value != calcFees.getFee(node.data, fieldName)&&validate) {
            if (node.sourceType === project.Bills.getSourceType()) {
                project.Bills.updateField(node.source, fieldName, value);
            } else if (node.sourceType === project.Ration.getSourceType()) {
                project.Ration.updateField(node.source, fieldName, value);
            } else if (node.sourceType === project.VolumePrice.getSourceType()) {
                project.VolumePrice.updateField(node.source, fieldName, value);
            }
        }
        projectObj.mainController.refreshTreeNode([node]);
    },
    checkMainSpread: function () {
        if (!this.mainSpread) {
            this.mainSpread = SheetDataHelper.createNewSpread($('#billsSpread')[0]);
            this.mainSpread.getActiveSheet().selectionPolicy(GC.Spread.Sheets.SelectionPolicy.single);
        }
    },
    refreshMainSpread: function () {
        if (this.mainSpread) {
            this.mainSpread.refresh();
        }
    },
    loadProjectData: function () {
        var that = this;
        this.project = PROJECT.createNew(scUrlUtil.GetQueryString('project'), userID);
        this.project.loadDatas(function (err) {
            if (!err) {
                let str = JSON.stringify(that.project.projSetting.main_tree_col);
                that.project.projSetting.mainGridSetting = JSON.parse(str);
                that.project.projSetting.mainGridSetting.frozenCols = 4;
                TREE_SHEET_HELPER.initSetting($('#billsSpread')[0], that.project.projSetting.mainGridSetting);
                that.project.projSetting.mainGridSetting.cols.forEach(function (col) {
                    col.data.splitFields = col.data.field.split('.');
                    if (col.data.getText && Object.prototype.toString.apply(col.data.getText) === "[object String]") {
                        col.data.getText = MainTreeCol.getEvent(col.data.getText);
                    }
                    if (col.readOnly && Object.prototype.toString.apply(col.readOnly) === "[object String]") {
                        col.readOnly = MainTreeCol.getEvent(col.readOnly);
                    }
                    if (col.data.cellType && Object.prototype.toString.apply(col.data.cellType) === "[object String]") {
                        let getCellType = MainTreeCol.getEvent(col.data.cellType);
                        col.data.cellType = getCellType();
                    }
                    if (col.data.digit && Object.prototype.toString.apply(col.data.digit) === "[object String]") {
                        col.data.decimal = that.project.getDecimal(col.data.digit);
                        col.data.formatter = MainTreeCol.getNumberFormatter(col.data.decimal);
                    }
                });
                that.mainController = TREE_SHEET_CONTROLLER.createNew(that.project.mainTree, that.mainSpread.getActiveSheet(), that.project.projSetting.mainGridSetting);
                that.mainController.showTreeData();
                that.mainController.bind('refreshBaseActn', function (tree) {
                    var setButtonValid = function (valid, btn) {
                        if (valid) {
                            btn.removeClass('disabled');
                        } else {
                            btn.addClass('disabled');
                        }
                    };
                    let selected = tree.selected;
                    let canUpLevel = function (node) {
                        if (selected && selected.depth() > 0 && selected.canUpLevel()) {
                            if (selected.sourceType === that.project.Bills.getSourceType()) {
                                return (!selected.nextSibling) || (selected.children.length === 0) || (selected.source.children.length > 0);
                            } else {
                                return false;
                            }
                        } else {
                            return false;
                        }
                    };
                    let canDownLevel = function (node) {
                        if (selected && selected.depth() > 0 && selected.canDownLevel()) {
                            if (selected.sourceType === that.project.Bills.getSourceType()) {
                                return (selected.preSibling.children.length === 0) || (selected.preSibling.source.children.length > 0);
                            } else {
                                return false;
                            }
                        } else {
                            return false;
                        }
                    };
                    let canDelete = function (node) {
                        if (selected) {
                            if (selected.sourceType === that.project.Bills.getSourceType()) {
                                return !(selected.data.flagsIndex && selected.data.flagsIndex.fixed && selected.data.flagsIndex.fixed.flag > 0);
                            } else {
                                return true;
                            }
                        } else {
                            return false;
                        }
                    };
                    setButtonValid(canUpLevel(selected), $('#upLevel'));
                    setButtonValid(canDownLevel(selected), $('#downLevel'));
                    setButtonValid(selected && (selected.depth() > 0) && selected.canUpMove(), $('#upMove'));
                    setButtonValid(selected && (selected.depth() > 0) && selected.canDownMove(), $('#downMove'));
                    setButtonValid(canDelete(selected), $('#delete'));
                });

              /*  if(!projectObj.gljSpreed){
                    projectObj.gljSpreed = gljView.buildSheet($("#gljSpread")[0]);
                    that.loadGLJSpreadContextMenu();
                }*/

                that.project.calcProgram = new CalcProgram(that.project);
                that.project.calcProgram.compileAllTemps();

                that.mainController.bind(TREE_SHEET_CONTROLLER.eventName.beforeTreeSelectedChange, that.beforeMainTreeSelectedChange);
                that.mainController.bind(TREE_SHEET_CONTROLLER.eventName.treeSelectedChanged, function (node) {
                    subViewObj.loadComments(node);
                    gljOprObj.showDataIfRationSelect(node);

                    // CSL.2017.07.25
                    if (SubActiveSheetNameIs('JSCX')) {
                        if (node.sourceType === that.project.Bills.getSourceType() || node.sourceType === that.project.Ration.getSourceType()) {
                            calcProgramObj.showData(node);
                        } else {
                            calcProgramObj.clearData();
                        };
                    };
                    //zhong 2017-9-1 特征及内容
                    if(pageCCOprObj.active){
                        pageCCOprObj.mainActiveCell = projectObj.mainSpread.getActiveSheet().getSelections()[0];//mainSpread焦点单元格
                        if(node.sourceType === that.project.Bills.getSourceType()){
                            pageCCOprObj.setCacheAndShow(node);
                        }
                        else{
                            pageCCOprObj.clearData();
                        }
                    }
                });

                that.mainSpread.bind(GC.Spread.Sheets.Events.EditEnded, that.mainSpreadEditEnded);

                that.loadMainSpreadContextMenu();
            }
            else {

            }
        });

    },
    loadMainSpreadContextMenu: function () {
        var project = this.project, spread = this.mainSpread, controller = this.mainController;
        $.contextMenu({
            selector: '#billsSpread',
            build: function ($trigger, e) {
                var target = SheetDataHelper.safeRightClickSelection($trigger, e, spread);
                controller.setTreeSelected(controller.tree.items[target.row]);
                return target.hitTestType === GC.Spread.Sheets.SheetArea.viewport || target.hitTestType === GC.Spread.Sheets.SheetArea.rowHeader;
            },
            items: {
                "insertBills": {
                    name: "插入清单",
                    icon: 'fa-sign-in',
                    disabled: function () {
                        return project.mainTree.selected ? project.mainTree.selected.sourceType !== project.Bills.getSourceType() : false;
                    },
                    callback: function (key, opt) {
                        ProjectController.addBills(project, controller);
                    }
                },
                "insertRation": {
                    name: "插入定额",
                    icon: 'fa-sign-in',
                    disabled: function () {
                        var selected = project.mainTree.selected;
                        if (selected) {
                            if (selected.sourceType === project.Ration.getSourceType()) {
                                return false;
                            } else if (selected.sourceType === project.Bills.getSourceType()) {
                                if (selected.source.children.length === 0) {
                                    return selected.children.length !== 0 ? selected.firstChild().sourceType !== project.Ration.getSourceType() : false;
                                } else {
                                    return true;
                                }
                            } else if (selected.sourceType === project.VolumePrice.getSourceType()) {
                                return true;
                            };
                        } else {
                            return true;
                        }
                    },
                    callback: function (key, opt) {
                        ProjectController.addRation(project, controller);
                    }
                },
                "insertLJ": {
                    name: "插入量价",
                    icon: 'fa-sign-in',
                    disabled: function () {
                        var selected = project.mainTree.selected;
                        if (selected) {
                            if (selected.sourceType === project.Ration.getSourceType()) {
                                return true;
                            } else if (selected.sourceType === project.Bills.getSourceType()) {
                                if (selected.source.children.length === 0) {
                                    return selected.children.length !== 0 ? selected.firstChild().sourceType !== project.VolumePrice.getSourceType() : false;
                                } else {
                                    return true;
                                }
                            } else if (selected.sourceType === project.VolumePrice.getSourceType()) {
                                return false;
                            };
                        } else {
                            return true;
                        }
                    },
                    callback: function (key, opt) {
                        ProjectController.addVolumePrice(project, controller);
                    }
                },
                "spr1": '--------',
                "delete": {
                    name: '删除',
                    icon: 'fa-remove',
                    disabled: function () {
                        var selected = project.mainTree.selected;
                        return !selected;
                    },
                    callback: function () {
                        var selected = controller.tree.selected;
                        if (selected) {
                            if (selected.sourceType === project.Bills.getSourceType()) {
                                project.Bills.deleteBills(selected.source);
                                controller.delete();
                            } else if (selected.sourceType === project.Ration.getSourceType()) {
                                project.Ration.delete(selected.source);
                                controller.delete();
                            } else if (selected.sourceType === project.VolumePrice.getSourceType()) {
                                project.VolumePrice.delete(selected.source);
                                controller.delete();
                            };
                        }
                    }
                },
                "spr2":'--------',
                "calculateAll_RationContent": {
                    name: '造价计算(子目含量取费)',
                    callback: function () {
                        ProjectController.calculateAll(project, controller, rationContent);
                    }
                },
                "calculateAll_RationPrice": {
                    name: '造价计算(子目单价取费)',
                    callback: function () {
                        ProjectController.calculateAll(project, controller, rationPrice);
                    }
                },
                "calculateAll_RationPriceConverse": {
                    name: '造价计算(子目单价取费-反算)',
                    callback: function () {
                        ProjectController.calculateAll(project, controller, rationPriceConverse);
                    }
                },
                "calculateAll_BillsPrice": {
                    name: '造价计算(清单单价取费)',
                    callback: function () {
                        ProjectController.calculateAll(project, controller, billsPrice);
                    }
                }
            }
        });
    }
};

$('#insert').click(function () {
    var controller = projectObj.mainController, project = projectObj.project;
    var selected = controller.tree.selected;

    if (!selected || selected.sourceType === project.Bills.getSourceType()) {
        ProjectController.addBills(project, controller);
    } else if (selected.sourceType === project.Ration.getSourceType()) {
        ProjectController.addRation(project, controller);
    } else if (selected.sourceType === project.VolumePrice.getSourceType()) {
        ProjectController.addVolumePrice(project, controller);
    }
});
$('#delete').click(function () {
    var controller = projectObj.mainController, project = projectObj.project;
    var selected = controller.tree.selected;

    if (selected) {
        if (selected.sourceType === project.Bills.getSourceType()) {
            project.Bills.deleteBills(selected.source);
            controller.delete();
        } else if (selected.sourceType === project.Ration.getSourceType()) {
            project.Ration.delete(selected.source);
            controller.delete();
        } else if (selected.sourceType === project.VolumePrice.getSourceType()) {
            project.VolumePrice.delete(selected.source);
            controller.delete();
        };
    }
});
$('#upLevel').click(function () {
    var controller = projectObj.mainController, project = projectObj.project;
    var selected = controller.tree.selected;

    if (selected && selected.sourceType === project.Bills.getSourceType()) {
        project.Bills.upLevelBills(selected.source);
        controller.upLevel();
    }
});
$('#downLevel').click(function () {
    var controller = projectObj.mainController, project = projectObj.project;
    var selected = controller.tree.selected;
    if (selected && selected.sourceType === project.Bills.getSourceType()) {
        project.Bills.downLevelBills(selected.source);
        controller.downLevel();
    }
});
$('#upMove').click(function () {
    var controller = projectObj.mainController, project = projectObj.project;
    var selected = controller.tree.selected, pre, preSerialNo;

    if (selected.sourceType === project.Bills.getSourceType()) {
        project.Bills.upMoveBills(selected.source);
        controller.upMove();
    } else if (selected.sourceType === project.Ration.getSourceType()) {
        project.Ration.changePos(selected.source, selected.preSibling.source);
        controller.upMove();
    } else if (selected.sourceType === project.VolumePrice.getSourceType()) {
        project.VolumePrice.changePos(selected.source, selected.preSibling.source);
        controller.upMove();
    }
});
$('#downMove').click(function () {
    var controller = projectObj.mainController, project = projectObj.project;
    var selected = controller.tree.selected, next, nextSerialNo;

    if (selected.sourceType === project.Bills.getSourceType()) {
        project.Bills.downMoveBills(selected.source);
        controller.downMove();
    } else if (selected.sourceType === project.Ration.getSourceType()) {
        project.Ration.changePos(selected.source, selected.nextSibling.source);
        controller.downMove();
    } else if (selected.sourceType === project.VolumePrice.getSourceType()) {
        project.VolumePrice.changePos(selected.source, selected.nextSibling.source);
        controller.downMove();
    }
});

