/**
 * 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.getGljArrByBill = function (treeNode, needOneBill) {
            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;
            }

            let nodeQ = calcTools.uiNodeQty(treeNode);
            let q = nodeQ ? nodeQ : 1;
            let allNodes = projectObj.project.Ration.getRationNodes(treeNode);
            let rNodes = allNodes.filter(function (node) {return calcTools.isRationItem(node)});
            let rations = rNodes.map(function (node) {return node.data});

            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);
                        let coe = calcTools.tenderCoe_GLJQty(treeNode, glj);
                        if (!sameGlj) {
                            sameGlj = clone(glj);
                            sameGlj.quantity = (sameGlj.quantity * ration.quantity).toDecimal(4);
                            // glj的 tenderQuantity = glj的quantity * 定额的quantity * glj的消耗量调整系数coe。
                            // 与定额的tenderQuantity无关，与定额的子目工程量调整系数coe无关。下面这里直接取数量即可，因为它在上一句已经乘过定额数量了。
                            sameGlj.tenderQuantity = (sameGlj.quantity * coe).toDecimal(4);
                            result.push(sameGlj);
                        } else {
                            sameGlj.quantity = sameGlj.quantity + (glj.quantity * ration.quantity).toDecimal(4);
                            sameGlj.tenderQuantity = sameGlj.tenderQuantity + (glj.quantity * coe).toDecimal(4);

                            sameGlj.totalQuantity = (parseFloat(sameGlj.totalQuantity) + parseFloat(glj.totalQuantity)).toDecimal(4);
                        }
                    }
                }
            }

            result = gljOprObj.combineWithProjectGlj(result,false);

            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 / q).toDecimal(decimalObj.process);  // 广联达这里没有取舍
                glj.tenderQuantity = (glj.tenderQuantity / q).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 (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,async function () {
                installationFeeObj.calcInstallationFee();
                await OVER_HEIGHT.reCalcOverHeightFee();
                await itemIncreaseFeeObj.calcItemIncreaseFeeByNodes([rationNode.parent]);
            });
        };
        // 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)
            } else {
                this.updateRationGLJByEdit(row, 'customQuantity', 0);
                //('ut_update',{'ID': row.ID, 'projectID': row.projectID},{'quantity':0,'customQuantity':0});
            }
        };
        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,
                taxRate:recode.taxRate
            };
            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 () {//等项目工料机加载完成后再给用户编辑
                    gljOprObj.refreshView();
                    me.refreshTreeNodeIfNeeded(recode);//刷新造价书上的树节点(如果需要)
                    me.reCalcWhenGLJChange(recode);//触发计算定额以及父节点
                    $.bootstrapLoading.end();
                    installationFeeObj.calcInstallationFee();
                    // OVER_HEIGHT.reCalcOverHeightFee();
                });
            };
            $.bootstrapLoading.start();
            CommonAjax.post("/rationGlj/updateRationGLJByEdit", {
                query: query,
                doc: updateData,
                priceInfo: priceInfo
            }, callback, function (err) {
                $.bootstrapLoading.end();
            });
        };
        ration_glj.prototype.refreshAfterQuantityUpdate = function (data, node) {
            let me = this;
            data.glj_result.forEach(function (item) {
                me.refreshEachItme(item.doc, item.query);
            });
            me.refreshRationAfterEdit(data, data.rationID, node);
        };
        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.getGLJDataPaging = function (condition, cb) {
            gljOprObj.loadingPagination = true;
            const property = projectObj.project.projectInfo.property;
            const actionType = $('#actionType').val();
            CommonAjax.post('/rationGlj/getGLJDataPaging', { condition }, function (data) {
                gljOprObj.curPageTotal = data.total;
                data.complementaryGLJs.forEach(glj => {
                    glj.isComplementary = true;
                });
                const gljType = condition.type === gljOprObj.pagingType.stdGLJ
                    ? 'stdGLJ'
                    : 'complementaryGLJs';
                const newData = data[gljType];
                // 添加组成物，类型为主材时，需要排除自身
                if ((actionType === 'addMix' || actionType === 'unitPriceAddMix') && projectGljObject.selectedProjectGLJ.type === gljType.MAIN_MATERIAL) {
                    const pIndex = gljOprObj.getIndex(projectGljObject.selectedProjectGLJ, gljKeyArray);
                    const delIndex = newData.findIndex(item => gljOprObj.getIndex(item, gljLibKeyArray) === pIndex);
                    if (!~delIndex) {
                        newData.splice(delIndex, 1);
                    }
                }
                if (condition.init) {
                    gljOprObj.treeData = data.treeData;
                    gljOprObj.distTypeTree = gljOprObj.getComboData(data.distTypeTree);
                }
                // 需要重置当前页面数据（点击了分类树、搜索等等）
                if (condition.reset) {
                    gljOprObj.stdGLJ = data.stdGLJ;
                    gljOprObj.complementaryGLJs = data.complementaryGLJs;
                    gljOprObj.AllRecode = [...gljOprObj.stdGLJ, ...gljOprObj.complementaryGLJs];
                } else {
                    gljOprObj[gljType].splice(condition.index, 0, ...newData);
                    gljOprObj.AllRecode.splice(condition.index, 0, ...newData);
                }
                // 根据缓存选中数据，设置人材机是否选中
                newData.forEach(item => {
                    const connectKey = gljOprObj.getIndex(item, gljLibKeyArray);
                    if (gljOprObj.GLJSelection.includes(connectKey)) {
                        item.select = 1;
                    }
                });
                // 设置人材机类型名称
                gljOprObj.setTypeName(gljOprObj.distTypeTree.comboDatas, newData);
                if (data.priceProperties && data.priceProperties.length > 0) {
                    // region: region目前跟单位工程绑定，这里暂时固定写死commonConstants.DEFAULT_REGION，以后应改成跟建设项目绑定的region，
                    let tmp = _.find(data.priceProperties, {region: commonConstants.DEFAULT_REGION, taxModel: parseInt(property.taxType)});
                    if (tmp) {
                        let dataCode = tmp.price.dataCode;
                        let allData = data.stdGLJ.concat(data.complementaryGLJs);
                        for (let glj of allData) {
                            if (glj.priceProperty && gljUtil.isDef(glj.priceProperty[dataCode])) {
                                glj.basePrice = glj.priceProperty[dataCode];
                            }
                        }
                    }
                }
                cb(data[gljType], data);
                gljOprObj.loadingPagination = false;
            }, function () {
                if ($.bootstrapLoading.isLoading()) {
                    $.bootstrapLoading.end();
                }
            });
        };
        ration_glj.prototype.getGLJData = function (cb) {
            let property = projectObj.project.projectInfo.property;
            let engineerID = property.engineering_id;
            CommonAjax.get('/rationGlj/getGLJData/'+engineerID, 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;
                         let allData = data.datas.stdGLJ.concat(data.datas.complementaryGLJs);
                         for(let glj of allData){
                             if(glj.priceProperty && gljUtil.isDef(glj.priceProperty[dataCode])) glj.basePrice = glj.priceProperty[dataCode];
                         }
                     }
                };
                cb(data);
            })
        };
        ration_glj.prototype.insertGLJAsRation = function (GLJSelection, selected, 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,
                        taxRate:glj.taxRate,
                        original_code: glj.code,
                        shortName: glj.shortName,
                        serialNo: serialNo,
                        GLJID: glj.ID,
                        adjCoe: glj.adjCoe,
                        materialType:glj.materialType,
                        materialCoe:glj.materialCoe,
                        materialIndexType:glj.materialIndexType,
                        materialIndexUnit:glj.materialIndexUnit,
                        materialIndexCoe:glj.materialIndexCoe,
                        repositoryId: glj.repositoryId
                    };
                    if(pEngineer) new_glj.programID = pEngineer;
                    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,
                taxRate:glj.taxRate,
                shortName: glj.shortName,
                type: glj.gljType,
                model:glj.model,
                adjCoe: glj.adjCoe,
                createType: 'add',
                materialType:glj.materialType,
                materialCoe:glj.materialCoe,
                materialIndexType:glj.materialIndexType,
                materialIndexUnit:glj.materialIndexUnit,
                materialIndexCoe:glj.materialIndexCoe,
                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) {
            const me = this,
                  gljList = [],
                  allGLJ = gljOprObj.AllRecode;
            GLJSelection.sort();
            GLJSelection.forEach(selKey => {
                const glj = allGLJ.find(item => gljOprObj.getIndex(item, gljLibKeyArray) === selKey);
                if (glj) {
                    const rationGLJ = me.getAddDataByStd(glj, ration.ID, ration.billsItemID, ration.projectID);
                    if (glj.userId) {
                        rationGLJ.fromUser = glj.userId;
                    }
                    gljList.push(rationGLJ);
                }
            });
            $.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) {
                    //result.adjustState;
                    let glj_list = me.datas;
                    let data = result.data;
                    let list_index = _.findIndex(glj_list, {'ID': data.ID});
                    let rationNode = projectObj.project.mainTree.findNode(data.rationID);
                    let nodes =  [rationNode];
                    glj_list[list_index] = data;
                    project.projectGLJ.loadNewProjectGLJToCaches([result.projectGLJ],true);
                    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.getReplaceDataByStd = function (oldData,glj) {
            if (oldData.createType===undefined || oldData.createType == 'normal') {// createTypel 默认是normal 只有是定额下带的工料机才需把类型改成替换，其它的保持不变
                oldData.rcode = oldData.code;
                oldData.createType = 'replace';
            }
            if(oldData.createType == 'replace' && oldData.rcode == glj.code){//如果原数据已经是替换过的，这次替换又恢复成原数据，则把类型改回来
                oldData.createType = 'normal'
            }
            oldData.GLJID = glj.ID;
            oldData.name = glj.name;
            oldData.code = glj.code;
            oldData.original_code = glj.code;
            oldData.unit = glj.unit;
            oldData.specs = glj.specs;
            oldData.type = glj.gljType;
            oldData.model = glj.model;
            oldData.basePrice = glj.basePrice;
            oldData.marketPrice = glj.basePrice;
            oldData.repositoryId = glj.repositoryId;
            oldData.materialType = glj.materialType;
            oldData. materialCoe =  glj.materialCoe;
            oldData. materialIndexType =  glj.materialIndexType;
            oldData. materialIndexUnit =  glj.materialIndexUnit;
            oldData. materialIndexCoe =  glj.materialIndexCoe;
            if (glj.hasOwnProperty("compilationId")) {
                oldData.from = "cpt";
                if (glj.userId) {
                    oldData.fromUser = glj.userId;
                }
                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);
            }
            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={};
            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;
            }
            let doc = {
                GLJID: glj.ID,
                createType: 'replace',
                rationItemQuantity: 0,
                name: glj.name,
                code: glj.code,
                original_code: glj.code,
                unit: glj.unit,
                specs: glj.specs,
                type: glj.gljType,
                model:glj.model,
                basePrice: glj.basePrice,
                marketPrice:glj.basePrice,
                repositoryId: glj.repositoryId,
                materialType: glj.materialType,   //三材类别
                materialCoe: glj.materialCoe,
                materialIndexType: glj.materialIndexType,
                materialIndexUnit: glj.materialIndexUnit,
                materialIndexCoe: glj.materialIndexCoe,
                projectID: oldData.projectID
            };
            if (glj.hasOwnProperty("compilationId")) {
                doc.from = "cpt";
                if (glj.userId) {
                    doc.fromUser = glj.userId;
                }
                if (glj.code.indexOf('-') != -1) {//这条工料机是用户通过修改包称、规格、型号等保存到补充工料机库的
                    doc.original_code = glj.code.split('-')[0];//取-前的编号作为原始编号
                }
            } else {
                doc.from = "std";
            }
            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 = _.cloneDeep(doc);
                    if(d.createType == 'replace'){
                        tem_doc.rcode = d.rcode;
                    }else if(d.createType == 'add'){//对于添加的类型，替换后还是添加类型
                        tem_doc.createType = 'add';
                    }else {
                        tem_doc.rcode = d.code
                    }
                    let task = {
                        updateOne:{
                            filter : {ID:d.ID},
                            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, async function () {
                    await OVER_HEIGHT.reCalcOverHeightFee();
                    await itemIncreaseFeeObj.calcItemIncreaseFeeByNodes([node.parent]);
                });
            }
        };
        return new ration_glj(project);
    }
};