/**
 * Created by CSL on 2017-05-12.
 */

var gljOprObj = {
    sheet: null,
    libID: null,
    ration: null,
    sheetData:[],
    coeSheetData:[],
    checkb:null,
    coeSheet:null,
    assSheet:null,
    assSheetData:[],
    setting: {
        header: [
            {headerName: "编码", headerWidth: 100, dataCode: "code", dataType: "String", formatter: "@"},
            {headerName: "名称", headerWidth: 120, dataCode: "name", dataType: "String"},
            {headerName: "规格型号", headerWidth: 80, dataCode: "specs", dataType: "String", hAlign: "center"},
            {headerName: "单位", headerWidth: 60, dataCode: "unit", dataType: "String", hAlign: "center"},
            {headerName: "类别", headerWidth: 50, dataCode: "gljDistType", dataType: "String", hAlign: "center"},
            {headerName: "定额消耗量", headerWidth: 80, dataCode: "rationItemQuantity", dataType: "Number", hAlign: "right"},    // dataType: "Number", formatter: "0.00"
            {headerName: "自定义消耗量", headerWidth: 80, dataCode: "customQuantity", dataType: "Number", hAlign: "right"},
            {headerName: "消耗量", headerWidth: 80, dataCode: "quantity", dataType: "Number", hAlign: "right"},
            {headerName: "基价单价", headerWidth: 80, dataCode: "basePrice", dataType: "Number", hAlign: "right"},
            {headerName: "调整基价", headerWidth: 80, dataCode: "adjustPrice", dataType: "String", hAlign: "right"},
            {headerName: "市场单价", headerWidth: 80, dataCode: "marketPrice", dataType: "String", hAlign: "right"},
            {headerName: "市场单价调整", headerWidth: 80, dataCode: "marketPriceAdjust", dataType: "String", hAlign: "right"},
            {headerName: "是否暂估", headerWidth: 80, dataCode: "isEstimate", dataType: "String", hAlign: "center",vAlign:"center",cellType:"checkBox"}
        ],
        view: {
            comboBox: [{row: -1, col: 12, rowCount: -1, colCount: 1}],
            lockedCells: [{row: -1, col: 3, rowCount: -1, colCount: 1}],
            lockColumns:[0,1,2,3,4,5,7,8,9,10,12]
        },
        notEditedType: ['混凝土','砂浆','配合比','机械']
    },
    coeSetting:{
        header:[
            {headerName: "调整", headerWidth: 100, dataCode: "isAdjust", dataType: "String",cellType:"checkBox"},
            {headerName: "条件", headerWidth: 120, dataCode: "name", dataType: "String"},
            {headerName: "内容", headerWidth: 350, dataCode: "content", dataType: "String", hAlign: "center"}
        ],
        view:{
            lockColumns:[0,1,2]
        }
    },
    assSetting:{
        header:[
            {headerName: "调整名称", headerWidth: 100, dataCode: "name", dataType: "String"},
            {headerName: "定额值", headerWidth: 120, dataCode: "stdValue", dataType: "Number"},
            {headerName: "实际值", headerWidth: 120, dataCode: "actualValue", dataType: "Number"}
        ],
        view:{
            lockColumns:[0,1]
        }
    },

    initSheet: function(sheet) {
        var me = this;
        me.sheet = sheet;
        sheetCommonObj.initSheet(me.sheet, me.setting, 30);
        me.bindSheetEvent(sheet);
        sheet.bind(GC.Spread.Sheets.Events.CellClick, me.onCellClick);
        this.loadGLJSpreadContextMenu();
    },
    initCoeSheet:function (sheet) {
        var me = this;
        me.coeSheet = sheet;
        sheetCommonObj.initSheet(me.coeSheet, me.coeSetting, 30);
        me.bindSheetEvent(sheet);
        me.addDropDownList();
        sheet.bind(GC.Spread.Sheets.Events.CellClick, me.onCoeCellClick);
        subSpread.bind(GC.Spread.Sheets.Events.ButtonClicked,me.onCheckBoxClick);
    },
    initAssSheet: function(sheet) {
        var me = this;
        me.assSheet = sheet;
        sheetCommonObj.initSheet(me.assSheet, me.assSetting, 30);
        me.bindSheetEvent(sheet);
    },

    bindSheetEvent:function (sheet) {
        var me = this;
        sheet.bind(GC.Spread.Sheets.Events.ClipboardPasting, me.onClipboardPasting);
        sheet.bind(GC.Spread.Sheets.Events.ClipboardPasted, me.onClipboardPasted);
        sheet.bind(GC.Spread.Sheets.Events.EditEnded, me.onEditEnded);
        sheet.bind(GC.Spread.Sheets.Events.RangeChanged, me.onRangeChanged);
       // sheet.bind(GC.Spread.Sheets.Events.CellClick, me.onCellClick);
    },

    onClipboardPasting: function(sender, args) {
        var me = gljOprObj;
        if (!me.ration) {
            args.cancel = true;
        }
    },

    onClipboardPasted: function(e, info) {
        var me = gljOprObj;
        if (!me.ration) {return;};
        // your code...
    },

    onEditEnded: function(sender,args){
        var me = gljOprObj;
        if(subSpread.getActiveSheetIndex()==0){
            me.onEditGLJSheet(args)
        }
        if(subSpread.getActiveSheetIndex()==1){
            me.onEditAssSheet(args);
        }

    },
    onEditGLJSheet(args){
        var me = gljOprObj;
        if(args.row>=me.sheetData.length){
            me.sheet.getCell(args.row, args.col).value(null);
            return;
        }
        var ration_glj = projectObj.project.ration_glj;
        var updateFunction =null;
        if(me.setting.header[args.col].dataCode=='marketPriceAdjust'){//市场单价调整
            updateFunction = ration_glj.marketPriceAdjustUpdate;
        }
        if(me.setting.header[args.col].dataCode=='customQuantity'){//自定义消耗量
            updateFunction = ration_glj.customQuantityUpdate;
        }
        me.updateRationGLJ(args,updateFunction);
    },
    onEditAssSheet(args){
        var me = gljOprObj;
        if(args.row>=me.assSheetData.length){
            me.assSheet.getCell(args.row, args.col).value(null);
            return;
        }
        if(me.assSetting.header[args.col].dataCode=='actualValue'){//自定义消耗量
            me.updateRationAss(args);
        }
    },

    onCheckBoxClick:function (sender,args) {
         if(subSpread.getActiveSheetIndex()==2){
             var checkboxValue = gljOprObj.coeSheet.getCell(args.row, args.col).value();
             var newval = 0;
             if(checkboxValue){
                 newval = 0;
                 gljOprObj.coeSheet.getCell(args.row, args.col).value(newval);
             }else {
                 newval=1
                 gljOprObj.coeSheet.getCell(args.row, args.col).value(newval);
             }
             gljOprObj.updateRationCoe(args,newval)
         }
        //console.log(args);
    },

    onCellClick: function(sender,args){
        var me = gljOprObj;
        if(args.row>=me.sheetData.length){
            return;
        }
        if(me.setting.header[args.col].dataCode=='marketPriceAdjust'){//市场单价调整
            var type = me.sheetData[args.row].gljDistType;
            var index= _.indexOf(me.setting.notEditedType,type);
            if(index!=-1){
                me.sheet.getCell(args.row, args.col, GC.Spread.Sheets.SheetArea.viewport).locked(true);
            }
        }
    },
    onCoeCellClick:function (sender,args) {
        var me = gljOprObj;
        var floatingObject = me.coeSheet.floatingObjects.get('customerCoe');

       // var isVisable = floatingObject.isVisible();
        if($('#dropdown').css("display") == 'none'){
            if(args.col==1&&me.coeSheetData.length>args.row&&me.coeSheetData[args.row].coeID==-1){
                me.showFloationObject(floatingObject,me.coeSheetData[args.row]);
            }
        } else {
            var result = me.checkIfNeedUpdate();
            if(result.isNeed){
                projectObj.project.ration_coe.updateCustomerCoe(result);
            }
            floatingObject.isVisible(false);
            $('#dropdown').hide();
        }
    },
    showFloationObject(floatingObject,data){
        floatingObject.isVisible(true);
        var sheet = this.coeSheet;
        var startRow = this.coeSheetData.length;
        var endRow = startRow+1;
        floatingObject.startRow(startRow);
        floatingObject.startColumn(1);
        floatingObject.endColumn(2);
        floatingObject.endRow(endRow);
        this.bindFloadingObjectValue(data);
        sheet.repaint();
        sheet.getViewportTopRow(1);
        var editPosition = $("#edit").offset();
        $('#dropdown').show();
        var top =editPosition.top>=825?825:editPosition.top
        $('#dropdown').offset({left:editPosition.left,top:top});//top: 791px; left:70px;

    },
    bindFloadingObjectValue(data){
        $('#coe_ration').val(data.coes[0].amount);
        $('#manual').val(data.coes[1].amount);
        $('#material').val(data.coes[2].amount);
        $('#manchine').val(data.coes[3].amount);
        $('#main').val(data.coes[4].amount);
        $('#equipment').val(data.coes[5].amount);
    },
    onInputChange(id,name){
        var coe = _.find(gljOprObj.coeSheetData,function (c) {
            return c.coeID == -1;
        });
        var newValue = gljOprObj.numberValueChecking($('#'+id).val());
        if(newValue){
            newValue=_.round(newValue,2);
            if(newValue==coe.coes[name].amount) return;
            if(id=='coe_ration'){
                $('#coe_ration').val(newValue);
                $('#manual').val(newValue);
                $('#material').val(newValue);
                $('#manchine').val(newValue);
                $('#main').val(newValue);
                $('#equipment').val(newValue);
            }
        }else {
            $('#'+id).val(coe.coes[name].amount);
        }
    },
    checkIfNeedUpdate(){
        var data = _.find(gljOprObj.coeSheetData,function (c) {
            return c.coeID == -1;
        });
        var result = {
            isNeed:false
        }
        var coe_ration = $('#coe_ration').val();
        var manual=$('#manual').val();
        var material = $('#material').val();
        var manchine= $('#manchine').val();
        var main = $('#main').val();
        var equipment=$('#equipment').val();
        if(coe_ration!=data.coes[0].amount){
            result.isNeed =true;
            data.coes[0].amount =coe_ration;
        }
        if(manual!=data.coes[1].amount){
            result.isNeed =true;
            data.coes[1].amount =manual;
        }
        if(material!=data.coes[2].amount){
            result.isNeed =true;
            data.coes[2].amount =material;
        }
        if(manchine!=data.coes[3].amount){
            result.isNeed =true;
            data.coes[3].amount =manchine;
        }
        if(main!=data.coes[4].amount){
            result.isNeed =true;
            data.coes[4].amount =main;
        }
        if(equipment!=data.coes[5].amount){
            result.isNeed =true;
            data.coes[5].amount =equipment;
        }
        if(result.isNeed){
            result.doc = {
                coes:data.coes
            };
            result.query = {
                projectID:data.projectID,
                ID:data.ID,
                rationID:data.rationID
            };
        }
        return result;

    },

    addDropDownList:function () {
        var sheet = this.coeSheet;
        sheet.suspendPaint();
        var customFloatingObject = new GC.Spread.Sheets.FloatingObjects.FloatingObject("customerCoe");
        var div = document.createElement('div');
        div.innerHTML = this.generateHtmlString();
        customFloatingObject.startRow(1);
        customFloatingObject.startColumn(1);
        customFloatingObject.endColumn(2);
        customFloatingObject.endRow(2);
        $(div).css('background', 'white');
        customFloatingObject.content(div);
        sheet.floatingObjects.add(customFloatingObject);
        customFloatingObject.isVisible(false);
        sheet.resumePaint();
    },
    onRangeChanged: function(sender, args) {
        if (args.action == GC.Spread.Sheets.RangeChangedAction.clear) {
            if (!confirm(`确定要删除选中的 ${args.rowCount} 条辅助定额吗？`)){return; }
            // your code...
        };
    },
    generateHtmlString:function () {
        return "<div id='edit'><div>";

 /*       var newString = "<form ><table border='1px' bordercolor='#CCCCCC' cellspacing='0px' style='border-collapse:collapse;font-size: 10px;>";
        //newString +="<tr><td style='height:15px' colspan='2'>自定义系数</td></tr>"
        newString += this.getOneRow('定额',0,'coe_ration');
        newString += this.getOneRow('人工',1,'manual');
        newString += this.getOneRow('材料',2,'material');
        newString += this.getOneRow('机械',3,'manchine');
        newString += this.getOneRow('主材',4,'main');
        newString += this.getOneRow('设备',5,'equipment');
        newString +="</table></form>";

        return newString;*/
        //"<form id='edit'><table border='1px' bordercolor='#CCCCCC' cellspacing='0px' style='border-collapse:collapse;font-size: 10px;><tr style='height:10px'><td style='width: 50px'>定额：</td><td style='width: 70px' align='right'><input type='text'value='1' name='ration' style='width:30px;border:0;height:14px' align='right'></td></tr><tr><td>定额：</td><td><input type='text' style='width:50px;border:0;height:10px'></td></tr><tr><td>定额：</td><td><input type='text' style='width:50px;border:0;height:10px'></td></tr><tr ><td>定额：</td><td><input type='text' style='width:50px;border:0;height:10px'></td></tr><tr><td>定额：</td><td><input type='text' style='width:50px;border:0;height:10px'></td></tr></table></form>";
    },
    getOneRow:function (text,name,id) {
        var rowstr = "<tr style='height:10px'><td style='width: 50px'>"+text
            +"：</td><td style='width: 70px' align='right'><input type='text'value='1' name="+name
            +" style='width:30px;border:0;height:14px' align='right' id="+id+" onchange='gljOprObj.onInputChange(this.id,this.name)'></td></tr>";
        return rowstr;

    },

    showDataIfRationSelect:function (node) {
        var isShow = false;
        if(node){
            if(this.selectedNodeId&&this.selectedNodeId==node.getID()){
                return;
            }else {
                this.selectedNodeId=node.getID();
            }
            if(node.sourceType=="ration"){
               this.showRationGLJData(node);
               this.showRationCoeData(node);
               this.showRationAssData(node);
                isShow=true;
            }
        }else {
            this.selectedNodeId=null;
        }
        if(!isShow){
            this.clearSheetData();
        }
  /*      this.lockRationGLJCell();
        this.lockRationCoeCell();*/
        //hide floatingObject
        var floatingObject = this.coeSheet.floatingObjects.get('customerCoe');
        floatingObject.isVisible(false);
        $('#dropdown').hide();
    },
    showRationGLJData:function (node) {
        let gljList = [];
        let ration_glj = projectObj.project.ration_glj;
        let ration = node.data;
        if(ration_glj.datas&&ration_glj.datas.length>0){
            gljList = _.filter(ration_glj.datas,{'projectID':ration.projectID,'rationID':ration.ID})
        }
        sheetCommonObj.showData(this.sheet,this.setting,gljList);
        this.sheetData=gljList;
    },
    showRationCoeData:function (node) {
        let coeList = [];
        let ration_coe= projectObj.project.ration_coe;
        let ration = node.data;
        if(ration_coe.datas&&ration_coe.datas.length>0){
            coeList = _.filter(ration_coe.datas,{'projectID':ration.projectID,'rationID':ration.ID})
        }
        sheetCommonObj.showData(this.coeSheet,this.coeSetting,coeList);
        this.coeSheetData=coeList;
    },
    showRationAssData:function (node) {
        let assList = node.data.rationAssList;
        sheetCommonObj.showData(this.assSheet,this.assSetting,assList);
        this.assSheetData =assList;
    },
    clearSheetData:function () {
        sheetCommonObj.showData(this.sheet,this.setting,[]);
        sheetCommonObj.showData(this.coeSheet,this.coeSetting,[]);
        sheetCommonObj.showData(this.assSheet,this.assSetting,[]);
        this.sheetData = [];
        this.coeSheetData = [];
        this.assSheetData = [];
    },
 /*   lockRationGLJCell:function(){
        sheetCommonObj.lockCells(this.sheet,this.setting);
    },
    lockRationCoeCell:function () {
        sheetCommonObj.lockCells(this.coeSheet,this.coeSetting);
    /!*    if(this.coeSheetData){
            for(var i =0;i<this.coeSheetData.length;i++){
                if(this.coeSheetData[i].coeID==-1){
                    this.coeSheet.getCell(i, 1, GC.Spread.Sheets.SheetArea.viewport).locked(false);
                }
            }
        }*!/

    },
    lockRationGLJCell:function(){
        sheetCommonObj.lockCells(this.sheet,this.setting);
    },*/
    loadGLJSpreadContextMenu: function () {
        var project =projectObj.project, spread =subSpread;
        var selectedRow =null;
        $.contextMenu({
            selector: '#subSpread',
            build: function ($trigger, e) {
                var target = SheetDataHelper.safeRightClickSelection($trigger, e, spread);
                selectedRow = target.row;
                //controller.setTreeSelected(controller.tree.items[target.row]);
                return target.hitTestType === GC.Spread.Sheets.SheetArea.viewport || target.hitTestType === GC.Spread.Sheets.SheetArea.rowHeader;
            },
            items: {
                "delete_glj": {
                    name: '删除工料机',
                    icon: 'fa-remove',
                    disabled: function () {
                        //var selected = project.mainTree.selected;
                        var disable = true;
                        if(subSpread.getActiveSheetIndex()==0&&gljOprObj.sheetData!=null&&gljOprObj.sheetData.length>0&&selectedRow<gljOprObj.sheetData.length){
                            disable=false
                        }
                        return disable;
                    },
                    callback: function () {
                        var deleteRow = gljOprObj.sheetData[selectedRow];
                        projectObj.project.ration_glj.updataOrdelete(deleteRow);
                    }
                }
            }
        });
    },
    updateRationGLJ:function (args,updateFunction) {
        if(!updateFunction){
            return
        }
        var me = gljOprObj;
        var newval = this.numberValueChecking(args.editingText);
        var recode = me.sheetData[args.row];
        updateFunction.apply(projectObj.project.ration_glj,[recode,newval,args.editingText]);
        if(newval){
            newval = parseFloat(recode.customQuantity).toFixed(2);
        }
        if(args.editingText===null){
            newval=null;
        }
        me.sheet.getCell(args.row, args.col).value(newval);

    },
    updateRationAss:function (args) {
        var me = gljOprObj;
        var newval = me.numberValueChecking(args.editingText);
        var recode = me.assSheetData[args.row];
        var isValidate = false;
        if(newval){
            isValidate = me.checkingActualValue(recode,newval)
        }
        if(isValidate){
            projectObj.project.ration_ass.updateActualValue(me.assSheetData,args.row,newval)
        }else {
            newval = recode.actualValue;
            me.assSheet.getCell(args.row, args.col).value(newval);
        }
    },

    updateRationCoe:function (args,newval) {
      var me = gljOprObj;
      var recode = me.coeSheetData[args.row];
      projectObj.project.ration_coe.adjustCoeClick(recode,newval);
    },
    numberValueChecking:function (val) {
        var newval = Number(val);
        if(number_util.isNumber(newval)){
            newval = newval.toFixed(2);
        }else {
            if(val){
                alert('您输入的数据类型不正确，请重新输入。');
            }
            newval = null;
        }
        return newval;
    },
    checkingActualValue(record,newval){
        var minExist = record.minValue&&record.minValue!='0'?true:false;
        var maxExist = record.maxValue&&record.maxValue!='0'?true:false;
        var minValue = parseFloat(record.minValue);
        var maxValue = parseFloat(record.maxValue);
        var stdVale = parseFloat(record.stdValue);
        if(stdVale==newval){
            return false;
        }

        if(!maxExist&&minExist){
            if(newval<minValue){
                alert('实际值应≥'+minValue);
                return false;
            }
        }
        if(maxExist&&!minExist){
            if(newval>maxValue){
                alert('实际值应≤'+maxValue);
                return false;
            }
        }
        if(maxExist&&minExist){
            if(newval<minValue||newval>maxValue){
                alert('实际值应介于'+minValue+'~'+maxValue+'之间');
                return false;
            }
        }
        return true;
    }
}

