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

var gljOprObj = {
    sheet: null,
    libID: null,
    ration: null,
    sheetData:[],
    coeSheetData:[],
    checkb:null,
    coeSheet:null,
    assSheet:null,
    assSheetData:[],
    detailSheet:null,
    detailData:[],
    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: "shortName", dataType: "String", hAlign: "center"},
            {headerName: "定额消耗量", headerWidth: 80, dataCode: "rationItemQuantity", dataType: "Number", hAlign: "right",formatter:"0.000",tofix:3},    // dataType: "Number", formatter: "0.00"
            {headerName: "自定义消耗量", headerWidth: 80, dataCode: "customQuantity", dataType: "Number", hAlign: "right",formatter:"0.000",tofix:3},
            {headerName: "消耗量", headerWidth: 80, dataCode: "quantity", dataType: "Number", hAlign: "right",formatter:"0.000",tofix:3},
            {headerName: "基价单价", headerWidth: 80, dataCode: "basePrice", dataType: "Number", hAlign: "right",formatter:"0.00"},
            {headerName: "调整基价", headerWidth: 80, dataCode: "adjustPrice", dataType: "Number", hAlign: "right",formatter:"0.00"},
            {headerName: "市场单价", headerWidth: 80, dataCode: "marketPrice", dataType: "Number", hAlign: "right",formatter:"0.00"},
            {headerName: "市场单价调整", headerWidth: 80, dataCode: "marketPriceAdjust", dataType: "Number", hAlign: "right",formatter:"0.00"},
            {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",cellType:"button"},
            {headerName: "内容", headerWidth: 350, dataCode: "content", dataType: "String", hAlign: "left"}
        ],
        view:{
            lockColumns:[0,1,2]
        }
    },
    assSetting:{
        header:[
            {headerName: "调整名称", headerWidth: 100, dataCode: "name", dataType: "String"},
            {headerName: "定额值", headerWidth: 120, dataCode: "stdValue", dataType: "String"},
            {headerName: "实际值", headerWidth: 120, dataCode: "actualValue", dataType: "String"}
        ],
        view:{
            lockColumns:[0,1]
        }
    },
    detailSetting:{
        header:[
            {headerName: "名称", headerWidth: 100, dataCode: "name", dataType: "String"},
            {headerName: "计算式", headerWidth: 120, dataCode: "regex", dataType: "String"},
            {headerName: "结果（C）", headerWidth: 120, dataCode: "result", dataType: "Number",formatter:"0.0000",tofix:4},
            {headerName: "累加", headerWidth: 120, dataCode: "isSummation", dataType: "String",cellType:"checkBox"}
        ],
        view:{
            lockColumns:[2,3]
        }
    },
    initSheet: function(sheet) {
        var me = this;
        me.sheet = sheet;
        sheetCommonObj.initSheet(me.sheet, me.setting, 30);
        sheet.name('ration_glj');
        me.bindSheetEvent(sheet);
        sheet.bind(GC.Spread.Sheets.Events.CellClick, me.onCellClick);
        gljContextMenu.loadGLJSpreadContextMenu();
    },
    initCoeSheet:function (sheet) {
        var me = this;
        me.coeSheet = sheet;
        sheetCommonObj.initSheet(me.coeSheet, me.coeSetting, 30);
        sheet.name('ration_coe');
        me.bindSheetEvent(sheet);
        sheet.bind(GC.Spread.Sheets.Events.CellClick, me.onCoeCellClick);
        subSpread.bind(GC.Spread.Sheets.Events.ButtonClicked,me.onButtonClick);
    },
    initAssSheet: function(sheet) {
        var me = this;
        me.assSheet = sheet;
        sheetCommonObj.initSheet(me.assSheet, me.assSetting, 30);
        sheet.name('ration_ass');
        me.bindSheetEvent(sheet);
    },
    initDetailSheet: function(sheet) {
        var me = this;
        me.detailSheet = sheet;
        sheetCommonObj.initSheet(me.detailSheet, me.detailSetting, 30);
        sheet.name('quantity_detail');
        me.bindSheetEvent(sheet);
    },
    showCoeData:function(sheet,setting,datas){
        sheet.floatingObjects.remove("customerCoe");
        sheetCommonObj.showData(sheet,setting,datas);
        if(datas.length>0){
            var cus_index= _.findIndex(datas,function(item){
                return item.coeID==-1;
            })
            if(cus_index!=-1){
                this.addDropDownList();
               this.addCusButton(cus_index,1,datas[cus_index].name);
            }
        }
    },
    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;
        console.log('past');
      //  if (!me.ration) {return;};
        // your code...
    },

    onEditEnded: function(sender,args){
        var me = gljOprObj;
        if(args.sheetName=='ration_glj'){
            me.onEditGLJSheet(args)
        }
        if(args.sheetName=='ration_ass'){
            me.onEditAssSheet(args);
        }
        if(args.sheetName=='quantity_detail'){
            me.onEditDetailSheet(args);
        }
    },
    onEditDetailSheet:function(args){
        var me = gljOprObj;
        if(args.row>me.detailData.length){
            return;
        }
        if(args.row==me.detailData.length&&args.editingText==null){
            return;
        }
       if(args.row==me.detailData.length){
           projectObj.project.quantity_detail.saveQuantityDetail(args,me.detailSetting.header[args.col].dataCode);
       }
        if(args.row<me.detailData.length){
            projectObj.project.quantity_detail.updateQuantityDetail(args,me.detailSetting.header[args.col].dataCode,me.detailData[args.row]);
        }

    },
    onEditGLJSheet:function(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:function(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);
        }
    },
    onButtonClick:function (sender,args) {
        var me = gljOprObj;
        var sheet = args.sheet, row = args.row, col = args.col;
        var cellType = sheet.getCellType(row, col);
        if (cellType instanceof GC.Spread.Sheets.CellTypes.Button) {
            me.onCusButtonClick(sender,args);
        }else {
           me.onCheckBoxClick(sender,args)
        }
    },
    onCheckBoxClick:function(sender,args){
        if(args.sheetName=='ration_glj'){
            return;
        }
        var checkboxValue = args.sheet.getCell(args.row, args.col).value();
        var newval = 0;
        if(checkboxValue){
            newval = 0;
            args.sheet.getCell(args.row, args.col).value(newval);
        }else {
            newval=1
            args.sheet.getCell(args.row, args.col).value(newval);
        }
        if(args.sheetName=='ration_coe'){
            gljOprObj.updateRationCoe(args,newval)
        }else {
            projectObj.project.quantity_detail.isSummationUpdate(args,gljOprObj.detailData,newval);
        }
    },
    onCusButtonClick:function (sender,args){
        var me = gljOprObj;
        var floatingObject = me.coeSheet.floatingObjects.get('customerCoe');
        var isVisable = floatingObject.isVisible();
        if(!isVisable){
            me.coeSheet.getCell(args.row, args.col, GC.Spread.Sheets.SheetArea.viewport).locked(false);
            me.showFloationObject(floatingObject,me.coeSheetData[args.row]);
        }else {
            var result = me.checkIfNeedUpdate();
            if(result.isNeed){
                projectObj.project.ration_coe.updateCustomerCoe(result);
            }
            floatingObject.isVisible(false);
        }
    },
    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].shortName;
            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]);
         }
         }*/
        if(isVisable){
            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+7;
        floatingObject.startRow(startRow);
        floatingObject.startColumn(1);
        floatingObject.endColumn(2);
        floatingObject.endRow(endRow);
        this.bindFloadingObjectValue(data);
        sheet.repaint();
        // 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(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();
    },
    addCusButton:function(row,col,text){
        var cus_button = new GC.Spread.Sheets.CellTypes.Button();
        gljOprObj.coeSheet.setCellType(row, col, cus_button, GC.Spread.Sheets.SheetArea.viewport);
        cus_button.marginLeft(0);
        cus_button.marginTop(0);
        cus_button.marginRight(0);
        cus_button.marginBottom(0);
        cus_button.text(text);
        cus_button.buttonBackColor('white');
        gljOprObj.coeSheet.repaint();
    },
    onRangeChanged: function(sender, args) {
        var me = gljOprObj;
        if (args.action == GC.Spread.Sheets.RangeChangedAction.clear) {
            args.editingText=null;
            if(args.sheetName=='ration_glj'){
                me.onEditGLJSheet(args);
            }
            if(args.sheetName=='ration_ass'){
                me.updateRationAss(args);
            }
        };
    },
    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;
            }
            this.showQuantityDetailData(node);
        }else {
            this.selectedNodeId=null;
        }
        if(!isShow){
            this.clearSheetData();
        }
        //hide floatingObject
        var floatingObject = this.coeSheet.floatingObjects.get('customerCoe');
        if(floatingObject){
            floatingObject.isVisible(false);
        }
     //   $('#dropdown').hide();
    },
    showRationGLJData:function (node) {
        var gljList = [];
        var ration_glj = projectObj.project.ration_glj;
        node=node?node:projectObj.project.mainTree.selected;
        if(node.sourceType==ModuleNames.ration){
            let ration = node.data;
            gljList=this.filterGljByRation(ration,ration_glj.datas);
            this.showInSheet(gljList);
        }
    },
    showRationGLJSheetData:function () {
        sheetCommonObj.showData(this.sheet,this.setting,this.sheetData);
    },
    filterGljByRation:function (ration,datas) {
        var gljList=[];
        if(datas&&datas.length>0){
            gljList = _.filter(datas,{'rationID':ration.ID})
        }
        return gljList;
    },
    showInSheet:function(gljList){
        gljList=this.combineWithProjectGlj(gljList);
        sheetCommonObj.showData(this.sheet,this.setting,gljList);
        this.sheetData=gljList;
    },
    combineWithProjectGlj:function (ration_gljs) {
        var projectGljs = projectObj.project.projectGLJ.datas;
        if(ration_gljs&&ration_gljs.length>0&&projectGljs&&projectGljs.length>0){
            ration_gljs.forEach(function (a) {
                var glj = _.find(projectGljs,{id:a.projectGLJID});
                if(glj){
                    a.basePrice=glj.unit_price.base_price;
                    a.marketPrice=glj.unit_price.market_price;
                    a.adjustPrice=glj.adjust_price;
                    a.isEstimate=glj.is_evaluate;
                }
            })
        }
        return ration_gljs;
    }
    ,
    showRationCoeData:function (node) {
        var coeList = [];
        var ration_coe= projectObj.project.ration_coe;
        var ration = node.data;
        if(ration_coe.datas&&ration_coe.datas.length>0){
            coeList = _.filter(ration_coe.datas,{'projectID':ration.projectID,'rationID':ration.ID})
        }
        this.showCoeData(this.coeSheet,this.coeSetting,coeList);
        this.coeSheetData=coeList;
    },
    showRationAssData:function (node) {
        var assList = node.data.rationAssList ? node.data.rationAssList : [];
        sheetCommonObj.showData(this.assSheet,this.assSetting,assList);
        this.assSheetData =assList;
    },
    showQuantityDetailData:function (node) {
        var details=[];
        var quantity_detail =projectObj.project.quantity_detail;
        if(node.sourceType==ModuleNames.ration){
            details=_.filter(quantity_detail.datas,{'rationID':node.data.ID});
        }else if(node.sourceType==ModuleNames.bills){
            details=_.filter(quantity_detail.datas,{'billID':node.data.ID});
        }
        details=_.sortBy(details,'seq');
        sheetCommonObj.showData(this.detailSheet,this.detailSetting,details);
        this.detailData = details;
    },
    clearSheetData:function () {
        sheetCommonObj.showData(this.sheet,this.setting,[]);
        sheetCommonObj.showData(this.coeSheet,this.coeSetting,[]);
        sheetCommonObj.showData(this.assSheet,this.assSetting,[]);
      //  sheetCommonObj.showData(this.detailSheet,this.detailSetting,[]);
        this.sheetData = [];
        this.coeSheetData = [];
        this.assSheetData = [];
        //this.detailData=[];
    },
 /*   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);
    },*/
    updateRationGLJ:function (args,updateFunction) {
        if(!updateFunction){
            return
        }
        var me = gljOprObj;
        var newval = this.numberValueChecking(args.editingText);
        var recode = me.sheetData[args.row];
        if(args.editingText===null){
            updateFunction.apply(projectObj.project.ration_glj,[recode,null,args.editingText]);
        }else if(newval!=null){
            updateFunction.apply(projectObj.project.ration_glj,[recode,newval,args.editingText]);
        }else {
            newval = recode[me.setting.header[args.col].dataCode];
            me.sheet.getCell(args.row, args.col).value(newval);
        }
    },
    updateRationAss:function (args) {
        var me = gljOprObj;
        var newval;
        newval = me.numberValueChecking(args.editingText);
        var recode = me.assSheetData[args.row];
        if(args.editingText===null){
            newval=parseFloat(recode.stdValue);
        }
        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)){
            return newval;
        }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(!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;
    },
    refreshView:function () {
        this.showRationGLJData();
    }
}

