/**
 * Created by zhang on 2018/6/1.
 */

let tender_obj={
    tenderSpread:null,
    tenderSheet:null,
    tenderTree:null,
    tenderController:null,
    tenderSetting:{
        header:[
            {headerName: "项目编码", headerWidth: 170, dataCode: "code", dataType: "String",spanRows: [2],getText:'getText.code'},
            {headerName: "类别", headerWidth: 50, dataCode: "subType", hAlign: "center", dataType: "String",spanRows: [2],getText:'getText.subType'},
            {headerName: "项目名称", headerWidth: 200, dataCode: "name",showHint:true, hAlign: "left", dataType: "String",spanRows: [2]},
            {headerName: "计量\n单位", headerWidth: 60, dataCode: "unit", hAlign: "center", dataType: "String",spanRows: [2]},
            {headerName: "工程量", headerWidth: 70, dataCode: "quantity", hAlign: "right", dataType: "Number",validator:"number",spanRows: [2],getText:'getText.quantity'},
            {headerName: "不调价", headerWidth: 55, dataCode: "is_adjust_price", hAlign: "center", cellType : "checkBox",dataType: "Number",spanRows: [2]},
            {headerName: ["初始报价","综合单价"], headerWidth: 80, dataCode: "feesIndex.common.unitFee", hAlign: "right", dataType: "Number",validator:"number",spanCols : [2,1]},
            {headerName: ["","综合合价"], headerWidth: 80, dataCode: "feesIndex.common.totalFee", hAlign: "right", dataType: "Number",validator:"number",spanCols : [0,1]},
            {headerName: ["目标造价","综合单价"], headerWidth: 80, dataCode: "targetUnitFee", hAlign: "right", dataType: "Number",validator:"number",spanCols : [2,1]},
            {headerName: ["","综合合价"], headerWidth: 80, dataCode: "targetTotalFee", hAlign: "right", dataType: "Number",validator:"number",spanCols : [0,1]},
            {headerName: ["调整后报价","综合单价"], headerWidth: 80, dataCode: "feesIndex.common.tenderUnitFee", hAlign: "right", dataType: "Number",validator:"number",spanCols : [2,1]},
            {headerName: ["","综合合价"], headerWidth: 80, dataCode: "feesIndex.common.tenderTotalFee", hAlign: "right", dataType: "Number",validator:"number",spanCols : [0,1]},
            {headerName: ["消耗量调整系数","人工"], headerWidth: 80, dataCode: "quantityCoe.labour", hAlign: "right", dataType: "Number",validator:"number",spanCols : [5,1]},
            {headerName: ["","材料"], headerWidth: 80, dataCode: "quantityCoe.material", hAlign: "right", dataType: "Number",validator:"number",spanCols : [0,1]},
            {headerName: ["","机械"], headerWidth: 80, dataCode: "quantityCoe.machine", hAlign: "right", dataType: "Number",validator:"number",spanCols : [0,1]},
            {headerName: ["","主材"], headerWidth: 80, dataCode: "quantityCoe.main", hAlign: "right", dataType: "Number",validator:"number",spanCols : [0,1]},
            {headerName: ["","设备"], headerWidth: 80, dataCode: "quantityCoe.equipment", hAlign: "right", dataType: "Number",validator:"number",spanCols : [0,1]},
            {headerName: "子目工程量\n调整系数", headerWidth: 80, dataCode: "rationQuantityCoe", hAlign: "right", dataType: "Number",spanRows: [2],validator:"number"}
        ],
        view: {
            lockColumns: [0,1,2,3,4,6,7,10,11]
        }
    },
    tenderTreeSetting:{
        "emptyRows" : 3,
        "headRows" :2,
        "treeCol" : 0,
        "headRowHeight" : [21],
        "cols" : []
    },
    initTenderSpread:function () {
        if(!this.tenderSpread){
            this.tenderSpread = SheetDataHelper.createNewSpread($("#tenderSpread")[0]);
            sheetCommonObj.spreadDefaultStyle(this.tenderSpread);
        }
        this.tenderSheet = this.tenderSpread.getSheet(0);
        this.tenderTree = cacheTree.createNew(this);
        this.tenderTreeSetting = this.createTenderTreeSetting();
        TREE_SHEET_HELPER.initSetting($('#tenderSpread')[0], this.tenderTreeSetting );
        this.tenderTreeSetting.setAutoFitRow = MainTreeCol.getEvent("setAutoFitRow");
        this.tenderController = TREE_SHEET_CONTROLLER.createNew(this.tenderTree, this.tenderSheet, this.tenderTreeSetting);
        this.tenderSheet.bind(GC.Spread.Sheets.Events.ValueChanged, this.onSheetValueChange);
        this.tenderSheet.bind(GC.Spread.Sheets.Events.RangeChanged, this.onTenderRangeChange);
        this.tenderSheet.bind(GC.Spread.Sheets.Events.EnterCell, this.onEnterCell);
        this.tenderSheet.bind(GC.Spread.Sheets.Events.EditStarting,this.onEditStarting);
        this.tenderController.bind(TREE_SHEET_CONTROLLER.eventName.treeSelectedChanged, this.treeSelectedChanged);
       // this.tenderController.bind(TREE_SHEET_CONTROLLER.eventName.treeSelectedChanged, this.onSelectionChange);
        disableRightMenu("tenderSpread", this.tenderSpread,this.rightClickCallback);
    },
    rightClickCallback:function (row) {
        let me = tender_obj;
        me.tenderController.setTreeSelected(me.tenderController.tree.items[row]);
    },
    createTenderTreeSetting:function () {
       return sheetCommonObj.transferToTreeSetting(this.tenderSetting,this.tenderTreeSetting,MainTreeCol);
    },
    showTenderData:function () {
        let me = this;
        let mainTree = projectObj.project.mainTree;
        this.tenderTree.nodes={},this.tenderTree.selected = null,this.tenderTree.roots = [],this.tenderTree.items=[];
        for(r of mainTree.roots){
            createTenderNode(r,null,null);
        }
        me.tenderTree.sortTreeItems();
        this.tenderSheet.setRowCount(0);
        me.tenderController.showTreeData();

        function createTenderNode(mainNode,parent,next) {
            if(mainNode.sourceType != ModuleNames.ration_glj){//主材、设备的工料机不用显示
                let newNode = me.tenderTree.addNode(parent, next, mainNode.data.ID);
                newNode.data = mainNode.data;
                newNode.source =  mainNode.source;
                newNode.sourceType = mainNode.sourceType;
                newNode.mainNode = mainNode;
                if(mainNode.children.length > 0){
                    for(let c of mainNode.children){
                        createTenderNode(c,newNode,null);
                    }
                }
                return newNode;
            }
        }
    },
    onTenderRangeChange:function (sender,info) {
        let me = tender_obj;
        let changeInfo=[];
        if(info.action == GC.Spread.Sheets.RangeChangedAction.clear){
            if(me.editChecking(info.row,info.col) == false){
                me.tenderController.refreshTreeNode(me.materialTree.selected, false);
            }else {
                info.newValue = null;
                me.onSheetValueChange(sender,info);
            }
        }else {
            let canChange = true;
            for(let c of info.changedCells){
                let value=  info.sheet.getCell(c.row, c.col).text();
                changeInfo.push({row:c.row,col:c.col,value:value});
                if(me.editChecking(c.row,c.col,true)==false){//如果不能编辑
                    canChange = false;
                    break;
                }
                if (!projectGljObject.checkData(c.col,me.tenderSetting,value)) {
                    alert('输入的数据类型不对，请重新输入!');
                    canChange = false;
                    break;
                }
            }
            if(canChange == false){
                tender_obj.showTenderData();
            }else {
                me.batchUpdateValue(changeInfo);
            }
        }

    },
    batchUpdateValue:function (changeInfo) {
        let me = tender_obj,updateNodes = [],datas = [],nodes=[];
        let dataMap = {};//用来去重复
        for(let c of changeInfo){
            let dataCode = me.tenderSetting.header[c.col].dataCode;
            let node = me.tenderTree.items[c.row];
            me.getUpdateData(c.value,dataCode,node,updateNodes);
        }
        for(let u of updateNodes){//有可能会有重复的数据，需要按相同的ID组合起来。
            if(dataMap[u.data.ID]){
                for(let key in u.data){
                    if(key == 'ID'){
                        continue;
                    }
                    dataMap[u.data.ID].data[key] = u.data[key];
                }
            }else {
                dataMap[u.data.ID] = u;
            }
        }
        for(let IDKey in dataMap){
            datas.push(dataMap[IDKey]);
            let temNode = me.tenderTree.findNode(IDKey);
            if(temNode) nodes.push(temNode);
        }
        me.updateTenderData(datas,function () {
            me.tenderController.refreshTreeNode(nodes, false);
        });

    },

    getUpdateData:function(value,dataCode,node,updateNodes,nodes){
        let me = tender_obj;
        let updateData = {type:node.sourceType,data:{'ID' : node.data.ID}};
        if(dataCode === 'is_adjust_price'){
            value = value? 1:0;
            if(value == 1){
                updateData = me.cleanTenderCoe(updateData,node);//打勾不调价后清空消耗量调整系数
            }
            me.updateChildrenValue(node,dataCode,value,updateNodes,nodes);
        }
        if(updateData&&dataCode.indexOf("Coe") != -1 ){//如果是调整系统项,级联更新子项
            value = scMathUtil.roundForObj(value,getDecimal('process'));
            me.updateChildrenValue(node,dataCode,value,updateNodes,nodes);
        }

        //在目标造价综合单价中输入数值，按项目属性中的清单单价精度取舍，并清空当前行的目标造价综合合价
        if(dataCode == 'targetUnitFee'){
            value = scMathUtil.roundForObj(value,getDecimal('unitPrice',node));
            updateData?updateData.data["targetTotalFee"] = null:'';
        }
        if(dataCode == 'targetTotalFee'){
            value = scMathUtil.roundForObj(value,getDecimal('totalPrice',node));
            updateData?updateData.data["targetUnitFee"] = null:'';
        }
        updateData.data[dataCode] = value;
        updateNodes.push(updateData);
        nodes?nodes.push(node):'';

    },

    onSheetValueChange : function (sender,args) {
        let me = tender_obj, row = args.row, col = args.col;
        let node = me.tenderTree.items[row];
        let dataCode = me.tenderSetting.header[col].dataCode;
        let value = args.newValue;
        let datas = [],nodes = [];
        if (value&&!projectGljObject.checkData(col,me.tenderSetting,value)) {
            alert('输入的数据类型不对，请重新输入!');
            nodes.push(node);
        }else {
            me.getUpdateData(value,dataCode,node,datas,nodes);
        }
        me.updateTenderData(datas,function () {
            me.tenderController.refreshTreeNode(nodes, false);
        });

    },
    onEnterCell : function (sender,args) {
        let me = tender_obj, row = args.row, col = args.col;
        if ([8, 9].includes(col)){
            let node = me.tenderTree.items[row];
            if (node.children && node.children.length > 0) {   // 父结点只读
                me.tenderSheet.getCell(row, col).locked(true);// = true;
            }
        }
    },
    updateChildrenValue:function (node,dataCode,value,datas,nodes) {
         if(node.children.length > 0){
            for(let c of node.children){
                this.updateChildrenValue(c,dataCode,value,datas,nodes);
                let updateData = {type:c.sourceType,data:{'ID' : c.data.ID}};
                updateData.data[dataCode] = value;
                if(dataCode == 'is_adjust_price' && value == 1){
                    updateData = this.cleanTenderCoe(updateData,c);
                }else if(dataCode.indexOf("Coe")!= -1 && c.data.is_adjust_price == 1){//更新调整系数时忽略不调价的行
                    continue;
                }
                datas.push(updateData);
                nodes?nodes.push(c):"";
            }
         }

    },
    cleanTenderCoe:function (updateData,node) {//清空调整系数
        scMathUtil.isDef(node.data.rationQuantityCoe)?updateData.data["rationQuantityCoe"] = null:'';
        if(scMathUtil.isDef(node.data.quantityCoe)){
            scMathUtil.isDef(node.data.quantityCoe.labour)?updateData.data["quantityCoe.labour"] = null:'';
            scMathUtil.isDef(node.data.quantityCoe.material)?updateData.data["quantityCoe.material"] = null:'';
            scMathUtil.isDef(node.data.quantityCoe.machine)?updateData.data["quantityCoe.machine"] = null:'';
            scMathUtil.isDef(node.data.quantityCoe.main)?updateData.data["quantityCoe.main"] = null:'';
            scMathUtil.isDef(node.data.quantityCoe.equipment)?updateData.data["quantityCoe.equipment"] = null:'';
        }
        return updateData;
    },
    cleanTargetPrice:function (updateData,node) {//清空目标报价
        scMathUtil.isDef(node.data.targetUnitFee)?updateData.data["targetUnitFee"] = null:'';
        scMathUtil.isDef(node.data.targetTotalFee)?updateData.data["targetTotalFee"] = null:'';
        return updateData;
    },
    cleanTenderPrice:function (updateData,node) {//清空调整后报价
        if(node.data.fees){
            for(let i =0; i< node.data.fees.length; i++){
                node.data.fees[i].tenderUnitFee?updateData.data["fees."+i+'.tenderUnitFee'] = 0:'';
                node.data.fees[i].tenderTotalFee?updateData.data["fees."+i+'.tenderTotalFee'] = 0:'';
            }
        }
    },
    cleanCacheCoes: function (){
        for(let node of tender_obj.tenderTree.items){
            if (node.data.rationQuantityCoe) node.data.rationQuantityCoe = null;
            let qcObj = node.data.quantityCoe;
            if (qcObj){
                for (let pn in qcObj){
                    qcObj[pn] = null;
                };
            };
        };
    },

    calcOptionsChecking:function (option) {//调整选项检查,返回需要更新的数组
        let datas = [];
        let me = tender_obj;
        for(let node of me.tenderTree.items){
            let tem_updateData = {type:node.sourceType,data:{}};
            if(option == 'coeBase') { //当值为“根据调整系数计算报价”时，清空目标报价。
                me.cleanTargetPrice(tem_updateData,node);
            }else if(option == 'priceBase'){//当值为“根据报价计算调整系数”时，清空调整系数。
                me.cleanTenderCoe(tem_updateData,node);
            }
            if(!_.isEmpty(tem_updateData.data)){//如果需要更新
                tem_updateData.data.ID = node.data.ID;
                datas.push(tem_updateData);
            }
        }
        return datas;
    },

    updateTenderData:function (datas,callback) {
        let me = tender_obj;
        if(datas.length <= 0){
            callback?callback():'';
            return;
        }
        $.bootstrapLoading.start();
        projectObj.project.updateNodes(datas,function () {
            for(let d of datas){
                let temObj = null;
                if(d.type == ModuleNames.bills || d.type == ModuleNames.ration){
                    let temNode = me.tenderTree.findNode(d.data.ID);
                    temObj = temNode?temNode.data:null;
                }else if(d.type == ModuleNames.project){
                    temObj = projectObj.project.projectInfo;
                }
                if(temObj){
                    for(let key in d.data){
                        if(key == 'ID' || key == 'id'){
                            continue;
                        }
                        me.setValue(temObj,key,d.data[key])
                    }
                }
            }
            callback?callback():'';
            $.bootstrapLoading.end();
        })
    },
    setValue:function (obj,key,value) {
        let keyArray = key.split('.');
        t_set(obj,value,keyArray,0);
        function t_set(obj,value,arr,index) {
            let nextIndex = index + 1;
            let tkey = arr[index];
            if(nextIndex < arr.length){
                if(obj[tkey]==undefined){
                    obj[tkey] = {};
                }
                t_set(obj[tkey],value,arr,nextIndex)
            }else if(nextIndex == arr.length){
                obj[tkey] = value;
            }
        }

    },
    refreshTenderTreeByDatas:function (datas) {
        let me = this;
        let nodes = [];
        for(let d of datas){
            if(d.type == ModuleNames.bills || d.type == ModuleNames.ration){
                let node = me.tenderTree.getNodeByID(d.data.ID);
                node?nodes.push(node):'';
            }
        }
        me.tenderController.refreshTreeNode(nodes);
        me.initPageContent();
    },
    treeSelectedChanged:function (node) {
        let me = tender_obj;
        //设置选中行底色和恢复前选中行底色
        let refreshNodes = [node];
        if(!me.tenderTree.preSelected){
            refreshNodes.push(me.tenderTree.items[0]);
        }
        else {
            refreshNodes.push(me.tenderTree.preSelected);
        }
        me.tenderTree.preSelected = node;
        projectObj.setNodesStyle(me.tenderSheet, refreshNodes,me.tenderTree);
        //console.log(node);
    },
    onEditStarting:function (sender,args) {
        let me = tender_obj, row = args.row, col = args.col;
        if(me.editChecking(row,col) == false){
            args.cancel = true;
        }

    },
    editChecking:function (row,col,isPaste = false) {//return false表示不能编辑
        let me = tender_obj;
        let dataCode = me.tenderSetting.header[col].dataCode;
        let lockColumns = me.tenderSetting.view.lockColumns;

        if(lockColumns.indexOf(col)!= -1){
            return false;
        }
        if(isPaste == false && dataCode == 'is_adjust_price'){//对于是粘贴或是拖动填充过来的数据，不调价不做判断
            return false;
        }
        if(row >=  me.tenderTree.items.length){
            return false;
        }
        if(dataCode == 'targetUnitFee' || dataCode == 'targetTotalFee'){
            if($('#calcPriceOption').val() == 'coeBase'){//下拉按钮显示为“根据调整系数计算报价”时，目标造价(综合单价、综合合价) ，灰显，只读。
                return false;
            }else if(me.tenderTree.items[row].data.is_adjust_price === 1){//下拉按钮显示为“根据报价计算调整系数”时，打勾了不调价，目标造价(综合单价、综合合价)只读。
                return false;
            }
        }
        if(dataCode.indexOf('Coe') != -1){//如果是调整系数列
            if($('#calcPriceOption').val() =='priceBase'){//下拉按钮显示为“根据报价计算调整系数”时，只读。
                return false;
            }else if(me.tenderTree.items[row].data.is_adjust_price === 1){//打勾了不调价，只读。
                return false;
            }
        }
        return true;
    },
    initPageContent : function () {
        let tenderSetting = projectObj.project.property.tenderSetting;
        let calcPriceOption = tenderSetting && tenderSetting.calcPriceOption? tenderSetting.calcPriceOption :"coeBase";
        let gljPriceTenderCoe = tenderSetting && tenderSetting.gljPriceTenderCoe?tenderSetting.gljPriceTenderCoe:1;
        $('#calcPriceOption').val(calcPriceOption);
        $('#gljPriceTenderCoe').val(gljPriceTenderCoe);
        if(calcPriceOption == 'coeBase'){
            if(!projectReadOnly){
                $('#tenderPrice').removeAttr("disabled");
            }
            $('#tenderGLJQuantity').attr("disabled",true);
            $('#tenderRationQuantity').attr("disabled",true);
        }else {
            $('#tenderPrice').attr("disabled",true);
            $('#tenderGLJQuantity').removeAttr("disabled");
            $('#tenderRationQuantity').removeAttr("disabled");
        }
        //gljPriceTenderCoe
    },
    doTenderCalc: function(tender){
        if (tender != tenderTypes.ttCalc)
            tender_obj.cleanCacheCoes();
        let callback = function () {
            projectObj.project.saveProperty('hasTender', true);
            tender_obj.showTenderData();
        };
        projectObj.project.calcProgram.calcAllNodesAndSave(calcAllType.catAll, callback, tender);
    }
};

$(function () {
    $('#tab_tender_price').on('shown.bs.tab', function (e) {
        sessionStorage.setItem('mainTab', '#tab_tender_price');
        $(e.relatedTarget.hash).removeClass('active');
        if(!tender_obj.tenderSpread){
            tender_obj.initTenderSpread();
            tender_obj.showTenderData();
            tender_obj.initPageContent();
        }
        autoFlashHeight();
        tender_obj.tenderSpread.refresh();
    });

    $('#tenderGLJQuantity').bind('click',function () {
        //console.log($('#gljPriceTenderCoe').val()) ;
    });

    $('#cleanTender').bind('click',function () {
        let me = tender_obj,datas = [];
        for(let node of me.tenderTree.items){
            let tem_updateData = {type:node.sourceType,data:{}};
            me.cleanTargetPrice(tem_updateData,node);
            me.cleanTenderCoe(tem_updateData,node);
            me.cleanTenderPrice(tem_updateData,node);
            if(!_.isEmpty(tem_updateData.data)){//如果需要更新
                tem_updateData.data.ID = node.data.ID;
                datas.push(tem_updateData);
            }
        }
        datas.push({type:ModuleNames.project,data:{'ID' : projectObj.project.ID(),'property.tenderSetting.gljPriceTenderCoe':1}});//恢复人材机单价调整系数为1。
        datas.push({type:ModuleNames.project,data:{'ID' : projectObj.project.ID(),'property.hasTender': false}});
        me.updateTenderData(datas,function () {
            me.refreshTenderTreeByDatas(datas);
        });
    });

    $('#calcPriceOption').change(function(){
        let me = tender_obj;
        let newVal = $(this).val();
        let datas = me.calcOptionsChecking(newVal);
        let updateData = {type:ModuleNames.project,data:{'ID' : projectObj.project.ID(),'property.tenderSetting.calcPriceOption':newVal}};
        datas.push(updateData);
        me.updateTenderData(datas,function () {
            me.refreshTenderTreeByDatas(datas);
        });
    });

    $('#gljPriceTenderCoe').change(function(){
        let me = tender_obj;
        let process = getDecimal('process');
        var newVal = $(this).val();
        process = scMathUtil.roundForObj(newVal,process);
        let updateData = {type:ModuleNames.project,data:{'ID' : projectObj.project.ID(),'property.tenderSetting.gljPriceTenderCoe':process}};
        me.updateTenderData([updateData],function () {
            me.initPageContent();
        });
    });

    $('#tenderPrice').on('click', function () {
        tender_obj.doTenderCalc(tenderTypes.ttCalc);
    });

    $('#tenderGLJQuantity').on('click', function () {
        tender_obj.doTenderCalc(tenderTypes.ttReverseGLJ);
    });

    $('#tenderRationQuantity').on('click', function () {
        tender_obj.doTenderCalc(tenderTypes.ttReverseRation);
    });

});