/**
 * Created by zhang on 2018/1/31.
 */
var installation_fee = {
    createNew: function (project) {
        // 用户定义private方法
        var tools = {};

        // 所有通过this访问的属性，都不应在此单元外部进行写入操作
        var installation_fee = function (proj) {
            // this.project = proj;
            this.datas = [];

            var sourceType = ModuleNames.installation_fee;
            this.getSourceType = function () {
                return sourceType;
            }
            proj.registerModule(ModuleNames.installation_fee, this);
        };

        // prototype用于定义public方法
        installation_fee.prototype.loadData = function (datas) {
            this.datas = datas;
        };
        installation_fee.prototype.getInstallationFeeByLibID=function(libID){
            return _.find(this.datas,{'libID':libID});
        };
        installation_fee.prototype.getInstallationFeeByID=function(ID){
            return _.find(this.datas,{'ID':ID});
        };

        installation_fee.prototype.getFeeRuleByFeeItem = function (feeItem) {
            let installFee = projectObj.project.installation_fee.getInstallationFeeByLibID(feeItem.libID);
            let impacRules = _.filter(installFee.feeRule,{'feeItemId':feeItem.ID});
            return impacRules;
        };
        installation_fee.prototype.getFeeRuleBySection = function (section) {
            let installFee = projectObj.project.installation_fee.getInstallationFeeByLibID(section.libID);
            let impacRules = _.filter(installFee.feeRule,{'sectionId':section.ID});
            return impacRules;
        };
        installation_fee.prototype.getInstallSectionsByfeeItemID=function(libID,feeItemId){
            let installationFee = this.getInstallationFeeByLibID(libID);
            let installSections = _.filter(installationFee.installSection,{'feeItemId':feeItemId});
            return installSections;
        };
        installation_fee.prototype.getFeeItemByID = function(libID,ID){
            let installFee = projectObj.project.installation_fee.getInstallationFeeByLibID(libID);
            return _.find(installFee.installFeeItem,{'ID':ID});
        };
        installation_fee.prototype.getInstallSectionByID = function(libID,ID){
            let installFee = projectObj.project.installation_fee.getInstallationFeeByLibID(libID);
            return _.find(installFee.installSection,{'ID':ID});
        };
        installation_fee.prototype.getFeeRuleBySectionID=function(libID,sectionId){
            let installationFee = this.getInstallationFeeByLibID(libID);
            let feeRules = _.filter(installationFee.feeRule,{'sectionId':sectionId});
            return feeRules;
        };
        installation_fee.prototype.getFeeRuleByID = function (libID,feeRuleID) {
            let installationFee = this.getInstallationFeeByLibID(libID);
            return _.find(installationFee.feeRule,{'ID':feeRuleID});
        };
        installation_fee.prototype.updateFeeItem = function(doc,libID,feeItemID,cleanPosition,callback){
            let me = this,ration_install=projectObj.project.ration_installation;
            let feeItem = me.getFeeItemByID(libID,feeItemID);
            let temFeeItem = _.cloneDeep(feeItem);//暂时不更新缓存
            let updateData = [];
            let cleanRules = [];
            let rationInstallations = [];
            for(let d_key in doc){
                temFeeItem[d_key] = doc[d_key]
            }
            updateData.push(me.getFeeItemUpdateData(libID,feeItemID,doc));
            let sections = me.getInstallSectionsByfeeItemID(libID,feeItemID);
            for (let s of sections){
                if(temFeeItem.isCal == 1){//勾选记取的时候要同步更新对应的定额安装费
                    me.getRIUpdateDataBySectionUpdate(s.ID,s.feeRuleId,rationInstallations);//生成受影响的定额安装增加费并加入到数组中
                }else {//取消打勾时清空对应的定额安装费的规则项
                    me.getRIUpdateDataBySectionUpdate(s.ID,"",rationInstallations);//生成受影响的定额安装增加费并加入到数组中
                }
            }
            if(cleanPosition==true){//如果要清除记取位置
                let [dataArray,impacRules] = installationFeeObj.getFeeRuleUpdateDataByFeeItem(feeItem,{code: "",ID:''});
                updateData = updateData.concat(dataArray);
                cleanRules = impacRules;
            }
            $.bootstrapLoading.start();
            me.submitInstallationUpdate(updateData,rationInstallations,function (data) {
                //更新缓存
                for(let d_key in doc){
                    feeItem[d_key] = doc[d_key]
                }
                for(let ir of cleanRules){//清除记取位置
                    ir.position = "";
                    ir.billID  = "";
                }
                if(callback){
                    callback();
                }
                $.bootstrapLoading.end();
            });
        };
        installation_fee.prototype.getRIUpdateDataBySectionUpdate = function (sectionID,newRuleID,rationInstallations) {
            let ration_install=projectObj.project.ration_installation;
            let ris = ration_install.getBySectionID(sectionID);
            for(let ri of ris){
                if(ri.unifiedSetting==1&&ri.ruleId!=newRuleID){//勾选按统一设置并且费率规则选择的不一样
                    rationInstallations.push({ID:ri.ID,doc:{'ruleId':newRuleID}});
                }
            }
        };

        installation_fee.prototype.updateFeeRule = function (doc,libID,feeRuleID,callback) {
            let me = this;
            let itemUpdateData = null;
            let feeItem=null;
            let ruleUpdateData=null;
            let updateData = [];
            let feeRule = me.getFeeRuleByID(libID,feeRuleID);
            if(feeRule){
                if(doc){//如果有需要更新的属性
                    ruleUpdateData = me.getFeeRuleUpdateData(libID,feeRuleID,doc);
                    updateData.push(ruleUpdateData);
                    if(doc.hasOwnProperty("billID")){//改变了选取位置后如果与费用项里的位置不一致的话要清空费用项的选取位置
                        feeItem = me.getFeeItemByID(libID,feeRule.feeItemId);
                        if(feeItem.position!=''&&feeItem.billID!=doc.billID){
                            itemUpdateData = me.getFeeItemUpdateData(libID,feeItem.ID,{position: "", billID:""});
                            updateData.push(itemUpdateData);
                        }
                    }
                    $.bootstrapLoading.start();
                    me.submitInstallationUpdate(updateData,null,function (data) {
                        //更新缓存
                        let isFeeItemUpdate = false;
                        if(itemUpdateData){
                            feeItem.position ="";
                            feeItem.billID = "";
                            isFeeItemUpdate= true;
                        }
                        for(let ukey in doc){
                            feeRule[ukey]=doc[ukey];
                        }
                        if(callback){//回调
                            callback(isFeeItemUpdate);
                        }
                        $.bootstrapLoading.end();
                    });
                }
            }else {
                if(callback){
                    callback(false);
                }
            }
        };
       installation_fee.prototype.getFeeRuleUpdateData = function (libID,feeRuleID,doc) {
            let installationFee = this.getInstallationFeeByLibID(libID);
            let updateData = {
                ID:installationFee.ID,
                itemID:feeRuleID,
                type:"feeRule",
                doc:doc
            };
            return updateData;
        };
       installation_fee.prototype.getSectionUpdateData = function (libID,sectionID,doc) {
           let installationFee = this.getInstallationFeeByLibID(libID);
           let updateData = {
               ID:installationFee.ID,
               itemID:sectionID,
               type:"installSection",
               doc:doc
           };
           return updateData;
       };
        installation_fee.prototype.getFeeItemUpdateData = function (libID,itemID,doc) {
           let installationFee = this.getInstallationFeeByLibID(libID);
            let updateData = {
                ID:installationFee.ID,
                itemID:itemID,
                type:'installFeeItem',
                doc:doc
            };
            return updateData;
        };
        installation_fee.prototype.updateInstallation = function (updateData,callback) {
            let me = this;
            me.submitInstallationUpdate(updateData,null,function (data) {
                for(let u of updateData){
                    let insFee =  me.getInstallationFeeByID(u.ID);
                    let item = _.find(insFee[u.type],{'ID':u.itemID})
                    if(item){
                        for(let key in u.doc){
                            item[key] = u.doc[key] ;
                        }
                    }
                }
                if(callback){
                    callback(data);
                }
            });
        };
       installation_fee.prototype.submitInstallationUpdate = function (updateData,rationInstallations,callback) {
            if(updateData){
                let data = {'projectID':projectObj.project.projectInfo.ID,'updateData':updateData};
                if(rationInstallations){//是否附带更新定额安装费
                    data['rationInstallations'] = rationInstallations;
                }
                CommonAjax.post('/installation/updateInstallationFee',data,function (data) {
                    //更新定额安装费的缓存
                    if(rationInstallations){
                        for(let ri of rationInstallations){
                            let c_ri = project.ration_installation.getByID(ri.ID);
                            if(c_ri){
                                for(let rkey in ri.doc){
                                    c_ri[rkey] = ri.doc[rkey];
                                }
                            }
                        }
                    }
                    callback(data);
                })
            }
        };
       installation_fee.prototype.calcInstallationFee=function(callback){
            if(!projectObj.project.isInstall()){//如果不是安装工程，则不用计算
                if(callback) callback(false);
                return;
            }
            let project = projectObj.project,me = this;
            let engineering = projectObj.project.projectInfo.property.engineering;
            let installSetting = projectObj.project.projectInfo.property.installSetting;
            let rationInstallation  = project.ration_installation;
            let BXs =  project.Bills.getAllBXs();//取所有补项
            let allBillsDatas = _.sortBy(_.cloneDeep(project.Bills.datas),'code');//取所有清单信息，用来查找清单信息和存放中间过程产生的清单
            let rationKeyMap={};//安装子目关联表
            let newBills = [];
            let billSerialMap = {};
            let FBMap = {};//保存分部下对应的补项
            let usedBXMap = {};//有使用到的补项
            let startTime =  +new Date();
            for(let bx of BXs){//把补项放入映射表中
                FBMap[bx.ParentID] = bx;
            }
            for(let d of me.datas){
                for(let item of d.installFeeItem){
                    //if(item.isCal == 1){ //勾选了记取的费用项  ------------------------------- 2019-07-12  需求修改，这里改成计算的时候不判断是否计取，直接按定额下的安装增加费的设置情况进行计算
                        let rule_ration_map = {};//费用规则定额映射表;
                        let ra_installs = rationInstallation.getCalcRIByItemID(d.libID,item.ID);//取所有有效的定额安装增加费
                        for(let ri of ra_installs){
                            let rationNode = project.mainTree.getNodeByID(ri.rationID);
                            if(rationNode){
                                if(rule_ration_map[ri.ruleId]){
                                    rule_ration_map[ri.ruleId].push(rationNode.data);
                                }else {
                                    rule_ration_map[ri.ruleId] = [rationNode.data];
                                }
                            }
                        }
                        for(let ruleIDKey in rule_ration_map){
                            calcEachRule(item,d.libID,ruleIDKey,rule_ration_map[ruleIDKey],rationKeyMap,newBills);
                        }
                    //}
                }
            }
            let updateData = {
                bills:{
                    delete:[],
                    add:newBills
                },
                ration:{//定额更新只有更新对应的工料机数据
                    delete:[],
                    update:[],
                    add:[]
                },
                userID: userID
            };
            let oldITypeRations = _.cloneDeep(project.Ration.getAllInstallTypeRation())//取所有旧的安装增加费定额-没有用的要删除
            let oldRationMap = {}, deleteRationNodes = [], deleteBillsNodes = [],reCalBillIDS = [];
            let isChange = newBills.length>0;//记录数据是否发生了改变;
            for(let o of oldITypeRations){//过滤出要删除的定额 - 同时对应的父项也要重新更新计算
                if(rationKeyMap[o.installationKey]==undefined){
                    updateData.ration.delete.push(o);
                    let d_node =  project.mainTree.getNodeByID(o.ID);
                    if(d_node){
                        deleteRationNodes.push(d_node);
                        reCalBillIDS.push(o.billsItemID);
                        isChange = true;
                    }
                }
                oldRationMap[o.installationKey] = o;
            }

            for(let inKey in rationKeyMap){
                if(oldRationMap[inKey]){//存在,则更新就可以了
                    if(checkRation(oldRationMap[inKey],rationKeyMap[inKey])){//检查是否需要更新
                        updateData.ration.update.push(oldRationMap[inKey]);
                        isChange = true;
                    }
                }else {
                    updateData.ration.add.push(rationKeyMap[inKey]);
                    isChange = true;
                }
            }

            for(let tem_bx of BXs){//过滤要删除的 自动生成的补项
                if(tem_bx.code&&tem_bx.code.startsWith('BAZF')&& usedBXMap[tem_bx.ParentID]==undefined){
                    updateData.bills.delete.push(tem_bx);
                    let b_node =  project.mainTree.getNodeByID(tem_bx.ID);
                    if(b_node){
                        deleteBillsNodes.push(b_node);
                        isChange = true;
                    }
                }
            }

            if(isChange == true){
                $.bootstrapLoading.start();
                CommonAjax.post("/project/calcInstallationFee",updateData,function (data) {
                    //提交后台成功后所做的操作，删除要先删除定额，再删除清单，添加要先添加清单再添加定额
                    updateData = data.updateData;
                    project.ration_glj.addDatasToList(data.add);//添加插入的定额
                    let calRations = [];
                    for(let ur of data.update){
                        let glj = project.ration_glj.getDataByID(ur.ID);
                        glj.quantity = ur.quantity;
                        glj.rationItemQuantity = ur.rationItemQuantity;
                    }
                    let selectedNode = projectObj.project.mainTree.selected;
                    //对树节点的操作并删除、添加清单、删除添加定额、删除对应的定额工料机缓存
                    TREE_SHEET_HELPER.massOperationSheet(projectObj.mainController.sheet, function () {
                        deleteOldNodes(deleteRationNodes,deleteBillsNodes);
                        calRations =  addNewNodes(updateData);
                    });
                    for(let u of updateData.ration.update){
                        let unode =  projectObj.project.mainTree.findNode(u.ID);
                         unode?calRations.push(unode):'';
                    }
                    if(reCalBillIDS.length > 0){
                        reCalBillIDS = _.uniq(reCalBillIDS);
                        for(let bID of reCalBillIDS){
                            let bnode =  projectObj.project.mainTree.findNode(bID);
                            bnode?calRations.push(bnode):''; //现在计算程序支持同时传入清单和定额了，所以能放一起
                        }
                    }
                    setTreeSelection(selectedNode);
                    let endTime =  +new Date();
                    console.log(`计算安装增加费时间——${endTime - startTime}`);
                    projectObj.project.projectGLJ.loadNewProjectGLJToCaches(data.projectGLJList,true);
                    cbTools.refreshFormulaNodes();
                    if(callback){
                        callback(true,calRations);
                    }
                        $.bootstrapLoading.end();

                });
            }else {
                if(callback) callback(false);
            }
            function addNewNodes(updateData) {
                let controller = projectObj.mainController;
                let Bill = project.Bills;
                let newAddNode = [];
                let newRationNodes = [];
                for(let nb of updateData.bills.add){
                    let newSource = Bill.tree.insertByData(nb, nb.ParentID, -1, true);
                    let newNode = project.mainTree.insert(nb.ParentID, -1, newSource.data.ID);
                    newNode.source = newSource;
                    newNode.sourceType = Bill.getSourceType();
                    newNode.data = newSource.data;
                    controller.sheet.addRows(newNode.serialNo(), 1);
                    controller.sheet.showRow(newNode.serialNo(), GC.Spread.Sheets.VerticalPosition.center);
                    newAddNode.push(newNode);
                    Bill.datas.push(nb);
                }
                for(let nr of updateData.ration.add){
                   let newNode = project.mainTree.insert(nr.billsItemID, -1, nr.ID);
                    newNode.source = nr;
                    newNode.sourceType = project.Ration.getSourceType();
                    newNode.data = nr;
                    controller.sheet.addRows(newNode.serialNo(), 1);
                    controller.sheet.showRow(newNode.serialNo(), GC.Spread.Sheets.VerticalPosition.center);
                    newAddNode.push(newNode);
                    newRationNodes.push(newNode);
                    project.Ration.datas.push(nr);
                }
                TREE_SHEET_HELPER.refreshTreeNodeData(controller.setting, controller.sheet, newAddNode, false);
                return newRationNodes;
            }

            function deleteOldNodes(deleteRationNodes,deleteBillsNodes) {
                let controller = projectObj.mainController, project = projectObj.project;
                let Bill = project.Bills, Ration = project.Ration,ration_glj = project.ration_glj;
                for(let rd of deleteRationNodes){
                    controller.sheet.deleteRows(rd.serialNo(),1);
                    controller.tree.delete(rd);
                    Ration.removeByID(rd.getID());
                    ration_glj.deleteByRation(rd.data);
                }
                for(let bd of deleteBillsNodes){
                    controller.sheet.deleteRows(bd.serialNo(),1);
                    controller.tree.delete(bd);
                    Bill.tree.delete(bd.source);
                    Bill.removeByID(bd.getID());
                }
            }

            function setTreeSelection(oldSelect) {
                let controller = projectObj.mainController;
                let sel = controller.sheet.getSelections()[0];
                if(controller.tree.getNodeByID(oldSelect.getID())){//如果旧选中节点还存在
                    controller.sheet.setSelection(oldSelect.serialNo(),sel.col,sel.rowCount,sel.colCount);
                    controller.setTreeSelected(oldSelect)
                }else {//选中节点已被删除，自动选中新的节点
                    controller.setTreeSelected(controller.tree.items[sel.row]);
                }
            }

            function checkRation(oldRation,newRation) {//检查定额是否需要更新
                let gljs = project.ration_glj.getGljByRationID(oldRation.ID);
                let modify = false;
                let gljList =[];
                for(let g of gljs){
                    if(g.quantity != newRation.glj[g.code].quantity){//消耗量不一样，需重新修改
                        let tem ={
                            ID:g.ID,
                            projectID:g.projectID,
                            quantity :newRation.glj[g.code].quantity,
                            rationItemQuantity:newRation.glj[g.code].rationItemQuantity
                        };
                        gljList.push(tem);
                        modify = true;
                    }
                }
                oldRation.glj = gljList;
                return modify;
            }

            function calcEachRule(item,libID,ruleID,rations,rationKeyMap,newBills) {
                let rule = me.getFeeRuleByID(libID,ruleID);
                let pre_key = libID+item.ID+item.feeType+ruleID;
                if(item.feeType == '子目费用'){
                    for(let r of rations){//在定额的同级新增一条
                        let billItemID = r.billsItemID;
                        let nextID = -1;
                        let newRationData = createNewRationData(billItemID,nextID,rule);
                        let [labourQuantity,materialQuantity,machineQuantity] = calcQuantity(rule,r);
                        newRationData = setGljQuantity(newRationData,labourQuantity,materialQuantity,machineQuantity);
                        let installationKey = pre_key+billItemID;
                        newRationData['installationKey'] = installationKey;
                        if(rationKeyMap[installationKey]){//如果已经存在，则工料机消耗量累加起来
                            sumGLJquantity(rationKeyMap[installationKey],labourQuantity,materialQuantity,machineQuantity);
                        }else {
                            rationKeyMap[installationKey] = newRationData;//在映射表中添加
                        }
                    }
                }else if(item.feeType == '措施费用'){//措施费用时，则在记取位置选择的清单下新增安装子目。
                    allInOne(item,rule,rations,newBills,pre_key,rationKeyMap);
                }else if(item.feeType=='分项费用'){
                    if(installSetting==undefined||installSetting=="0"){//选择了“整个项目统一计取”，则在记取位置选择的分项下新增安装子目
                        allInOne(item,rule,rations,newBills,pre_key,rationKeyMap);
                    }else {//选择了每个分部单独记取
                        calcEveryFB(item,rule,rations,newBills,pre_key,rationKeyMap);
                    }
                }
            }


            function sumGLJquantity(ration,labourQuantity,materialQuantity,machineQuantity) {
                let gljDecimal = getDecimal('glj.quantity');
                let sumLabour = scMathUtil.roundForObj(ration.glj['RGFTZ'].quantity,gljDecimal)+labourQuantity;
                let sumMaterial = scMathUtil.roundForObj(ration.glj['CLFTZ'].quantity,gljDecimal)+materialQuantity;
                let sumMachine = scMathUtil.roundForObj(ration.glj['JXFTZ'].quantity,gljDecimal)+machineQuantity;
                ration.glj['RGFTZ'].quantity =scMathUtil.roundToString(sumLabour,gljDecimal);
                ration.glj['RGFTZ'].rationItemQuantity = scMathUtil.roundToString(sumLabour,gljDecimal);
                ration.glj['CLFTZ'].quantity = scMathUtil.roundToString(sumMaterial,gljDecimal);
                ration.glj['CLFTZ'].rationItemQuantity = scMathUtil.roundToString(sumMaterial,gljDecimal);
                ration.glj['JXFTZ'].quantity = scMathUtil.roundToString(sumMachine,gljDecimal);
                ration.glj['JXFTZ'].rationItemQuantity = scMathUtil.roundToString(sumMachine,gljDecimal);
            }

            function calcEveryFB(item,rule,rations,newBills,pre_key,rationKeyMap) {
                let parentMap = {};
                for(let r of rations){//先归类
                    let rationNode = project.mainTree.getNodeByID(r.ID);
                    if(rationNode){
                        if(parentMap[rationNode.parent.parent.getID()]){
                            parentMap[rationNode.parent.parent.getID()].push(r)
                        }else {
                            parentMap[rationNode.parent.parent.getID()] = [r];
                        }
                    }
                }
                for(let billID_key in parentMap){
                    let gljDecimal = getDecimal('glj.quantity');
                    let tem_rations = parentMap[billID_key];
                    let BXNodeData;
                    if(FBMap[billID_key]){//查看有没有对应的补项，如果没有，新增一个
                        BXNodeData = FBMap[billID_key];
                    }else {//新增一个
                        BXNodeData = {
                            projectID: parseInt(project.ID()),
                            ParentID:billID_key,
                            NextSiblingID:-1,
                            name:'安装增加费',
                            unit:'元',
                            quantity:'1',
                            type:billType.BX
                        };
                        BXNodeData.ID =  uuid.v1();
                        BXNodeData.code = getBXCode("BAZF",usedBXMap);
                        FBMap[billID_key] = BXNodeData;
                        newBills.push(BXNodeData);
                    }
                    usedBXMap[billID_key] = BXNodeData;//记录有用到的补项，最后没有用到的要删除
                    let newRationData = createNewRationData(BXNodeData.ID,-1,rule);
                    let labourSum = 0,materialSum =0,machineSum = 0;
                    for(let ra of tem_rations){//措施费用的情况下，多条定额生成一条安装子目
                        let [tem_labourQuantity,tem_materialQuantity,tem_machineQuantity] = calcQuantity(rule,ra);
                        labourSum =scMathUtil.roundForObj(labourSum+tem_labourQuantity,gljDecimal);
                        materialSum= scMathUtil.roundForObj(materialSum+tem_materialQuantity,gljDecimal);
                        machineSum = scMathUtil.roundForObj(machineSum+tem_machineQuantity,gljDecimal);
                    }
                    newRationData = setGljQuantity(newRationData,labourSum,materialSum,machineSum);
                    let installationKey = pre_key+BXNodeData.ID;
                    newRationData['installationKey'] = installationKey;
                    rationKeyMap[installationKey] = newRationData;//在映射表中添加
                }
            }

            function getBXCode(code,BXMap) {//自动生成物补项编号加001、002等后缀
                let codes = [];
                let i = 1;
                let newCode = '';
                for(let key in BXMap){
                    codes.push(BXMap[key].code);
                }
                while (true){
                    newCode = code + seqString(i,3);
                    if(codes.indexOf(newCode)==-1){
                        break;
                    }
                    i++;
                }
               return newCode;
            }

            function allInOne(item,rule,rations,newBills,pre_key,rationKeyMap) {//统一设置
                let billData = getBillNodeData(item,rule,newBills);//取对应的清单或生成一个新的清单数据
                let newRationData = createNewRationData(billData.ID,-1,rule, item.feeType);
                let gljDecimal = getDecimal('glj.quantity');
                let labourSum = 0,materialSum =0,machineSum = 0;
                for(let r of rations){//措施费用的情况下，多条定额生成一条安装子目
                    let [tem_labourQuantity,tem_materialQuantity,tem_machineQuantity] = calcQuantity(rule,r);
                    labourSum =scMathUtil.roundForObj(labourSum+tem_labourQuantity,gljDecimal);
                    materialSum= scMathUtil.roundForObj(materialSum+tem_materialQuantity,gljDecimal);
                    machineSum = scMathUtil.roundForObj(machineSum+tem_machineQuantity,gljDecimal);
                }
                newRationData = setGljQuantity(newRationData,labourSum,materialSum,machineSum);
                let installationKey = pre_key+billData.ID;
                newRationData['installationKey'] = installationKey;
                rationKeyMap[installationKey] = newRationData;//在映射表中添加
            }

            function setGljQuantity(rationData,labourQuantity,materialQuantity,machineQuantity) {
                let gljDecimal = getDecimal('glj.quantity');
                rationData.glj['RGFTZ'].quantity = scMathUtil.roundToString(labourQuantity,gljDecimal);
                rationData.glj['RGFTZ'].rationItemQuantity = scMathUtil.roundToString(labourQuantity,gljDecimal);
                rationData.glj['CLFTZ'].quantity = scMathUtil.roundToString(materialQuantity,gljDecimal);
                rationData.glj['CLFTZ'].rationItemQuantity = scMathUtil.roundToString(materialQuantity,gljDecimal);
                rationData.glj['JXFTZ'].quantity = scMathUtil.roundToString(machineQuantity,gljDecimal);
                rationData.glj['JXFTZ'].rationItemQuantity = scMathUtil.roundToString(machineQuantity,gljDecimal);
                return rationData;
            }

            function createNewRationData(billItemID,nextID,rule,feeType) {
                let br = project.Ration.getBillsSortRation(billItemID);
                let serialNo = 0;
                if(billSerialMap[billItemID]){
                    serialNo = billSerialMap[billItemID]+1
                }else {
                    serialNo = br.length > 0 ? br[br.length - 1].serialNo + 1 : 1;
                    billSerialMap[billItemID] = serialNo;
                }
                serialNo = br.length > 0 ? br[br.length - 1].serialNo + 1 : 1;
                let newRationData = project.Ration.getTempRationData(project.Ration.getNewRationID(), billItemID, serialNo, rationType.install);
                newRationData = setNewRationProperty(newRationData,nextID,rule);
                if (feeType && feeType === '措施费用') {
                    const installationMeasure = project.calcProgram.templates.find(item => item.name === '安装费用(措施)');
                    if (installationMeasure) {
                        newRationData.programID = installationMeasure.ID;
                    }
                }
                return newRationData;
            }
            function getBillNodeData(item,rule,newBills) {
                let billData = null;
                let billID = null;
                if(rule.billID&&rule.billID!=""){
                    billData = getBillsByID(rule.billID);
                    billID = rule.billID;
                }
                if(!billData){
                    let t_code = rule.position;
                    if(!t_code) t_code = "BAZF";//2019-07-12  需求的修改，改成计算的时候不判断是否计取，直接按定额下的安装增加费的设置改了需求后，有可能造成选取位置为空的情况，这时code为undefinded
                    billData = getBillsByCode(t_code);
                    if(!billData){//如果按ID和按code都找不到清单的话，自动生成一个
                        let newBillData = project.Bills.getNewInstallBillData(t_code,billID,item.feeType);
                        if(item.feeType == '措施费用'){
                            newBillData.type = billType.BILL;
                        }else if(item.feeType == '分项费用'){
                            newBillData.type = billType.FX;
                        }
                        newBills.push(newBillData);
                        allBillsDatas.push(newBillData);
                        return newBillData;
                    }
                }
                return billData;
            }
            function getBillsByID(billID){
                return _.find(allBillsDatas,{"ID":billID});
            }
            function getBillsByCode(code){
                return _.find(allBillsDatas, function(b) {
                    if(b.code&&b.code.indexOf(code)!=-1){
                        return true;
                    }else {
                        return false;
                    }
                })
            }
            function calcQuantity(rule,ration) {//计算单条定额的三个消耗量
                let gljDecimal = getDecimal('glj.quantity');
                let labourQuantity = 0, materialQuantity = 0, machineQuantity = 0;
                let labour = rule.labour?rule.labour*0.01:0;
                let material = rule.material?rule.material*0.01:0;
                let machine = rule.machine?rule.machine*0.01:0;
                let feeRate =  rule.feeRate?rule.feeRate*0.01:0;
                if(rule.base=='分别按人材机乘系数'){//'分别按人材机乘系数','人工','材料','机械'
                    labourQuantity = scMathUtil.roundForObj(parseFloat(project.Ration.getLabourTotalFee(ration))*parseFloat(labour),gljDecimal);
                    materialQuantity = scMathUtil.roundForObj(parseFloat(project.Ration.getMaterialTotalFee(ration))*parseFloat(material),gljDecimal);
                    machineQuantity = scMathUtil.roundForObj(parseFloat(project.Ration.getMachineTotalFee(ration))*parseFloat(machine),gljDecimal);
                }else {
                    let base = 0;
                    if(rule.base=='人工'){
                        base = parseFloat(project.Ration.getLabourTotalFee(ration))*parseFloat(feeRate);
                    }else if(rule.base=='材料'){
                        base = parseFloat(project.Ration.getMaterialTotalFee(ration))*parseFloat(feeRate);
                    }else if(rule.base=='机械'){
                        base = parseFloat(project.Ration.getMachineTotalFee(ration))*parseFloat(feeRate);
                    }
                    labourQuantity = scMathUtil.roundForObj(base*parseFloat(labour),gljDecimal);
                    materialQuantity = scMathUtil.roundForObj(base*parseFloat(material),gljDecimal);
                    machineQuantity = scMathUtil.roundForObj(base*parseFloat(machine),gljDecimal);
                }
                return [labourQuantity,materialQuantity,machineQuantity];
            }

            function setNewRationProperty(data,nextID,rule) {
                data.code = rule.code;
                data.name = rule.rule;
                data.unit = '元';
                data.quantity = '1';
                data.contain ='1';
                data.nextID = nextID;
                //取管理费费率
                if(installationFeeObj.feeRateMap[rule.code]) data.manageFeeRate = installationFeeObj.feeRateMap[rule.code];
                data.glj = {
                    'RGFTZ':{
                        rationID:data.ID,
                        billsItemID:data.billsItemID,
                        shortName:project.projectGLJ.getShortNameByID(gljType.LABOUR),
                        GLJID:-1,
                        projectID:data.projectID,
                        code:'RGFTZ',
                        original_code:'RGFTZ',
                        name:'人工费调整',
                        specs:'',
                        unit:'元',
                        type:gljType.LABOUR,
                        basePrice:1,
                        marketPrice:1,
                        adjCoe:null,
                        from:'std',
                        repositoryId:-1,
                        quantity:'0',
                        rationItemQuantity:'0'
                    },
                    'CLFTZ':{
                        rationID:data.ID,
                        billsItemID:data.billsItemID,
                        shortName:project.projectGLJ.getShortNameByID(gljType.GENERAL_MATERIAL),
                        GLJID:-1,
                        projectID:data.projectID,
                        code:'CLFTZ',
                        original_code:'CLFTZ',
                        name:'材料费调整',
                        specs:'',
                        unit:'元',
                        type:gljType.GENERAL_MATERIAL,
                        basePrice:1,
                        marketPrice:1,
                        adjCoe:null,
                        from:'std',
                        repositoryId:-1,
                        quantity:'0',
                        rationItemQuantity:'0'
                    },
                    'JXFTZ':{
                        rationID:data.ID,
                        billsItemID:data.billsItemID,
                        shortName:project.projectGLJ.getShortNameByID(gljType.GENERAL_MACHINE),
                        GLJID:-1,
                        projectID:data.projectID,
                        code:'JXFTZ',
                        original_code:'JXFTZ',
                        name:'机械费调整',
                        specs:'',
                        unit:'元',
                        type:gljType.GENERAL_MACHINE,
                        basePrice:1,
                        marketPrice:1,
                        adjCoe:null,
                        from:'std',
                        repositoryId:-1,
                        quantity:'0',
                        rationItemQuantity:'0'
                    }
                };
                return data;
            }
        };

        installation_fee.prototype.updateInstallSetting = function (newValue,callback) {
           let mixDatas = {
                projectID: projectObj.project.ID(),
                updateType: 'update',
                properties: {
                    "property.installSetting":newValue
                },
                labourCoes: {},
                rations: [],
                bills: []
            };
            CommonAjax.post('/pm/api/updateMixDatas', {user_id: userID, mixDataArr: mixDatas}, function (rstData) {
                projectObj.project.projectInfo.property.installSetting = newValue;
                if(callback){
                    callback();
                }
            });
        };

        installation_fee.prototype.setRationInstallToDefual = function(){
           let ration_install=projectObj.project.ration_installation;
           let rationInstallations = [];
           for(let ri of ration_install.datas){
              if(ri.unifiedSetting == 0 || ri.ruleId!==""){
                rationInstallations.push({ID:ri.ID,doc:{'ruleId':"",unifiedSetting:1}});
              }
           } 
           return rationInstallations;
        }

        installation_fee.prototype.resetToDefault = function (callback) {
            let me = this;
            let installFees = [];
            for(let d of me.datas){
                let ins ={
                    libID:d.libID,
                    ID:d.ID
                };
                installFees.push(ins);
            }
            //data.projectID,data.installFees
            let rationInstallations = me.setRationInstallToDefual();


            $.bootstrapLoading.start();
            CommonAjax.post("/installation/resetToDefault",{projectID:project.ID(),installFees:installFees,rationInstallations:rationInstallations},function (result) {
                console.log(result)
                me.datas = result;
                 //更新定额安装费的缓存
                 if(rationInstallations.length > 0){
                  for(let ri of rationInstallations){
                      let c_ri = project.ration_installation.getByID(ri.ID);
                      if(c_ri){
                          for(let rkey in ri.doc){
                              c_ri[rkey] = ri.doc[rkey];
                          }
                      }
                  }
                }
                if(callback){
                    callback();
                }
                $.bootstrapLoading.end();
            })
        };
        // 提交数据后返回数据处理
        installation_fee.prototype.doAfterUpdate = function(err, data){

        };
        return new installation_fee(project);
    }

};
