/**
 * Created by Zhong on 2017/12/1.
 */
/*
* 计算基数,清单、定额统一ui
* */
let calcBaseView = {
    //可用计算基数的清单固定列映射(与fixedFlag)
    inputExpr: $('#calcBaseExp'),
    confirmBtn: $('#calcBaseFeeRateConf'),//org:calcBaseConf
    type: {bills: 'bills', ration: 'ration'},
    billsCBClass:{ALL: [], FBFX: [], CSXM: [], QTXM: [], FBF: [], RCJ: [], GF: [], SJ: [], SQGCZJ: []},
    curType: null,
    editingCell: null,
    workBook: null,
    setting:{
        billsHeader: [
            {name: '计算基础名称', dataCode: 'base', width: 300, vAlign: 'center', hAlign: 'left'},
            {name: '金额', dataCode: 'price', width: 100, vAlign: 'center', hAlign: 'right'}
        ],
        rationHeader: [
            {name: '定额计算程序基数名称', dataCode: 'base', width: 400, vAlign: 'center', hAlign: 'left'}
        ],
        options: {
            tabStripVisible:  false,
            allowCopyPasteExcelStyle : false,
            allowExtendPasteRange: false,
            allowUserDragDrop : false,
            allowUserDragFill: false,
            scrollbarMaxAlign : true
        },
        locked: {
            rows: [],
            cols: [0]
        }
    },

    renderSheetFuc: function (sheet, fuc) {
        sheet.suspendPaint();
        sheet.suspendEvent();
        fuc();
        sheet.resumePaint();
        sheet.resumeEvent();
    },

    setOptions: function (workbook, opts) {
        for(let opt in opts){
            workbook.options[opt] = opts[opt];
        }
    },

    buildHeader: function (sheet, headers) {
        let me = calcBaseView;
        let fuc = function () {
            sheet.options.clipBoardOptions = GC.Spread.Sheets.ClipboardPasteOptions.values;
            sheet.options.isProtected = true;
            sheet.options.protectionOptions = {
                allowResizeColumns: true
            };
            sheet.setColumnCount(headers.length);
            sheet.setRowHeight(0, 20, GC.Spread.Sheets.SheetArea.colHeader);
            sheet.setColumnWidth(0, 20, GC.Spread.Sheets.SheetArea.rowHeader);
            for(let i = 0, len = headers.length; i < len; i++){
                sheet.setValue(0, i, headers[i].name, GC.Spread.Sheets.SheetArea.colHeader);
                sheet.setColumnWidth(i, headers[i].width, GC.Spread.Sheets.SheetArea.colHeader);
            }
        };
        me.renderSheetFuc(sheet, fuc);
    },

    buildSheet: function () {
        if(!this.workBook){
            this.workBook = new GC.Spread.Sheets.Workbook($('#billsBaseSpread')[0], {sheetCount: 1});
            sheetCommonObj.spreadDefaultStyle(this.workBook);
            this.setOptions(this.workBook, this.setting.options);
            //bills
            if(this.curType === this.type.bills){
                this.setting.header = this.setting.billsHeader;
            }
            //ration
            else {
                this.setting.header = this.setting.rationHeader;
            }
            this.buildHeader(this.workBook.getActiveSheet(), this.setting.header);
            this.bindEvent(this.workBook);
        }
    },

    bindEvent: function (workBook) {
        const _events = GC.Spread.Sheets.Events;
        let sheet = workBook.getActiveSheet();
        sheet.bind(_events.CellDoubleClick, this.onCellDoubleClick);
    },

    showData(datas){
        let me = calcBaseView;
        let sheet = this.workBook.getActiveSheet();
        let cols = this.setting.header;
        let fuc = function () {
            sheet.setRowCount(datas.length);
            let style = new GC.Spread.Sheets.Style();
            //style.formatter = MainTreeCol.getNumberFormatter(decimalObj.bills.totalPrice, true);
            sheet.setStyle(-1, 1, style);
            for(let col = 0, cLen = cols.length; col < cLen; col++){
                sheet.getRange(-1, col, -1, 1).hAlign(GC.Spread.Sheets.HorizontalAlign[cols[col]['hAlign']]);
                sheet.getRange(-1, col, -1, 1).vAlign(GC.Spread.Sheets.VerticalAlign[cols[col]['vAlign']]);
                for(let row = 0, rLen = datas.length; row < rLen; row++){
                    sheet.setValue(row, col, datas[row][cols[col]['dataCode']]);
                }
            }
        };
        this.renderSheetFuc(sheet, fuc);
    },

    onCellDoubleClick: function (sender, args) {
        let me = calcBaseView;
        if(args.col === 0){
            let v = args.sheet.getValue(args.row, args.col);
            if(!me.isDef(v)){
                return;
            }
            let baseFigure = '';
            if(me.curType == me.type.bills)
                baseFigure = `{${v}}`
            else if (me.curType == me.type.ration)
                baseFigure = `[${v}]`;
            if(baseFigure.trim() !== ''){
                //在光标后面插入
                let insertStr = me.insertStr(baseFigure);
                me.inputExpr.val(insertStr);
            }
        }
        me.workBook.focus(false);
        me.inputExpr.focus();
    },
    isDef: function (v) {
        return v !== undefined && v !== null;
    },
    //processMouseDown触发时间比SelectionChanged早，所以直接取selected是上一个节点的,需要传row取当前选中节点
    ifEdit: function (type, row) {
        if (type == 'ration'){
            return true;
        } else{
            let selected = projectObj.project.mainTree.items[row];
            return selected && MainTreeCol.readOnly.forCalcBase(selected)?false:true;
        }
    },
    bindClassBtn: function () {
        let me = this;
        for(let clas in me.billsCBClass){
            let jqS = `#cb_${clas}`;
            $(jqS).click(function () {
                sheetCommonObj.cleanData(me.workBook.getSheet(0), me.setting, -1);
                me.showData(me.billsCBClass[clas]);
                $('#cbClassList li .btn ').removeClass('btn btn-outline-secondary btn-sm active');
                $(this).addClass('btn btn-outline-secondary btn-sm active');
            });
        }
    },
    //计算基数转换为显示数据Obj to Array, 给清单基数分类赋值
    toViewData: function (obj) {
        let rst = [];
        for(let figure in obj){
            let figureObj = Object.create(null);
            figureObj.base = figure;
            figureObj.price = projectObj.project.calcBase.getBase(figure);
            rst.push(figureObj);
            //set class datas
            this.billsCBClass.ALL.push(figureObj);
        }
        return this.billsCBClass.ALL;
    },

    initCalctor: function (type) {//type = bills、ration
        let me = calcBaseView;
        let showDatas;
        me.inputExpr = $('#calcBaseExp');
        me.curType = type;
        //去除清单基数分类
        $('#cbClassList').hide();
        $('#cbRowDiv').removeClass('row');
        $('#billsBaseSpread').removeClass('col-9');
        if (type === me.type.bills) {
            try{
                //锁定的清单不显示
                if(projectObj.project.isBillsLocked() && projectObj.project.withinBillsLocked(projectObj.project.mainTree.selected)){
                    return;
                }
                let row = projectObj.mainSpread.getActiveSheet().getActiveRowIndex();
                let node = projectObj.project.mainTree.items[row];
                //输入框显示原本的
                if (me.isDef(node.data.calcBase)) {
                    me.inputExpr.val(cbParser.toFExpr(node.data.calcBase));
                }
                let baseObj = projectObj.project.calcBase.getBaseByClass(node);
                showDatas = me.toViewData(baseObj);
                $('#cbClassList li .btn ').removeClass('btn btn-outline-secondary btn-sm active');
                $('#cb_ALL').addClass('btn btn-outline-secondary btn-sm active');
            } catch (err) {
                alert(err);
            }
        } else if (type == me.type.ration) {
            let calcItem = calcProgramManage.getSelectionInfo().calcItem;
            if (calcItem.dispExprUser) {
                me.inputExpr.val(calcItem.dispExpr);
                if (calcItem.dispExpr == '0'){
                    me.inputExpr.focus();
                    me.inputExpr.select();
                }
            }
            let bnArr = Object.keys(rationCalcBases);
            // bnArr.sort();
            let baseArr = [];
            for (let bn of bnArr) {
                baseArr.push({base: bn})
            };
            showDatas = baseArr;
        }

        me.buildSheet();
        me.showData(showDatas);
        //$('#qd-jsjs').modal('show');
        $('#calcBaseFeeRate').modal('show');
    },

    getInputExpr: function () {
        return this.inputExpr.val();
    },

    //四则运算符控制，不可连续出现: ++ +*...
    arithmeticLegal: function (v) {
        let rex = /[\+,\-,\*,\/]{2}/g;
        let rex2 = /[{]{2}/g;
        let rex3 = /[}]{2}/g;
        let rex4 = /[F]{2}/g;
        let rex5 = /[.]{2}/g;
        let rex6 = /[%]{2}/g;
        return !rex.test(v) && !rex2.test(v) && !rex3.test(v) && !rex4.test(v) && !rex5.test(v) && !rex6.test(v);
    },

    //运算符点击显示到运算窗口
    clickOpr: function (operators) {
        let me = calcBaseView;
        for(let i = 0, len = operators.length; i < len; i++){
            operators[i].bind('click', function () {
                let v = $(this)[0].textContent;
                let insertStr = me.insertStr(v);
                me.inputExpr.val(insertStr);
                /*if(me.arithmeticLegal(insertStr)){
                    me.inputExpr.val(insertStr);
                }*/
                me.inputExpr.focus();
            });
        }
    },

    //光标处插入（替换选中）
    insertStr: function (v) {
        let me = calcBaseView;
        //在光标后面插入
        let exp = me.getInputExpr();
        let startIdx = me.inputExpr[0].selectionStart;
        let endIdx = me.inputExpr[0].selectionEnd;
        let startStr = exp.substring(0, startIdx);
        let endStr = exp.substring(endIdx, exp.length);
        return startStr + v + endStr;
    },

    //输入窗口控制
    inputControl: function () {
        let me = calcBaseView;
        me.inputExpr.on('input',function () {
            if(!me.arithmeticLegal(me.inputExpr.val())){
                if(me.preInputExpr){
                    me.inputExpr.val(me.preInputExpr);
                }
            }
            me.preInputExpr = me.inputExpr.val();
        });
    },

    //确认按钮
    calcBaseConf: function () {
        let me = calcBaseView;
        me.confirmBtn.bind('click', function () {
            //通过什么触发：计算基数、综合合价
            let toggle = me.confirmBtn.attr('toggle');
            if(!toggle || toggle !== 'calcBase'){
                return;
            }
            //bills
            if(me.curType === me.type.bills){
                let selected = projectObj.project.mainTree.selected;
                projectObj.updateCellValue(selected, me.getInputExpr(), {data: {field: 'calcBase'}});
                if(projectObj.project.calcBase.success || selected.data.calcBase === me.getInputExpr()){
                    //$('#qd-jsjs').modal('hide');
                    $('#calcBaseFeeRate').modal('hide');
                }
            }
            else if (me.curType === me.type.ration) {
                let expr = me.inputExpr.val();
                expr = analyzer.standard(expr);
                me.inputExpr.val(expr);

                let template = calcProgramManage.getSelectionInfo().template;
                let calcItem = calcProgramManage.getSelectionInfo().calcItem;

                if (calcItem.dispExpr != expr){
                    if (analyzer.isLegal(expr, calcItem.ID, template)){
                        let cp = projectObj.project.calcProgram;
                        let lc = analyzer.calcItemLabourCoe(calcItem);
                        calcItem.dispExpr = expr;
                        calcItem.dispExprUser = analyzer.getDispExprUser(expr, lc);
                        calcItem.expression = analyzer.getExpression(expr, template);
                        calcItem.compiledExpr = analyzer.getCompiledExpr(calcItem.expression, lc);
                        calcItem.statement = analyzer.getStatement(calcItem.expression, template);

                        let data = {
                            'projectID': projectObj.project.ID(),
                            'templatesID': template.ID,
                            'calcItem': calcItem
                        };
                        calcProgramManage.saveCalcItem(data, function (rst) {
                            if (rst){
                                cp.compileTemplate(template);
                                let relationNodes = calcTools.getNodesByProgramID(template.ID);
                                cp.calcNodesAndSave(relationNodes);
                                calcProgramManage.refreshDetailSheet();
                                //$('#qd-jsjs').modal('hide');
                                $('#calcBaseFeeRate').modal('hide');
                                $.bootstrapLoading.end();
                            }
                        });
                    }
                    else{
                        $('#errorInfo').html(analyzer.error);
                    };
                }
                else{
                    //$('#qd-jsjs').modal('hide');
                    $('#calcBaseFeeRate').modal('hide');
                }
            }
        });
    },
    onCalcBaseButtonClick:function (hitinfo,type='bills') {
        let me = calcBaseView;
        let node = projectObj.project.mainTree.items[hitinfo.row] ? projectObj.project.mainTree.items[hitinfo.row] : null;
        if(hitinfo.sheet.getParent() === projectObj.mainSpread){
            projectObj.mainController.setTreeSelected(node);
        }
        hitinfo.sheet.setActiveCell(hitinfo.row, hitinfo.col);
        calcBaseView.confirmBtn.attr('toggle', 'calcBase');
        changeCalcBaseFeeRate('calcBase');
        $('#tabCalcBase').tab('show');
        calcBaseView.initCalctor(type);
    }
};

$(document).ready(function () {
 /*   $('#qd-jsjs').on('shown.bs.modal', function () {
        calcBaseView.workBook.refresh();
    });*/
    $('#calcBaseFeeRate').on('shown.bs.modal', function () {
        let toggle = calcBaseView.confirmBtn.attr('toggle');
        if(toggle === 'calcBase'){
            $('#tabCalcBase').tab('show');
        }
        sheetCommonObj.refreshWorkbookDelDefer(calcBaseView.workBook, 100);
    });
    $('#tabCalcBase').on('shown.bs.tab', function () {
        sheetCommonObj.refreshWorkbookDelDefer(calcBaseView.workBook, 100);
    });

    /*$('#qd-jsjs').on('hidden.bs.modal', function () {
        $('#errorInfo').text('');
        //清空输入框
        calcBaseView.inputExpr.val('');
        calcBaseView.workBook.destroy();
        calcBaseView.workBook = null;
        //清空清单分类数据
        for(let attr in calcBaseView.billsCBClass){
            calcBaseView.billsCBClass[attr] = [];
        }
    });*/

    $('#calcBaseFeeRate').on('hidden.bs.modal', function () {
        $('#errorInfo').text('');
        //清空输入框
        calcBaseView.inputExpr.val('');
        if(calcBaseView.workBook){
            calcBaseView.workBook.destroy();
            calcBaseView.workBook = null;
        }
        //清空清单分类数据
        for(let attr in calcBaseView.billsCBClass){
            calcBaseView.billsCBClass[attr] = [];
        }
    });

    //bind operator click function
    calcBaseView.clickOpr([$('#addOpr'), $('#subOpr'), $('#mulOpr'), $('#divOpr'), $('#percentOpr'), $('#leftOpr'), $('#rightOpr')]);

    //bind input control
    //calcBaseView.inputControl();

    //confirmBtn
    calcBaseView.calcBaseConf();

    //class btn
    calcBaseView.bindClassBtn();
});