/**
 * Created by Mai on 2017/4/1.
 */
let ration_glj = {
    createNew: function (project) {
        // 用户定义private方法
        let tools = {};

        // 所有通过this访问的属性，都不应在此单元外部进行写入操作
        let ration_glj = function (proj) {
            this.gljTree = cacheTree.createNew(this);
            // this.project = proj;
            this.datas = [];
            let sourceType = ModuleNames.ration_glj;
            this.getSourceType = function () {
                return sourceType;
            }
            proj.registerModule(ModuleNames.ration_glj, this);
        };

        // 从后台获取数据
        /*glj.prototype.pullData = function (){
         this.project.pullData(
         '/glj/getData',
         {projectID: this.project.ID},
         function(result){
         if (result.error ===0){
         this.loadDatas(result.data);
         }
         else {
         // to do: 错误处理需要细化
         alert(result.message);
         }
         },
         function (){}//to do: 错误处理需要细化
         )
         };*/
        // prototype用于定义public方法
        ration_glj.prototype.loadData = function (datas) {
            this.datas = datas;
        };

        ration_glj.prototype.getGLJListByRationID = function (rationID) {
            return  _.filter(this.datas, {'rationID': rationID})
        };


        ration_glj.prototype.getGatherGljArrByRations = function (rations, needOneBill, billQuantity) {
            let result = [];
            let clone = function (obj) {
                if (obj === null) return null;
                let o = Object.prototype.toString.apply(obj) === "[object Array]" ? [] : {};
                for (let i in obj) {
                    o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === "object" ? clone(obj[i]) : obj[i]);
                }
                return o;
            }
            let findGlj = function (sourceGlj, gljArr) {
                for (let glj of gljArr) {
                    if (glj.projectGLJID === sourceGlj.projectGLJID) {
                        return glj;
                    }
                }
                return null;
            }
            for (let ration of rations) {
                if (ration.type == rationType.volumePrice || ration.type == rationType.gljRation){
                    let glj = JSON.parse(JSON.stringify(ration));
                    glj.type = glj.subType;
                    glj.totalQuantity = parseFloatPlus(ration.quantity);
                    glj.markertPrice = glj.marketUnitFee;
                    glj.basePrice = glj.marketUnitFee;
                    glj.adjustPrice = glj.marketUnitFee;
                    result.push(glj);
                } else{
                    let rationGljs = projectObj.project.calcProgram.getGljArrByRation(ration);
                    for (let glj of rationGljs) {
                        let sameGlj = findGlj(glj, result);
                        if (!sameGlj) {
                            sameGlj = clone(glj);
                            sameGlj.quantity = (sameGlj.quantity * ration.quantity).toDecimal(4);
                            result.push(sameGlj);
                        } else {
                            sameGlj.quantity = sameGlj.quantity + (glj.quantity * ration.quantity).toDecimal(4);
                            sameGlj.totalQuantity = (parseFloat(sameGlj.totalQuantity) + parseFloat(glj.totalQuantity)).toDecimal(4);
                        }
                    }
                }
            }

            result = gljOprObj.combineWithProjectGlj(result);

            if (!needOneBill) return result;

            // 上面取的是清单下所有工料机的总量，我要算清单单价，所以要取单位清单的工料机数量，所以下面要除以清单数量。
            let oneBill = JSON.parse(JSON.stringify(result));

            for (let glj of oneBill){
                if (glj.type == rationType.volumePrice){  // 量价、工料机形式的定额要进行数据变换才能参与基数计算。
                    glj.type = glj.subType;
                    glj.basePrice = glj.marketUnitFee;
                    glj.marketPrice = glj.marketUnitFee;
                    glj.adjustPrice = glj.marketUnitFee;
                }
                else if (glj.type == rationType.gljRation){
                    glj.type = glj.subType;
                };

                // glj.quantity = (glj.quantity / billQuantity).toDecimal(decimalObj.glj.quantity);
                glj.quantity = (glj.quantity / billQuantity).toDecimal(decimalObj.process);  // 广联达这里没有取舍
            };
            return oneBill;
        }

        // 提交数据后返回数据处理
        ration_glj.prototype.doAfterUpdate = function (err, data) {
            let me = this;
            if (!err) {
                if (data.updateTpye == 'ut_update') {
                    me.refreshAfterUpdate(data);
                } else if (data.updateTpye == 'ut_delete') {
                    me.refreshAfterDelete(data);
                } else {
                    me.refreshAfterSave(data);
                }
            }
            projectObj.project.projectGLJ.loadData();
        };
        ration_glj.prototype.getDataByID = function (ID) {
            return _.find(this.datas,{'ID':ID});
        };

        ration_glj.prototype.refreshAfterSave = function (data) {
            let me = projectObj.project.ration_glj;
            let neRecodes = [];
            if (data) {
                // neRecodes=data.newRecords;//原来是显示和缓存分开的，后来发现会导致数据不一致的问题所以改成统一的了，这里也只是会作为显示。
                neRecodes = data.showDatas;
                gljOprObj.sheetData = neRecodes;
                me.addDatasToList(neRecodes);
            }
            project.projectGLJ.loadData(function () {
                gljOprObj.showRationGLJSheetData(true);
                //add to mainTree;
                me.addToMainTree(neRecodes);
                let rationID = neRecodes[0].rationID;
                let node = project.mainTree.nodes['id_' + rationID];
                if(isDef(node)){
                    project.calcProgram.calcAndSave(node);
                }
                if (activeSubSheetIsCalcProgram())
                    calcProgramObj.refreshCalcProgram(node, 1);
            });
        };
        ration_glj.prototype.getGljByRationID = function(rationID){
            return  _.filter(this.datas, {'rationID': rationID});
        };
        ration_glj.prototype.addDatasToList = function (datas) {
            let  me = projectObj.project.ration_glj;
            if(datas&&datas.length>0){
                if (me.datas && Array.isArray(me.datas)) {
                    me.datas = me.datas.concat(datas);
                } else {
                    me.datas = datas;
                }
            }
        };
        ration_glj.prototype.updateGLJNodeAfterReplace = function(data){
            if(!data) return null;
            if (this.needShowToTree(data)) {//当替换的是主材或设备时，刷新对应的树节点
                var node = this.findGLJNodeByID(data.ID);
                if (node) {
                    this.transferToNodeData(data);
                    node.source = data;
                    node.data = data;
                }
                return node;
            }
        };

        ration_glj.prototype.addToMainTree = function (datas) {
            datas = gljUtil.sortRationGLJ(datas);
            for (let data of datas) {
                if (this.needShowToTree(data)) {
                    gljOprObj.setGLJPrice(data);
                    this.transferToNodeData(data);
                    let parentNode = projectObj.project.mainTree.findNode(data.rationID);
                    if (parentNode) {
                        let nextNodeID = null;
                        if (parentNode.children.length > 0) {
                            for (let br of parentNode.children) {
                                if (compareRationGLJ(data, br.data)) {//如果有兄弟节点则找到添加位置。
                                    nextNodeID = br.getID();
                                }
                            }
                        }
                        nextNodeID = nextNodeID ? nextNodeID : parentNode.tree.rootID();
                        let newNode = projectObj.project.mainTree.insert(parentNode.getID(), nextNodeID,data.ID);
                        newNode.source = data;
                        newNode.sourceType = this.getSourceType();
                        newNode.data = data;
                        ProjectController.syncDisplayNewRationGljNode(projectObj.mainController, newNode);
                    }
                }
            }
        };
        ration_glj.prototype.removeNodeByRation = function(ration,controller){//删除主材或设备节点
            let glj_list = _.filter(projectObj.project.ration_glj.datas,{'rationID':ration.ID});
            let deleteNodes = [];
            for(let rg of glj_list){
                if(this.needShowToTree(rg)){
                    let r_node = projectObj.project.mainTree.getNodeByID(rg.ID);
                    deleteNodes.push(r_node);
                }
            }
            if(deleteNodes.length > 0){
                let rowIndex = deleteNodes[0].serialNo();
                if(controller.tree.m_delete(deleteNodes)){
                    TREE_SHEET_HELPER.massOperationSheet(controller.sheet, function () {
                        let rowCount = deleteNodes.length;
                        controller.sheet.deleteRows(rowIndex, rowCount);
                    });
                }
            }
        };

        ration_glj.prototype.refreshAfterUpdate = function (data) {
            let me = this;
            let rationID= me.updateCacheAfterAdjust(data);
            gljOprObj.showRationGLJSheetData(true);
            this.reCalcWhenGLJChange({rationID:rationID});
        };

        ration_glj.prototype.updateCacheAfterAdjust=function (data) {
            let me = this;
            let rationID=null;
            if (data.quantityRefresh) {
                data.glj_result.forEach(function (item) {
                    rationID = me.refreshEachItme(item.doc, item.query);
                })
            } else {
                rationID =  me.refreshEachItme(data.doc, data.query);
            }
            return rationID;
        };


        ration_glj.prototype.refreshEachItme = function (doc, query) {
            let glj = this.refreshByID(query.ID,doc);
            return glj.rationID;
        };

        ration_glj.prototype.refreshByID=function (ID,doc) {
            let glj_list = projectObj.project.ration_glj.datas;
            let glj_index = _.findIndex(glj_list,{"ID":ID});
            _.forEach(doc, function (n, key) {
                glj_list[glj_index][key] = n;
            });
            return glj_list[glj_index]
        };

        ration_glj.prototype.refreshAfterDelete = function (data) {
            let me = projectObj.project.ration_glj;
            let glj_list = me.datas;
            let oldData = _.remove(glj_list, data.query);
            _.remove(gljOprObj.sheetData, data.query);
            gljOprObj.showRationGLJSheetData();
            projectObj.project.projectGLJ.loadData();
            let rationNode = null;
            let next = null;
            let selected = projectObj.project.mainTree.selected;
            if (selected.sourceType == ModuleNames.ration) { //如果选中的是定额，说明是右键删除工料机操作，如果选中的是定额工料机，则说明是在造价书主界面中点击了删除按钮
                rationNode = selected;
            } else if (selected.sourceType == ModuleNames.ration_glj) {
                rationNode = selected.parent;
                next = true;
            }
            rationNode.data.adjustState = data.adjustState;
            projectObj.mainController.refreshTreeNode([rationNode]);
            for (let o of oldData) {
                if (this.needShowToTree(o)) {
                    let node = me.findGLJNodeByID(o.ID);  //找到对应的树节点
                    projectObj.mainController.deleteNode(node, next);
                }
            }
            project.calcProgram.calcAndSave(rationNode,function () {
                installationFeeObj.calcInstallationFee();
            });
        };
        // CSL,2017.05.09
        ration_glj.prototype.modifyQuantity = function (data, newQuantity) {
            this.project.beginUpdate('modifyQuantity');
            data.quantity = newQuantity;
            data.customQuantity = newQuantity;
            data.updateType = 'ut_update';
            this.project.push(this.getSourceType, data);
            this.project.endUpdate();
        };

        ration_glj.prototype.modifyPrice = function (data, newPrice) {
            this.project.beginUpdate('modifyPrice');
            data.price = newPrice;
            data.updateType = 'ut_update';
            this.project.push(this.getSourceType, data);
            this.project.endUpdate();
        };

        ration_glj.prototype.deleteGLJ = function (data) {
            this.project.beginUpdate('deleteGLJ');
            data.customQuantity = 0;
            data.quantity = 0;
            data.rationItemQuantity = 0;
            data.updateType = 'ut_update';
            this.project.push(this.getSourceType, data);
            this.project.endUpdate();
        };
        ration_glj.prototype.addRationGLJ = function (newRation, data) {
            let souceTypeList = [];
            let criteriaDataList = [];
            if (data.hasOwnProperty('rationGljList') && data.rationGljList.length > 0) {
                let criteria = {};
                criteria.ration_glj_list = [];
                for (let i = 0; i < data.rationGljList.length; i++) {
                    let temdata = data.rationGljList[i];
                    let newGLJ = {};
                    newGLJ.projectID = parseInt(newRation.projectID);
                    newGLJ.GLJID = temdata.gljId;
                    newGLJ.rationID = newRation.ID;
                    newGLJ.billsItemID = newRation.billsItemID;
                    newGLJ.rationItemQuantity = temdata.consumeAmt;
                    newGLJ.quantity = temdata.consumeAmt;
                    newGLJ.glj_repository_id = data.rationRepId;
                    criteria.ration_glj_list.push(newGLJ);
                }
                criteria.updateType = 'ut_create';
                souceTypeList.push(this.getSourceType());
                criteriaDataList.push(criteria);
            }
            let ration_coe = projectObj.project.ration_coe;
            let rationCoeData = ration_coe.getRationCoedata(newRation, data);
            souceTypeList.push(ration_coe.getSourceType());
            criteriaDataList.push(rationCoeData);
            project.pushNow('addRationGLJAndRationCoe', souceTypeList, criteriaDataList);

        };

        ration_glj.prototype.getDeleteDataByRation = function (rationData) {
            let updateData = [];
            updateData.push({
                'deleteType': 'RATION',
                'updateType': 'ut_delete',
                'updateData': {'ID': rationData.ID, 'projectID': rationData.projectID}
            });
            return updateData;
        };
        ration_glj.prototype.getDeleteDataByBills = function (datas) {
            let updateData = [];
            datas.forEach(function (deleteData) {
                if (deleteData.type == 'delete') {
                    let billData = deleteData.data;
                    updateData.push({
                        'deleteType': 'BILL',
                        'updateType': 'ut_delete',
                        'updateData': {'ID': billData.ID, 'projectID': billData.projectID}
                    });
                }
            })
            return updateData;
        };
        ration_glj.prototype.deleteByRation = function (ration) {
            let glj_list = projectObj.project.ration_glj.datas;
            _.remove(glj_list,{'rationID':ration.ID});
        };
        ration_glj.prototype.deleteByBills = function (deleteData) {
            let rationList = projectObj.project.Ration.datas;
            let deleteRationList = [];
            for (let i = 0; i < deleteData.length; i++) {
                if (deleteData[i].type == 'delete') {
                    let billID = deleteData[i].data.ID;
                    let raList = _.filter(rationList, (ration) => {
                        return ration.billsItemID == billID;
                    });
                    deleteRationList = deleteRationList.concat(raList);
                }
            }
            for (let i = 0; i < deleteRationList.length; i++) {
                this.deleteByRation(deleteRationList[i]);
                projectObj.project.ration_coe.deleteByRation(deleteRationList[i]);
                projectObj.project.quantity_detail.deleteByRation(deleteRationList[i]);
                projectObj.project.ration_installation.deleteByRation(deleteRationList[i]);
                projectObj.project.Ration.datas.splice(projectObj.project.Ration.datas.indexOf(deleteRationList[i]), 1);
            }
        }

        ration_glj.prototype.updataOrdelete = function (row) {
            let updateData = null;
            if (row.rationItemQuantity == 0) {
               /* updateData = this.getUpdateData('ut_delete', {
                    'ID': row.ID,
                    'projectID': row.projectID
                }, {rationID: row.rationID});
                project.pushNow('updateRationGLJ', [this.getSourceType()], updateData)*/
                this.deleteRationGLJ({ID:row.ID,rationID:row.rationID, projectID: row.projectID,type:row.type});
            } else {
                this.updateRationGLJByEdit(row, 'customQuantity', 0);
                //('ut_update',{'ID': row.ID, 'projectID': row.projectID},{'quantity':0,'customQuantity':0});
            }
        };

        ration_glj.prototype.deleteRationGLJ = async function(data){
            try {
                let result = await ajaxPost('/rationGlj/deleteRationGLJ',data);
                console.log(result);
                let oldData = this.addAndDeleteDatas([],result.deleteList);
                this.refreshQuantityAfterCalResult(result.glj_result);
                let rationNode = null;
                let next = null;
                let selected = projectObj.project.mainTree.findNode(result.rationID);
                if (selected.sourceType == ModuleNames.ration) { //如果选中的是定额，说明是右键删除工料机操作，如果选中的是定额工料机，则说明是在造价书主界面中点击了删除按钮
                    rationNode = selected;
                } else if (selected.sourceType == ModuleNames.ration_glj) {
                    rationNode = selected.parent;
                    next = true;
                }
                rationNode.data.adjustState = result.adjustState;
                projectObj.mainController.refreshTreeNode([rationNode]);
                for (let o of oldData) {
                    if (this.needShowToTree(o)) {
                        let node = me.findGLJNodeByID(o.ID);  //找到对应的树节点
                        projectObj.mainController.deleteNode(node, next);
                    }
                }
                project.calcProgram.calcAndSave(rationNode,function () {
                    installationFeeObj.calcInstallationFee();
                });
                gljOprObj.refreshView();
                projectObj.project.projectGLJ.loadData();
            }catch (e){
                console.log(e)
            }

        };

        ration_glj.prototype.getUpdateData = function (type, query, doc, callfunction) {
            let updateData = [];
            let newobj = {
                'updateType': type,
                'query': query,
            }
            if (doc) {
                newobj['doc'] = doc;
            }
            if (callfunction) {
                newobj['updateFunction'] = callfunction;
            }
            updateData.push(newobj);
            return updateData;
        };
        ration_glj.prototype.updateRationGLJByEdit = function (recode, updateField, newval, node) {
            let me = this,doc = {};
            doc[updateField] = newval;
            me.submitChange(recode,doc,updateField,node);
        };

        ration_glj.prototype.submitChange = function(recode,updateData,updateField,node){
            let me = this;
            let query = {
                'ID': recode.ID,
                'projectID': recode.projectID,
                'rationID': recode.rationID
            };
            let priceInfo = {
                base_price: recode.basePrice,
                market_price: recode.marketPrice
            };
            if(updateData['type'] != undefined || updateData['type'] != null){
                updateData.shortName = projectObj.project.projectGLJ.getShortNameByID(updateData['type']);
            }
            let callback = function (data) {
                if (updateField == 'customQuantity') {
                    me.refreshAfterQuantityUpdate(data, node);
                } else {
                    let doc = data.doc;
                    for (let key in doc) {
                        recode[key] = doc[key];
                    }
                    me.refreshRationAfterEdit(data,recode.rationID, node);//更新名称和定额调整状态
                    if (node) {//如果不是在造价书页面直接编辑，则不用刷新
                        if (updateField == "type" && !(updateData['type'] == gljType.MAIN_MATERIAL || updateData['type'] == gljType.EQUIPMENT)) {//如果改变类型后不是主材或设备，则在造价书树中移除
                            projectObj.mainController.deleteNode(node, true);
                        }
                    }
                }
                projectObj.project.projectGLJ.loadData(function () {//等项目工料机加载完成后再给用户编辑
                    me.refreshTreeNodeIfNeeded(recode);//刷新造价书上的树节点(如果需要)
                    me.reCalcWhenGLJChange(recode);//触发计算定额以及父节点
					zmhs_obj.refreshStableDataIfNeeded();
                    gljOprObj.refreshView();
					$.bootstrapLoading.end();
                    installationFeeObj.calcInstallationFee();
                });
            };
            $.bootstrapLoading.start();
            CommonAjax.post("/rationGlj/updateRationGLJByEdit", {
                query: query,
                doc: updateData,
                priceInfo: priceInfo
            }, callback, function (err) {
                $.bootstrapLoading.end();
            });
        };
        ration_glj.prototype.refreshAfterQuantityUpdate = function (data, node) {
            this.refreshQuantityAfterCalResult(data.glj_result);
            this.refreshRationAfterEdit(data, data.rationID, node);
        };
        ration_glj.prototype.refreshQuantityAfterCalResult = function (glj_result) {//后端计算后，前端刷新结果
            let me = this;
            glj_result.forEach(function (item) {
                me.refreshEachItme(item.doc, item.query);
            });
        };

        ration_glj.prototype.refreshRationAfterEdit= function(data,rationID,rnode){
            let nodes = [];
            let node = this.refreshRationNode(data.name,data.adjustState,rationID);
            if (node) nodes.push(node);
            if (rnode)  nodes.push(rnode);
            projectObj.mainController.refreshTreeNode(nodes);
        };
        ration_glj.prototype.refreshRationNode = function(name,adjustState,rationID){
            let node = projectObj.project.mainTree.findNode(rationID);
            if (!node)  return null;
            if(gljUtil.isDef(adjustState)){
                node.data.adjustState = adjustState;
            }
            if(gljUtil.isDef(name)){
                node.data.name = name;
            }
            return node
        };
        ration_glj.prototype.getGLJData = function (url, cb) {
            let property = projectObj.project.projectInfo.property;
            //let engineerID = property.engineering_id;
            CommonAjax.get(url, function (data) {
                //编办中有多单价设置
                if(data.datas.priceProperties && data.datas.priceProperties.length > 0){
                    let tem = _.find(data.datas.priceProperties,{region:property.region,taxModel:parseInt(property.taxType)});
                    if(tem){
                        let dataCode = tem.price.dataCode;
                        for(let glj of data.datas.stdGLJ){
                            if(glj.priceProperty && gljUtil.isDef(glj.priceProperty[dataCode])) glj.basePrice = glj.priceProperty[dataCode];
                        }
                    }
                };
                cb(data);
            })
        };
        ration_glj.prototype.insertGLJAsRation = function (GLJSelection, selected,insertType, callback) {
            let gljList = [];
            let allGLJ = gljOprObj.AllRecode;
            let billsItemID = null, serialNo = 0,selectedSerialNo = null,nextNodeID = null, parentNodeID = null, billNode = null;
            let pEngineer = projectObj.project.projectInfo.property.projectEngineering;
            let children = [];
            if (selected.sourceType === project.Bills.getSourceType()) {
                billsItemID = selected.data.ID;
                parentNodeID = selected.getID();
                nextNodeID = selected.tree.rootID();
                billNode = selected;
            } else {
                billsItemID = selected.data.billsItemID;
                serialNo = selected.data.serialNo;
                selectedSerialNo = selected.data.serialNo;
                nextNodeID = selected.getNextSiblingID();
                parentNodeID = selected.getParentID();
                billNode = selected.parent;
            }
            children = project.Ration.getBillsSortRation(billsItemID);
            serialNo == 0 ? serialNo = children.length : "";
            for (let con_key of GLJSelection) {
                let glj = _.find(allGLJ, function (item) {
                    let i_key = gljOprObj.getIndex(item, gljLibKeyArray);
                    return i_key == con_key;
                });
                if (glj) {
                    serialNo += 1;
                    let new_glj = {
                        ID: project.Ration.getNewRationID(),
                        projectID: parseInt(project.ID()),
                        billsItemID: billsItemID,
                        type: rationType.gljRation,
                        code: glj.code,
                        name: glj.name,
                        quantity: 0,
                        unit: glj.unit,
                        specs: glj.specs,
                        subType: glj.gljType,
                        model:glj.model,
                        basePrice: glj.basePrice,
                        marketPrice:glj.basePrice,
                        original_code: glj.code,
                        shortName: glj.shortName,
                        serialNo: serialNo,
                        GLJID: glj.ID,
                        adjCoe: glj.adjCoe,
                        materialType:glj.materialType,
                        materialCoe:glj.materialCoe,
                        grossWeightCoe:glj.grossWeightCoe,
                        purchaseStorageRate:glj.purchaseStorageRate,
                        offSiteTransportLossRate:glj.offSiteTransportLossRate,
                        handlingLossRate:glj.handlingLossRate,
                        repositoryId: glj.repositoryId
                    };
                    if(pEngineer) new_glj.programID = pEngineer;
                    if(insertType=="insertEquipment")  new_glj.programID = projectObj.project.calcProgram.compiledTemplateMaps['设备购置'];
                    /* let belongFlag = cbTools.getBelongFlag(selected); 原来是在设备购置清单下插入设备才要取设备勾置费的，现在改成插入设备直接取
                    if (belongFlag && belongFlag === fixedFlag.EQUIPMENT_ACQUISITION_FEE) {
                        new_glj.programID = projectObj.project.calcProgram.compiledTemplateMaps['设备购置'];
                    } */
                    if (glj.hasOwnProperty("compilationId")) {
                        new_glj.from = "cpt";
                        if (glj.code.indexOf('-') != -1) {//这条工料机是用户通过修改名称、规格、型号等保存到补充工料机库的
                            new_glj.original_code = glj.code.split('-')[0];//取-前的编号作为原始编号
                        }
                    }
                    if(optionsOprObj.getOption(optionsOprObj.optionsTypes.GENERALOPTS, 'rationQuanACToBillsQuan')){//需要根据清单转换工程量
                        new_glj.quantityEXP="QDL";
                        if(billNode.data.quantity){
                            new_glj.quantity = scMathUtil.roundForObj(billNode.data.quantity/FilterNumberFromUnit(glj.unit),getDecimal("glj.quantity"));
                            new_glj.contain =  scMathUtil.roundForObj(new_glj.quantity/billNode.data.quantity,6);
                        }
                    }
                    gljList.push(new_glj);
                }
            }
            if (gljList.length == 0) {
                return;
            }
            let postData = {
                gljList: gljList,
                projectID: parseInt(project.ID()),
                billsItemID: billsItemID,
                rationCount: project.Ration.maxRationID()
            }
            selectedSerialNo == null ? "" : postData.selectedSerialNo = selectedSerialNo;
            CommonAjax.post("/ration/insertGLJAsRation", postData, function (data) {
                // 更新兄弟节点的序列号
                if (selectedSerialNo != null) {
                    let selectIndex = _.findIndex(children, {"serialNo": selectedSerialNo});
                    if (selectIndex + 1 < children.length) {
                        for (let i = selectIndex + 1; i < children.length; i++) {
                            children[i].serialNo += gljList.length;
                        }
                    }
                }
                callback(parentNodeID,nextNodeID,data);
            }, function () {
                $.bootstrapLoading.end();
            });

        };
        ration_glj.prototype.getGLJDataByCodes = function (codes,callback) {
            if(!gljUtil.isDef(codes)||codes.length ==0) {
                if(callback) callback([]);
                return
            }
            $.bootstrapLoading.start();
            CommonAjax.post("/rationGlj/getGLJDataByCodes", { 'engineerID':projectObj.project.projectInfo.property.engineering_id,projectID:projectObj.project.ID(),codes:codes}, function (result) {
                $.bootstrapLoading.end();
                callback(result)
            });
        };

        ration_glj.prototype.getAddDataByStd = function (glj,rationID,billsItemID,projectID) {//生成添加类型的定额工料机数据
            let ration_glj = {
                projectID: projectID,
                GLJID: glj.ID,
                rationID: rationID,
                billsItemID: billsItemID,
                rationItemQuantity: 0,
                quantity: 0,
                name: glj.name,
                code: glj.code,
                original_code: glj.code,
                unit: glj.unit,
                specs: glj.specs,
                basePrice: glj.basePrice,
                marketPrice:glj.basePrice,
                shortName: glj.shortName,
                type: glj.gljType,
                model:glj.model,
                adjCoe: glj.adjCoe,
                createType: 'add',
                materialType:glj.materialType,
                materialCoe:glj.materialCoe,
                grossWeightCoe:glj.grossWeightCoe,
                purchaseStorageRate:glj.purchaseStorageRate,
                offSiteTransportLossRate:glj.offSiteTransportLossRate,
                handlingLossRate:glj.handlingLossRate,
                repositoryId: glj.repositoryId
            };
            if (glj.hasOwnProperty("compilationId")) {
                ration_glj.from = "cpt";
                if (glj.code.indexOf('-') != -1) {//这条工料机是用户通过修改名称、规格、型号等保存到补充工料机库的
                    ration_glj.original_code = glj.code.split('-')[0];//取-前的编号作为原始编号
                }
            }
            return ration_glj;
        };


        ration_glj.prototype.addGLJByLib = function (GLJSelection, ration, callback) {
            let me=this,gljList = [];
            let allGLJ = gljOprObj.AllRecode;
            GLJSelection.sort();
            _.forEach(GLJSelection, function (g) {
                let glj = _.find(allGLJ, function (item) {
                    let i_key = gljOprObj.getIndex(item, gljLibKeyArray);
                    return i_key == g;
                });
                let ration_glj = me.getAddDataByStd(glj,ration.ID,ration.billsItemID,ration.projectID);
                gljList.push(ration_glj);
            });
            $.bootstrapLoading.start();
            CommonAjax.post("/rationGlj/addGLJ", gljList, callback, function () {
                $.bootstrapLoading.end();
            });
        };

        ration_glj.prototype.updateRationGLJByChangeCode = function (recode, updateField, newval) {
            let me = this;
            let priceMap = projectObj.project.projectGLJ.datas.unitPriceMap;
            let priceObj = priceMap[newval];
            if(priceObj){
                if (recode.createType===undefined || recode.createType == 'normal') {// createTypel 默认是normal 只有是定额下带的工料机才需把类型改成替换，其它的保持不变
                    recode.rcode = recode.code;
                    recode.createType = 'replace';
                }
                recode.code = priceObj.code;
                recode.name = priceObj.name;
                recode.type = priceObj.type;
                recode.unit = priceObj.unit;
                recode.shortName = priceObj.short_name;
                recode.specs = priceObj.specs;
                recode.GLJID=priceObj.glj_id;
                recode.original_code =  priceObj.original_code;
                recode.basePrice = priceObj.base_price;
                recode.marketPrice = priceObj.market_price;
            }
            $.bootstrapLoading.start();
            CommonAjax.post("/rationGlj/replaceGLJ", recode, function (result) {
                if (result) {
                    me.setDatasAfterReplace(result);
                    let data = result.data;
                    let rationNode = projectObj.project.mainTree.findNode(data.rationID);
                    let nodes =  [rationNode];
                    gljOprObj.refreshView();
                    if (project.ration_glj.needShowToTree(data)) {//当替换的是主材或设备时，刷新对应的树节点
                        let node = project.ration_glj.findGLJNodeByID(data.ID);
                        if (node) {
                            project.ration_glj.transferToNodeData(data);
                            node.source = data;
                            node.data = data;
                        }
                        node ? nodes.push(node) : "";
                    }
                    rationNode.data.adjustState = result.adjustState;
                    rationNode.data.name = result.name;
                    projectObj.mainController.refreshTreeNode(nodes);
                    project.calcProgram.calcAndSave(rationNode);
                    $.bootstrapLoading.end();
                }
            }, function () {
                $.bootstrapLoading.end();
            });
        };

        ration_glj.prototype.setDatasAfterReplace = function(result){
            let me = this;
            me.addAndDeleteDatas(result.newRecodes,result.deleteList);
            let list_index = _.findIndex(me.datas, {'ID': result.data.ID});
            if(result.data) me.datas[list_index] = result.data;
            me.refreshQuantityAfterCalResult(result.glj_result);
            if(result.projectGLJ) project.projectGLJ.loadNewProjectGLJToCaches([result.projectGLJ],true);
        };

        ration_glj.prototype.addAndDeleteDatas = function (newRecodes,deleteList) {
            let oldData = [];
          if(newRecodes.length > 0 ) this.datas = this.datas.concat(newRecodes);
          if(deleteList.length > 0) {
              oldData =  _.remove(this.datas,function (item) {
                  return  deleteList.indexOf(item.ID)!=-1;
              });
          }
          return oldData;
        };
        ration_glj.prototype.getReplaceDataByStd = function (oldData,glj) {
            if (oldData.createType===undefined || oldData.createType == 'normal') {// createTypel 默认是normal 只有是定额下带的工料机才需把类型改成替换，其它的保持不变
                oldData.rcode = oldData.code;
                oldData.createType = 'replace';
                oldData.mIndexObj ={code:oldData.code,name:oldData.name,type:oldData.type,unit:oldData.unit,specs:oldData.specs};
            }else if(oldData.createType == 'replace' && oldData.rcode == glj.code){//如果原数据已经是替换过的，这次替换又恢复成原数据，则把类型改回来
                oldData.createType = 'normal';
                oldData.mIndexObj = null;
            }
            oldData.GLJID = glj.ID;
            oldData.name = glj.name;
            oldData.type = glj.gljType;
            oldData.code = glj.code;
            oldData.original_code = glj.code;
            oldData.unit = glj.unit;
            oldData.specs = glj.specs;
            oldData.model = glj.model;
            oldData.basePrice = glj.basePrice;
            oldData.shortName=glj.shortName;
            oldData.marketPrice = glj.basePrice;
            oldData.repositoryId = glj.repositoryId;
            oldData.materialType = glj.materialType;
            oldData.materialCoe =  glj.materialCoe;
            oldData.grossWeightCoe= glj.grossWeightCoe;
            oldData.purchaseStorageRate = glj.purchaseStorageRate;
            oldData.offSiteTransportLossRate = glj.offSiteTransportLossRate;
            oldData.handlingLossRate = glj.handlingLossRate;
            if (glj.hasOwnProperty("compilationId")) {
                oldData.from = "cpt";
                if (glj.code.indexOf('-') != -1) {//这条工料机是用户通过修改包称、规格、型号等保存到补充工料机库的
                    oldData.original_code = glj.code.split('-')[0];//取-前的编号作为原始编号
                }
            } else {
                oldData.from = "std";
            }
            return oldData;
        };


        ration_glj.prototype.replaceGLJ = function (selectCode, oldData, callback) {
            let allGLJ = gljOprObj.AllRecode;
            let glj = _.find(allGLJ, function (item) {
                let i_key = gljOprObj.getIndex(item, gljLibKeyArray);
                return i_key == selectCode;
            });
            if (selectCode == gljOprObj.getIndex(oldData, gljKeyArray)) {
                return callback(null);
            }
            //如果是从混凝土改成商品混凝土，并且混凝土的定额消耗量不为空，则原混凝土的自定义消耗改成0，插入一条新的商品混凝土自定义消耗量为原定额计算后的消耗量
            if(gljUtil.isAddCommercialForReplace(oldData.type,glj.gljType,oldData.rationItemQuantity)){
                let originalID = oldData.ID;
                let customQuantity = gljUtil.isDef(oldData.quantity)? oldData.quantity:0;
                oldData = this.getAddDataByStd(glj,oldData.rationID,oldData.billsItemID,oldData.projectID);
                oldData.toCommercial=true;
                oldData.originalID = originalID;
                oldData.customQuantity = customQuantity;
            }else {
                oldData = this.getReplaceDataByStd(oldData,glj);
            }
            $.bootstrapLoading.start();
            CommonAjax.post("/rationGlj/replaceGLJ", oldData, callback, function () {
                $.bootstrapLoading.end();
            });
        };

        ration_glj.prototype.mReplaceGLJ = function (selectCode, oldData, callback) {
            let allGLJ = gljOprObj.AllRecode,tasks = [],updateMap={},doc = null;
            let oldIndex = gljOprObj.getIndex(oldData, gljKeyArray);
            let glj = _.find(allGLJ, function (item) {
                let i_key = gljOprObj.getIndex(item, gljLibKeyArray);
                return i_key == selectCode;
            });
            if (selectCode == oldIndex) {
                return callback(null);
            }
            let query = {
                projectID: oldData.projectID,
                code: oldData.code,
                name: oldData.name,
                unit: oldData.unit,
                type: oldData.type
            };
            if (oldData.specs && oldData.specs != '') {
                query.specs = oldData.specs;
            }
            for(let d of this.datas){//查询出所有需替换的工料机
                if(!gljOprObj.scopeSelectedIDMap[d.billsItemID]) continue; //如果不在选中范围的，跳过
                let tem_index = gljOprObj.getIndex(d, gljKeyArray);
                if(tem_index == oldIndex){
                    let tem_doc = {};
                    //是否从混凝土改成商品混凝土，并且混凝土的定额消耗量不为空
                    if(gljUtil.isAddCommercialForReplace(d.type,glj.gljType,d.rationItemQuantity)){
                        tem_doc = {'customQuantity':'0'};
                        //插入一条新的定额,这里的更新自定义消耗量操作由task完成了，不用像单条替换那样做标记，修改等
                        let newDoc =  this.getAddDataByStd(glj,d.rationID,d.billsItemID,d.projectID);
                        let customQuantity = gljUtil.isDef(d.quantity)? d.quantity:0;
                        newDoc.customQuantity = customQuantity;
                        let tTask = {insertOne:{document: newDoc}};
                        tasks.push(tTask);
                        doc=newDoc//后台操作： 要根据nweDoc,插入项目工料机，修改insertOne里项目工料机ID,生成新的自身ID
                    }else {
                        tem_doc = this.getReplaceDataByStd(d,glj);
                        if(gljUtil.isConcreteType(d.type)||gljUtil.isCommercialConcreteType(d.type)) tem_doc.isConcrete = true;//这里是在批量替换中有可能同时存在定额下的替换和添加的替换，对于添加的替换，要走替换混凝土的逻辑，定额下的替换又走另外的逻辑
                        doc = tem_doc;
                    }
                    let task = {
                        updateOne:{
                            filter : {ID:d.ID,rationID:d.rationID},
                            update : tem_doc
                        }
                    };
                    tasks.push(task);
                    updateMap[d.ID] = tem_doc;
                }
            }

            $.bootstrapLoading.start();
            CommonAjax.post("/rationGlj/mReplaceGLJ", {query: query, doc: doc,tasks:tasks}, function (result) {
                callback(result,updateMap);
            }, function () {
                $.bootstrapLoading.end();
            });
        };

        ration_glj.prototype.getMainAndEquGLJ = function (rationID) {
            let gljList = _.filter(this.datas, function (n) {
                return n.rationID == rationID && (n.type == gljType.MAIN_MATERIAL || n.type == gljType.EQUIPMENT)
            });
            gljList = gljUtil.sortRationGLJ(gljList);
            return gljOprObj.combineWithProjectGlj(gljList);
        };
        ration_glj.prototype.transferToNodeData = function (data) {
            data.contain=scMathUtil.roundForObj(data.quantity,getDecimal('glj.quantity'));
            data.subType = data.type;
        };
        ration_glj.prototype.combineRationAndGLJ = function (ration) {
            if (ration) {
                let projectGLJData = projectObj.project.projectGLJ.datas;
                let projectGljs = projectGLJData.gljList;
                let mixRatioMap = projectGLJData.mixRatioMap;
                let glj = _.find(projectGljs, {'id': ration.projectGLJID});
                if (glj) {
                    if(projectObj.project.projectGLJ.isEstimateType(glj.type)){
                        ration.isEstimate = glj.is_evaluate;
                    }
                    ration = gljOprObj.setGLJPrice(ration,glj);
                    ration.isAdd = glj.unit_price.is_add;
                    let connect_index = gljOprObj.getIndex(glj, gljKeyArray);
                    if (mixRatioMap.hasOwnProperty(connect_index)) {
                        let mixRatios = gljOprObj.getMixRationShowDatas(mixRatioMap[connect_index], projectGljs);
                        ration.subList = mixRatios;
                    }
                }
            }
            return ration;
        };
        ration_glj.prototype.updateFromMainSpread = function (value, node, fieldName) {
            if (node.data[fieldName] !== value) {
                if (fieldName == "marketUnitFee") {
                    let decimal = getDecimal("glj.unitPrice");
                    let newval = number_util.checkNumberValue(value, decimal);
                    if (newval) {
                        fieldName = "marketPrice";
                        projectObj.project.projectGLJ.updatePriceFromRG(node.data, fieldName, newval);
                        return;

                    }
                } else {
                    if(fieldName == "contain"){
                        if(value==null){
                            value="";
                        }else {
                            let decimal = getDecimal("glj.quantity");
                            value = number_util.checkNumberValue(value, decimal);
                            fieldName="customQuantity";//填入自定义消耗
                        }
                    }

                    if (value !== undefined && value !== null) {
                        if (fieldName == "subType") {
                            node.data.subType = value;
                            fieldName = "type";//转换成更新工料机类型
                        }
                        this.updateRationGLJByEdit(node.data, fieldName, value, node);
                        return;
                    }
                }
            }
            // node.data.subType = value;
            projectObj.mainController.refreshTreeNode([node]);
        };
        ration_glj.prototype.refreshTreeNodeIfNeeded = function (data) {
            if (this.needShowToTree(data)) {
                this.transferToNodeData(data);
                gljOprObj.refreshTreeNode({"type": ModuleNames.ration_glj, "ID": data.ID});
            }
        };
        ration_glj.prototype.needShowToTree = function (data) {
            if ((data.type == gljType.MAIN_MATERIAL || data.type == gljType.EQUIPMENT) && projectObj.project.projectInfo.property.displaySetting.disPlayMainMaterial == true) {
                return true
            }
            return false
        };
        ration_glj.prototype.findGLJNodeByID = function (ID) {
            return projectObj.project.mainTree.findNode(ID);
        };
        ration_glj.prototype.findRationNodeByID = function (ID) {
            return projectObj.project.mainTree.findNode(ID);
        };
        ration_glj.prototype.reCalcWhenGLJChange = function (ration_glj) {//当改变定额工料机时，重新计算定额以及其父节点
            let node = this.findRationNodeByID(ration_glj.rationID);
            if (node) {
                node.changed = true;
                project.calcProgram.calcAndSave(node);
            }
        };
        ration_glj.prototype.reCalcWhenVvTaxChange = function () {
            let rationIDs = [];
            for(let g of this.datas){
                if(g.type == gljType.GENERAL_MACHINE) rationIDs.push(g.rationID);
            }
            this.calcRationsByIDs(_.uniq(rationIDs))
        };
        ration_glj.prototype.calcRationsByIDs = function (rationIDs) {
            let nodes = [];
            for(let ID of rationIDs){
                let node =  projectObj.project.mainTree.findNode(ID);
                if(node) nodes.push(node)
            }
            project.calcProgram.calcNodesAndSave(nodes);
        };
        ration_glj.prototype.updateProportion = function (proportionList, projectID, rationID) {
            const postData = {
                proportionList,
                projectID,
                rationID
            };
            $.bootstrapLoading.start();
            CommonAjax.post('/rationGLJ/updateProportion', postData, function (rst) {
                proportionList.forEach(item => {
                    const glj = zmhs_obj.stableSheetData.find(glj => glj.ID === item.ID);
                    if (glj) {
                        glj.adjustProportion = item.adjustProportion;
                    }
                });
                zmhs_obj.refreshStableDataIfNeeded();
                zmhs_obj.refreshAfterUpdate(rst);
                $.bootstrapLoading.end();
            }, function () {
                zmhs_obj.refreshStableDataIfNeeded();
                $.bootstrapLoading.end();
            });
        };
        return new ration_glj(project);
    }
};