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


let gljUtil = {
    calcProjectGLJQuantity:function (projectGLJDatas,rationGLJDatas,rationDatas,billsDatas,q_decimal,_,scMathUtil,isReport) {
        let project_gljs = projectGLJDatas.gljList;
        let mixRatioMap = projectGLJDatas.mixRatioMap;
        let rations = rationDatas;
        let rationMap = _.indexBy(rations,'ID');
        let quantityMap={};
        let rationGljGroup = _.groupBy(rationGLJDatas,'projectGLJID');
        let IDarray =  this.getSubdivisionAndTechBillsLeavesID(billsDatas);//分别取分部分项和技术措施项目的所有叶子清单ID
        let billIDs = IDarray[0],tech_billIDS = IDarray[1];
        let sField = "subdivisionQuantity";
        let tField = "techQuantity";
        let qField = "quantity";

        for(let pglj of project_gljs ){
            let pg_index = this.getIndex(pglj,this.gljKeyArray);
            pglj[sField] = 0;
            pglj[tField] = 0;
            pglj[qField] = 0;
            let gljGroup = rationGljGroup[pglj.id]?rationGljGroup[pglj.id]:[];//定额工料机没有，有可能是定额类型的工料机
            let result = this.getQuantityPerGLJ(gljGroup,rations,rationMap,pglj,billIDs,tech_billIDS,q_decimal,_,scMathUtil);
            pglj[sField] = result.subdivisionQuantity;
            pglj[tField] = result.techQuantity;
            pglj[qField] = result.quantity;
            pglj.tenderQuantity = result.tenderQuantity;
            quantityMap[pg_index] = pglj;
        }
        //计算做为组成物的消耗量
        for(let pkey in mixRatioMap){
            let mixRatioList = mixRatioMap[pkey];
            for(let m of mixRatioList){
                let m_index = this.getIndex(m,this.gljKeyArray);
                let m_glj = quantityMap[m_index];
                let p_glj = quantityMap[pkey];
                if(m_glj&&p_glj){
                    let quantity = scMathUtil.roundForObj(parseFloat(p_glj[qField])*parseFloat(m.consumption),q_decimal);
                    let tenderQuantity = scMathUtil.roundForObj(parseFloat(p_glj.tenderQuantity)*parseFloat(m.consumption),q_decimal);
                    let techQuantity = scMathUtil.roundForObj(parseFloat(p_glj[tField])*parseFloat(m.consumption),q_decimal);
                    let subdivisionQuantity = scMathUtil.roundForObj(parseFloat(p_glj[sField])*parseFloat(m.consumption),q_decimal);
                    m_glj[qField] =  scMathUtil.roundForObj(parseFloat(m_glj[qField])+quantity,q_decimal);
                    m_glj.tenderQuantity =  scMathUtil.roundForObj(parseFloat(m_glj.tenderQuantity)+tenderQuantity,q_decimal);
                    m_glj[tField] =  scMathUtil.roundForObj(parseFloat(m_glj[tField])+techQuantity,q_decimal);
                    m_glj[sField] =  scMathUtil.roundForObj(parseFloat(m_glj[sField])+subdivisionQuantity,q_decimal);
                }
            }
        }

        if (isReport) {
            for(let pglj of project_gljs ){
                pglj[qField] = pglj.tenderQuantity;
            }
        }
    },
    getQuantityPerGLJ : function (ration_glj_list,rations,rationMap,pglj,billIDs,tech_billIDS,q_decimal,_,scMathUtil) {
        let result={};
        let quantity_sum=0;//工料机汇总消耗量
        let sum = 0;//分部分项总消耗量
        let tech_sum = 0;//技术措施总消耗量
        let tender_qantity_sum = 0;
        for(let rg of ration_glj_list){
            let tem_ration = rationMap[rg.rationID];
            let r_quantity = tem_ration?scMathUtil.roundForObj(tem_ration.quantity,q_decimal):0;
            let glj_quantity = scMathUtil.roundForObj(rg.quantity, q_decimal);
            let tender_r_quantity = r_quantity;
            let tender_glj_quantity = glj_quantity;
            if(!r_quantity){
                continue;
            }
            if(!pglj.is_adjust_price){
                tender_glj_quantity = this.getRationGLJTenderQuantity(rg,tem_ration,q_decimal,scMathUtil);
                tender_r_quantity = this.getRationTenderQuantity(tem_ration,q_decimal,scMathUtil);
            }
            let total = scMathUtil.roundForObj(glj_quantity*r_quantity, q_decimal);
            let tender_total = scMathUtil.roundForObj(tender_glj_quantity*tender_r_quantity, q_decimal);
            quantity_sum = scMathUtil.roundForObj(quantity_sum+total,q_decimal);
            tender_qantity_sum = scMathUtil.roundForObj(tender_qantity_sum+tender_total,q_decimal);
            if(_.includes(billIDs,rg.billsItemID)){//计算分部分项
                sum = scMathUtil.roundForObj(sum+total,q_decimal);
            }
            if(_.includes(tech_billIDS,rg.billsItemID)){//计算技术措施项目消耗量
                tech_sum = scMathUtil.roundForObj(tech_sum+total,q_decimal);
            }
        }
        //2019-11-07 定额类型工料机已经屏蔽，如果打开，记得加上调价后的消耗量
        for(let ra of rations){//计算定额类型工料机的消耗量
            if(ra.type == this.rationType.gljRation&&ra.projectGLJID===pglj.id){
                let r_quantity = scMathUtil.roundForObj(ra.quantity,q_decimal);
                r_quantity = r_quantity?r_quantity:0;
                let tender_r_quantity = r_quantity;
                if(!pglj.is_adjust_price){
                  tender_r_quantity = this.getRationTenderQuantity(ra,q_decimal,scMathUtil);
                }
                quantity_sum = scMathUtil.roundForObj(quantity_sum+r_quantity,q_decimal);
                tender_qantity_sum = scMathUtil.roundForObj(tender_qantity_sum+tender_r_quantity,q_decimal);
                if(_.includes(billIDs,ra.billsItemID)){//计算分部分项
                    sum = scMathUtil.roundForObj(sum+r_quantity,q_decimal);
                }
                if(_.includes(tech_billIDS,ra.billsItemID)){//计算技术措施项目消耗量
                    tech_sum = scMathUtil.roundForObj(tech_sum+r_quantity,q_decimal);
                }
            }
        } 
        result.subdivisionQuantity = sum;
        result.techQuantity = tech_sum;
        result.quantity = quantity_sum;
        result.tenderQuantity = tender_qantity_sum;
        return result;
    },
    getRationGLJTenderQuantity:function (ration_glj,ration,q_decimal,scMathUtil,projectGLJ) {
        let coeMap = {
          1:'labour',  //人工
          2:'material',//材料
          3:'machine',//机械
          4:'main', //主材
          5:'equipment'//设备
        };
        let typeString = ration_glj.type +"";
        let coeField = "";
        for(let key in coeMap){
            if(typeString.indexOf(key) == 0){
              coeField = coeMap[key];
              break;
            }
        }
        let coe = 1;
        if(projectGLJ && projectGLJ.is_adjust_price == 0){
          coe = ration.quantityCoe&&this.isNotEmpty(ration.quantityCoe[coeField])?ration.quantityCoe[coeField]:1;
          coe = parseFloat(coe);
        }else{
          coe = 1;
        }  
        if (coe == 0) coe = 1;
        let glj_quantity = scMathUtil.roundForObj(ration_glj.quantity, q_decimal);
        return scMathUtil.roundForObj(glj_quantity * coe,q_decimal);
    },
    getRationTenderQuantity:function (ration,q_decimal,scMathUtil) {
        let rationQuantityCoe = this.isNotEmpty(ration.rationQuantityCoe)?ration.rationQuantityCoe:1;
        rationQuantityCoe = parseFloat(rationQuantityCoe);
        if (rationQuantityCoe == 0) rationQuantityCoe = 1;
        let r_quantity = ration?scMathUtil.roundForObj(ration.quantity,q_decimal):0;
        return scMathUtil.roundForObj(r_quantity * rationQuantityCoe,q_decimal);
    },
    isNotEmpty:function (str) {
        return this.isDef(str) && str!="";
    },
    getSubdivisionAndTechBillsLeavesID:function (billsDatas) {//分别取分部分项和技术措施项目的所有叶子清单ID
         if(typeof (projectObj) !== 'undefined'){//存在，说明在前端调用
             return [projectObj.project.Bills.getSubdivisionProjectLeavesID(),projectObj.project.Bills.getTechLeavesID()];
         }
        let parentMap ={};
        let subdivisionBillID  = null,techBillID = null,sIDs = [],tIDS = [];
        for(let b of billsDatas){
            if(parentMap[b.ParentID]){
                parentMap[b.ParentID].push(b);
            }else {
                parentMap[b.ParentID]= [b];
            }
            let flag = this.getFlag(b);
            if(this.isDef(flag)&&flag.flag == this.fixedFlag.SUB_ENGINERRING){
                subdivisionBillID = b.ID;
            }
            if(this.isDef(flag)&&flag.flag == this.fixedFlag.CONSTRUCTION_TECH){
                techBillID = b.ID;
            }
        }

        getLeaveIDs(subdivisionBillID,parentMap,sIDs);
        getLeaveIDs(techBillID,parentMap,tIDS);
        return [sIDs,tIDS];

        function getLeaveIDs(ID,parentM,leaveIDs) {
            if(parentM[ID] && parentM[ID].length > 0){
                let children  =  parentM[ID];
                for(let c of children){
                    if(parentM[c.ID]){
                        getLeaveIDs(c.ID,parentM,leaveIDs);
                    }else {
                        leaveIDs.push(c.ID);
                    }
                }
            }
        }
    },
    getFlag:function (b) {
        return _.find(b.flags,{"fieldName":"fixed"});
    },
    getGLJPrice:function (glj,projectGLJDatas,calcOptions,labourCoeDatas,decimalObj,isRadio,_,scMathUtil,tenderCoe, isReport) {
        let result = {};
        if(isReport){
            result.marketPrice = this.getMarketPrice(glj,projectGLJDatas,calcOptions,decimalObj,isRadio,_,scMathUtil,tenderCoe);
        }else {
            result.marketPrice = this.getMarketPrice(glj,projectGLJDatas,calcOptions,decimalObj,isRadio,_,scMathUtil);
            result.tenderPrice = this.getMarketPrice(glj,projectGLJDatas,calcOptions,decimalObj,isRadio,_,scMathUtil,tenderCoe);
        }
        if(this.calcPriceDiff(glj,calcOptions)==true){//计取价差
            result.basePrice = this.getBasePrice(glj,projectGLJDatas,calcOptions,labourCoeDatas,decimalObj,isRadio,_,scMathUtil);
            result.adjustPrice = this.getAdjustPrice(glj,projectGLJDatas,calcOptions,labourCoeDatas,decimalObj,isRadio,_,scMathUtil);
        }else {//不计价差
            result.basePrice = result.marketPrice;
            result.adjustPrice = result.marketPrice;
        }
        return result;
    },
    getMarketPrice:function (glj,projectGLJDatas,calcOptions,decimalObj,isRadio,_,scMathUtil,tenderCoe) {
        let price_decimal = decimalObj.glj.unitPrice;
        let price_hasM_decimal = decimalObj.glj.unitPriceHasMix?decimalObj.glj.unitPriceHasMix:decimalObj.glj.unitPrice;
        let quantity_decimal = decimalObj.glj.quantity;
        let process_decimal = decimalObj.process;
        let priceCoe = this.isDef(tenderCoe)?tenderCoe:1;
        if (priceCoe == '0' || priceCoe == 0) priceCoe = 1;   // 这里加个保护
        if (['GLF', 'LR', 'FXF'].includes(glj.code)) priceCoe = 1; // 类型是“企业管理费”、“利润”、“一般风险费”的，不应调整单价。
        if (this.notEditType.indexOf(glj.unit_price.type)!=-1&&glj.ratio_data.length>0) {//对于混凝土、配合比、砂浆、机械台班等有组成物的材料，价格需根据组成物计算得出。
            let p =0;
            for(let ratio of glj.ratio_data){
                let rIndex = gljUtil.getIndex(ratio);
                let tem = null;
                if(projectGLJDatas.gljMap){
                    tem = projectGLJDatas.gljMap[rIndex]
                }
                if(!tem){
                    tem =  _.find(projectGLJDatas.gljList,function(item){
                        return rIndex == gljUtil.getIndex(item)
                    });
                }
              
                if(tem){
                    let tem_marketPrice = this.getMarketPrice(tem,projectGLJDatas,calcOptions,decimalObj,true,_,scMathUtil);  //let priceData=this.getGLJPrice(tem,projectGLJDatas,calcOptions,labourCoeDatas,decimalObj,true,_,scMathUtil);
                    let temP = scMathUtil.roundForObj(
                        scMathUtil.roundForObj(tem_marketPrice * priceCoe, price_decimal) *
                        scMathUtil.roundForObj(ratio.consumption,quantity_decimal), process_decimal);
                    p = scMathUtil.roundForObj(temP + p, process_decimal);
                }
            }
            return scMathUtil.roundForObj(p,price_hasM_decimal);
        }else {
            let tem_decimal =price_decimal; //isRadio==true?process_decimal:price_decimal;
            let tem_price = scMathUtil.roundForObj(glj.unit_price.market_price,price_decimal);
            return scMathUtil.roundForObj(tem_price*priceCoe,tem_decimal);
        }
    },
    getBasePrice:function (glj,projectGLJDatas,calcOptions,labourCoeDatas,decimalObj,isRadio,_,scMathUtil) {
        let price_decimal = decimalObj.glj.unitPrice;
        let price_hasM_decimal = decimalObj.glj.unitPriceHasMix?decimalObj.glj.unitPriceHasMix:decimalObj.glj.unitPrice;
        let quantity_decimal = decimalObj.glj.quantity;
        let process_decimal = decimalObj.process;

        if (this.notEditType.indexOf(glj.unit_price.type)!=-1&&glj.ratio_data.length>0) {//对于混凝土、配合比、砂浆、机械台班等有组成物的材料，价格需根据组成物计算得出。
            //2018-09-07 需求修改，定额价不按组成物的量和价实时计算出来，直接取单价文件中的定额价
       /*     let p =0;
            for(let ratio of glj.ratio_data){
                let tem =  _.find( projectGLJDatas.gljList,{
                    'code': ratio.code,
                    'name': ratio.name,
                    'specs':ratio.specs,
                    'type': ratio.type,
                    'unit': ratio.unit
                });
                if(tem){
                    let priceData=this.getGLJPrice(tem,projectGLJDatas,calcOptions,labourCoeDatas,decimalObj,true,_,scMathUtil);
                    let temP = scMathUtil.roundForObj(priceData.basePrice*scMathUtil.roundForObj(ratio.consumption,quantity_decimal),process_decimal);
                    p = scMathUtil.roundForObj(temP + p,process_decimal);
                }
            }
            return scMathUtil.roundForObj(p,price_hasM_decimal);*/

            return scMathUtil.roundForObj(glj.unit_price.base_price,price_hasM_decimal);
        }else {
            let tem_decimal =price_decimal; //isRadio==true?process_decimal:price_decimal;
            return scMathUtil.roundForObj(glj.unit_price.base_price,tem_decimal);
        }
    },
    //这个函数isRadio目前看来没有用，如果后续改了方法，导致isRadio的值会影响结果的话，需要调整调用这个方法的地方.
    getAdjustPrice:function (glj,projectGLJDatas,calcOptions,labourCoeDatas,decimalObj,isRadio,_,scMathUtil) {
        let decimal = decimalObj.glj.unitPrice;
        let price_hasM_decimal = decimalObj.glj.unitPriceHasMix?decimalObj.glj.unitPriceHasMix:decimalObj.glj.unitPrice;
        let quantity_decimal =  decimalObj.glj.quantity;
        let process_decimal = decimalObj.process;
        let  tem_decimal = isRadio==true?process_decimal:decimal;
        if (glj.unit_price.type == this.gljType.LABOUR || glj.unit_price.type == this.gljType.MACHINE_LABOUR) {//人工、机上人工，调整价根据定额价*调整系数计算得出。
            let labour = _.find(labourCoeDatas.coes,{'ID':glj.adjCoe});
            let coe = labour && labour.coe ? labour.coe : 1;
            return scMathUtil.roundForObj(parseFloat(coe * scMathUtil.roundForObj(glj.unit_price.base_price,decimal)), decimal);
        } else if (this.notEditType.indexOf(glj.unit_price.type)!=-1&&glj.ratio_data.length>0) {//对于混凝土、配合比、砂浆、机械台班，调整价根据组成物计算得出。
            let p =0;
            for(let ratio of glj.ratio_data){
                let rIndex = gljUtil.getIndex(ratio);
                let tem = null;
                if(projectGLJDatas.gljMap){
                    tem = projectGLJDatas.gljMap[rIndex]
                }
                if(!tem){
                    tem =  _.find(projectGLJDatas.gljList,function(item){
                        return rIndex == gljUtil.getIndex(item);
                    });
                }
                if(tem){
                    let priceData=this.getGLJPrice(tem,projectGLJDatas,calcOptions,labourCoeDatas,decimalObj,true,_,scMathUtil);
                    let temP = scMathUtil.roundForObj(priceData.adjustPrice*scMathUtil.roundForObj(ratio.consumption,quantity_decimal),process_decimal);
                    p = scMathUtil.roundForObj(temP + p,process_decimal);
                }
            }
            return scMathUtil.roundForObj(p,price_hasM_decimal);
        } else {//对于其他普通材料等，无调整系数，调整价=定额价。
            return  scMathUtil.roundForObj(glj.unit_price.base_price,decimal)
        }
    },
    calcPriceDiff:function (glj,calcOptions) {
        if(glj.is_evaluate==1){//先按是否暂估判断
            return calcOptions.calc_est;
        }
        if(glj.type == this.gljType.MAIN_MATERIAL || glj.type == this.gljType.EQUIPMENT){//再判断是否是主材和设备
            return calcOptions.calc_main;
        }
        if(glj.unit_price.is_add==1){//再判断是否新增
            return calcOptions.calc_add;
        }
        return true;
    },
    isFlag : function (v) {
        return this.isDef(v.flagsIndex) && this.isDef(v.flagsIndex.fixed) && this.isDef(v.flagsIndex.fixed.flag);
    },
    isDef:function (v) {
        return v !== undefined && v !== null;
    },
    nullString(key){
        return (key === undefined || key === null || key === '') ? 'null' : key
      },
    getIndex(obj, pops){
        let t_index = '';
        let k_arr = [];
        if(!pops) pops = this.gljKeyArray;
        if(pops.length === 5){
            return `${this.nullString(obj[pops[0]])}|-|${this.nullString(obj[pops[1]])}|-|${this.nullString(obj[pops[2]])}|-|${this.nullString(obj[pops[3]])}|-|${this.nullString(obj[pops[4]])}`
        }else{
            for (let p of pops) {
                let tmpK = (obj[p] == undefined || obj[p] == null || obj[p] == '') ? 'null' : obj[p];
                k_arr.push(tmpK);
            }
            t_index = k_arr.join("|-|");
            return t_index;
        }
    },
    getGljTypeSeq:function () {
        let gljType = this.gljType;
        return   [gljType.LABOUR,gljType.MAIN_MATERIAL,gljType.CONCRETE,gljType.MORTAR,gljType.MIX_RATIO,gljType.COMMERCIAL_CONCRETE,
                gljType.COMMERCIAL_MORTAR,gljType.GENERAL_MATERIAL,gljType.OTHER_MATERIAL,gljType.GENERAL_MACHINE,gljType.INSTRUMENT,gljType.OTHER_MACHINE_USED,
                gljType.MACHINE_COMPOSITION,gljType.MACHINE_LABOUR,gljType.FUEL_POWER_FEE,gljType.DEPRECIATION_FEE,gljType.INSPECTION_FEE,gljType.MAINTENANCE,
                gljType.DISMANTLING_FREIGHT_FEE,gljType.VERIFICATION_FEE,gljType.OTHER_FEE,gljType.EQUIPMENT,gljType.MANAGEMENT_FEE,gljType.PROFIT,gljType.GENERAL_RISK_FEE]
    },
    sortRationGLJ:function (list,std) {
        list = _.sortByAll(list, [function (item) {
            let typeField = std == true?"gljType":"type";
            return _.indexOf(gljUtil.getGljTypeSeq(),item[typeField])
        }, "code"]);
        return list;
    },
    getTotalQuantity:function(glj,ration,rd,gd){
        if(ration){
            let quantity = ration.quantity;
            quantity = (quantity == 0 || quantity == undefined || quantity == null || quantity == "") ? 0 : quantity;
            quantity = scMathUtil.roundForObj(quantity, rd);//计算前进行4舍5入
            glj.quantity = scMathUtil.roundForObj(glj.quantity, gd);
            let pglj = calcTools.getProjectGLJ(glj);
            glj.tenderQuantity = this.getRationGLJTenderQuantity(glj, ration, gd, scMathUtil,pglj);

            return scMathUtil.roundForObj(quantity * glj.quantity, gd)+'';
        }
    },
    getEngineerCostData:function(property,bills,fixedFlag,scMathUtil){
        let priceIndex = {
            name:"工程造价指标",
            attrs:[],
            children:[],
        };
        let fixMap = {};
        let buildingArea = this.getBuildArea(property.engineerFeatures); //tender.property.projectFeature?getItemValueBykey(tender.property.projectFeature,"buildingArea"):1;//建筑面积

        for(let b of bills){
            if(b.flags && b.flags.length > 0){
                let f = _.find(b.flags,{"fieldName":"fixed"});
                if(f) fixMap[f.flag] = this.getTotalFee(b,scMathUtil,property.decimal);
            }
        }
        //计算其他组织措施费 = 施工组织措施项目下的子项，除了  安全文明施工费、建设工程竣工档案编制费以外的项
        let CONSTRUCTION_ORGANIZATION = fixMap[fixedFlag.CONSTRUCTION_ORGANIZATION]?fixMap[fixedFlag.CONSTRUCTION_ORGANIZATION]:0;
        let SAFETY_CONSTRUCTION =  fixMap[fixedFlag.SAFETY_CONSTRUCTION]?fixMap[fixedFlag.SAFETY_CONSTRUCTION]:0;
        let PROJECT_COMPLETE_ARCH_FEE =  fixMap[fixedFlag.PROJECT_COMPLETE_ARCH_FEE]? fixMap[fixedFlag.PROJECT_COMPLETE_ARCH_FEE]:0;
        let other_org_fee = CONSTRUCTION_ORGANIZATION - SAFETY_CONSTRUCTION - PROJECT_COMPLETE_ARCH_FEE;
        other_org_fee = other_org_fee >0 ?other_org_fee:0;
        let engineerCost = fixMap[fixedFlag.ENGINEERINGCOST]?fixMap[fixedFlag.ENGINEERINGCOST]:1;
        priceIndex.children.push(this.getEngineerFlag("分部分项工程费",fixMap[fixedFlag.SUB_ENGINERRING],engineerCost,buildingArea,scMathUtil));
        priceIndex.children.push(this.getEngineerFlag("技术措施费",fixMap[fixedFlag.CONSTRUCTION_TECH],engineerCost,buildingArea,scMathUtil));
        priceIndex.children.push(this.getEngineerFlag("安全文明施工费",fixMap[fixedFlag.SAFETY_CONSTRUCTION],engineerCost,buildingArea,scMathUtil));
        priceIndex.children.push(this.getEngineerFlag("建设工程竣工档案编制费",fixMap[fixedFlag.PROJECT_COMPLETE_ARCH_FEE],engineerCost,buildingArea,scMathUtil));
        priceIndex.children.push(this.getEngineerFlag("其他组织措施费",other_org_fee,engineerCost,buildingArea,scMathUtil));
        priceIndex.children.push(this.getEngineerFlag("暂列金额",fixMap[fixedFlag.PROVISIONAL],engineerCost,buildingArea,scMathUtil));
        priceIndex.children.push(this.getEngineerFlag("专业工程暂估价",fixMap[fixedFlag.ENGINEERING_ESITIMATE],engineerCost,buildingArea,scMathUtil));
        priceIndex.children.push(this.getEngineerFlag("计日工",fixMap[fixedFlag.DAYWORK],engineerCost,buildingArea,scMathUtil));
        priceIndex.children.push(this.getEngineerFlag("总承包服务费",fixMap[fixedFlag.TURN_KEY_CONTRACT],engineerCost,buildingArea,scMathUtil));
        priceIndex.children.push(this.getEngineerFlag("索赔与现场签证",fixMap[fixedFlag.CLAIM_VISA],engineerCost,buildingArea,scMathUtil));
        priceIndex.children.push(this.getEngineerFlag("规费",fixMap[fixedFlag.CHARGE],engineerCost,buildingArea,scMathUtil));
        priceIndex.children.push(this.getEngineerFlag("税金",fixMap[fixedFlag.TAX],engineerCost,buildingArea,scMathUtil));
        priceIndex.children.push(this.getEngineerFlag("工程造价",fixMap[fixedFlag.ENGINEERINGCOST],engineerCost,buildingArea,scMathUtil));
        return priceIndex;
    },
    getBuildArea:function (features) {
        if(features){
            let areas = [];
            for(let f of features){
                if(f.index == true && f.value && f.value !=="" && this.IsNumber(f.value)) areas.push(f.value);
            }
            return areas.length==0?1:areas;
        }
        return 1
    },
    getEngineerFlag: function (name,totalCost,engineerCost,buildingArea,scMathUtil) {
        totalCost = totalCost?totalCost:0;
        let flag = {
            name:name,
            attrs:[
                {name: "金额", value: scMathUtil.roundToString(totalCost,3)},
                {name: "单方造价", value: scMathUtil.roundToString(this.calcUnitB(totalCost,buildingArea,scMathUtil),2)},
                {name: "占造价比例", value: scMathUtil.roundToString(totalCost/engineerCost * 100,2)},
            ],
        };
        return flag;
    },
    getTotalFee:function (b,scMathUtil,decimal) {
        let total = 0;
        if(b.fees && b.fees.length > 0){
            for(let f of b.fees){
                if(f.fieldName == "common"){
                    total = scMathUtil.roundForObj(f.tenderTotalFee,decimal?decimal.bills.totalPrice:getDecimal("bills.totalPrice"));
                }
            }
        }
        return total;
    },
     IsNumber : function(pstrVal){
        let dblNo = Number.NaN;
        dblNo = new Number(pstrVal);
        if (isNaN(dblNo)) return false;
        return true;
     },
    calcUnitB:function (total,building,scMathUtil,coe,decimal = 3) {
        if(Array.isArray(building)){
            for(let b of building){
                total = scMathUtil.roundForObj(total/b,6);
            }
        }else {
            total = scMathUtil.roundForObj(total/building,6);
        }
        coe = gljUtil.isDef(coe)?coe:1;
        return scMathUtil.roundForObj(total*coe,decimal);
    },
    getEconomicDatas:function(engineerFeatures,economics,billsList,fixedFlag,_,scMathUtil,decimal){
        let datas = [];
        let [bills,totalFee] = gljUtil.getIndexBills(billsList,fixedFlag,_,scMathUtil,decimal);
        let billsGroup = _.groupBy(bills,'economicType');
        if(!economics) return datas;
        for(let e of economics){
            let tem = {
                name:e.name,
                exportName:e.exportName,
                cost:0,
                unitCost:0,
                per:0
            };
            if(billsGroup[e.name]) setEconomics(billsGroup[e.name],totalFee,tem);
            datas.push(tem);
        }
        function setEconomics(items,engineerCost,data) {
            let cost = 0;
            let priceDe = decimal?decimal.bills.totalPrice:getDecimal("bills.totalPrice");//getDecimal("bills.totalPrice");
            for(let i of items){
                i.totalFee =  scMathUtil.roundForObj(i.totalFee,priceDe);
                cost = scMathUtil.roundForObj(cost + i.totalFee,decimal?decimal.process:getDecimal("process"))//getDecimal("process");
            }
            data.cost = scMathUtil.roundForObj(cost,priceDe);
            data.unitCost = gljUtil.calUnitWidthCoe(data.cost,true,engineerFeatures,_,scMathUtil);//noNeedCoe = true 这里不需要乘以系数
            data.per = engineerCost?scMathUtil.roundForObj(data.cost/engineerCost * 100,2):0;
        }

        return datas;
    },
    calUnitWidthCoe:function (total,noNeedCoe,engineerFeatures,_,scMathUtil) {
        let areas = gljUtil.getBuildArea(engineerFeatures);
        let f = _.find(engineerFeatures,{index:true});
        return f && noNeedCoe!==true?gljUtil.calcUnitB(total,areas,scMathUtil,f.coe):gljUtil.calcUnitB(total,areas,scMathUtil);
    },
    getIndexBills:function (bills,fixedFlag,_,scMathUtil,decimal) {
        let parentMap = {},datas = [],totalCost = 0;
        let FBFX_b = null,teh_b = null,costNode=null;
        for(let b of bills) {
            parentMap[b.ParentID] ? parentMap[b.ParentID].push(b) : parentMap[b.ParentID] = [b];//有添加，无则生成
            if(b.flags && b.flags.length > 0){
                let f = _.find(b.flags,{"fieldName":"fixed"});
                if(!f) continue;
                if(f.flag == fixedFlag.SUB_ENGINERRING) FBFX_b = b;//过滤出分部分项工程;
                if(f.flag == fixedFlag.CONSTRUCTION_TECH) teh_b = b;//过滤出技术措施项目;
                if(f.flag == fixedFlag.ENGINEERINGCOST) costNode = b;//过滤出工程造价项目;
            }
        }
        if(FBFX_b) getChildren(FBFX_b,parentMap,datas);
        if(teh_b) getChildren(teh_b,parentMap,datas);
        if(costNode) totalCost = gljUtil.getTotalFee(costNode,scMathUtil,decimal);

        for(let td of datas){
            if(parentMap[td.ID]){
                td.economicType = "";
                td.quantityIndexType = "";
                td.quantityIndexUnit = "";
                td.quantityIndexCoe = "";
            }
        }
        return [datas,totalCost];

        function getChildren(d,map,arr) {
            let tem = {
                ID:d.ID,
                ParentID:d.ParentID,
                code:d.code,
                name:d.name,
                unit:d.unit,
                quantity:d.quantity,
                totalFee:gljUtil.getTotalFee(d,scMathUtil,decimal),
                economicType:d.economicType,
                quantityIndexType:d.quantityIndexType,
                quantityIndexUnit:d.quantityIndexUnit,
                quantityIndexCoe:d.quantityIndexCoe,
            };
            arr.push(tem);
            if(map[d.ID]){
                for(let s of map[d.ID]){
                    getChildren(s,map,arr)
                }
            }
        }
    },
    getMainMaterialDatas:function (projectProperty,engineerFeatures,materials,projectGLJData,calcOptions,decimalObj,isRadio,_,scMathUtil) {
        let datas = [];
        let materialGroup = _.groupBy(projectGLJData.gljList,'materialIndexType');
        if(!materials) return datas;
        for(let m of materials){
            let tem = {
                name:m.name,
                unit:m.unit,
                exportName:m.exportName,
                unitPrice:0,
                quantity:0,
                unitIndex:0
            };
            if(materialGroup[m.name]) setMainMaterial(materialGroup[m.name],tem);
            datas.push(tem);
        }

        function setMainMaterial(gljs,data) {
            let quantity = 0 ,unitPrice=0;
            for(let g of gljs){
                if(!g.tenderQuantity || g.tenderQuantity=="") continue;
                let tenderCoe = gljUtil.getTenderPriceCoe(g,projectProperty);
                let marketPrice = gljUtil.getMarketPrice(g,projectGLJData,calcOptions,decimalObj,false,_,scMathUtil,tenderCoe); // gljOprObj.setGLJPrice(tem,g);
                let materialIndexCoe = g.materialIndexCoe?scMathUtil.roundForObj(g.materialIndexCoe,decimalObj.process):0;
                let t_quantity = scMathUtil.roundForObj(g.tenderQuantity * materialIndexCoe,decimalObj.process);
                quantity = scMathUtil.roundForObj(t_quantity + quantity,decimalObj.process);
                let temPrice = scMathUtil.roundForObj(g.tenderQuantity * marketPrice,decimalObj.process);
                unitPrice = scMathUtil.roundForObj(temPrice + unitPrice,decimalObj.process);
            }
            data.quantity = scMathUtil.roundForObj(quantity,2);
            if(data.quantity) data.unitPrice = scMathUtil.roundForObj(unitPrice/data.quantity,2);
            data.unitIndex = gljUtil.calUnitWidthCoe(data.quantity,false,engineerFeatures,_,scMathUtil);
        }

        return datas;
    },
    getQuantityDatas:function (engineerFeatures,mainQuantities,billsList,fixedFlag,_,scMathUtil,decimal) {//主要工程量指标
        let datas = [];
        let [bills,totalFee] = gljUtil.getIndexBills(billsList,fixedFlag,_,scMathUtil,decimal);//bills,fixedFlag,_,scMathUtil
        let billsGroup = _.groupBy(bills,'quantityIndexType');
        if(!mainQuantities) return datas;
        for(let m of mainQuantities){
            let tem = {
                name : m.name,
                quantityIndexUnit:m.unit,
                exportName:m.exportName,
                quantity:0
            };
            console.log(m.coe);
            if(billsGroup[m.name]) setQuantities(billsGroup[m.name],tem);

            datas.push(tem);
        }

        function setQuantities(items,data) {
            let quantity = 0;
            for (let i of items){
                let coe = i.quantityIndexCoe && i.quantityIndexCoe!=""?parseFloat(i.quantityIndexCoe):0;
                i.quantity = scMathUtil.roundForObj(parseFloat(i.quantity)*coe,decimal.process);
                quantity = scMathUtil.roundForObj(quantity +  i.quantity,decimal.process);
            }
            data.quantity = gljUtil.calUnitWidthCoe(quantity,false,engineerFeatures,_,scMathUtil);
             //主要工程量指标另外加了一个系数
            let f = _.find(engineerFeatures,{index:true});
            if(f){
                let quantityCoe = gljUtil.isDef(f.quantityCoe)?f.quantityCoe:1;
                data.quantity = scMathUtil.roundForObj(data.quantity*quantityCoe,3);
            }
           
        }

        return datas;
    },
    getTenderPriceCoe : function(glj,tproperty){
        let tenderCoe = 1;
        let property = tproperty?tproperty:projectObj.project.property;
        if (!glj.is_adjust_price&&property.tenderSetting && isDef(property.tenderSetting.gljPriceTenderCoe) ){
            tenderCoe = parseFloat(property.tenderSetting.gljPriceTenderCoe);
            if (tenderCoe == 0) tenderCoe = 1;
        }
        return tenderCoe;

        function isDef (v) {
            return v !== undefined && v !== null;
        }
    },
    setProperty:function(Obj,updateData) {
        for(let ukey in updateData){
            if(_.isObject(updateData[ukey]) && _.isObject(Obj[ukey])&&!_.isArray(updateData[ukey])){
                setProperty(Obj[ukey],updateData[ukey]);
            }else {
                Obj[ukey] = updateData[ukey];
            }
        }
    },
    sortProjectGLJ:function(jsonData) {
      if (jsonData.length > 0) {
          jsonData = _.sortByAll(jsonData, [function (item) {
            let unit_price = item.unit_price?item.unit_price:item;
            return _.indexOf(gljTypeSeq,unit_price.type);
          }, 'code']);
      }
      return jsonData
    },
    getInfoMarketPrice:function (info,taxType) {
      //1: 一般计税 2: 简易计税
      let fieldArray=['noTaxPrice'];//一般计税 - 不含税价 || 简易计税 - 含税价
      taxType == "1" ? fieldArray.push("taxPrice"):fieldArray.unshift("taxPrice");
      //一个放后面，一个放前面
      let infoPrice = info[fieldArray[0]];
      if(!this.isDef(infoPrice)) infoPrice= info[fieldArray[1]];//信息价只有一个价格（含税价/不含税价），则不分计税方式，套用仅有的价格。
      return parseFloat(infoPrice);
    },
    getPirceInfoDatas: function (projectGLJList, contractor_list, labourCoeDatas, projectProperty, _, scMathUtil) {
        let datas = [];
        let pgljList = projectGLJList;
        let contractorList = contractor_list;
        let calcOptions=projectProperty.calcOptions;
        let decimalObj = projectProperty.decimal; 
        let billsDecimal = decimalObj.bills.totalPrice;
        let gljMap = _.indexBy(pgljList, 'id');
        for (let e of contractorList) {
            let t = {
            ID: e.ID,
            projectID: e.projectID,
            is_related: e.is_related, //关联，1关，0不关
            projectGLJID: e.projectGLJID, //关联工料机ID
            seq: e.seq, //序号
            code: e.code,
            name: e.name,
            specs: e.specs,
            unit: e.unit,
            type: e.type,
            marketPrice: e.market_price,
            quantity: e.quantity,
            remark: e.remark,
            supply: e.supply,
            riskCoe: e.riskCoe,
            is_evaluate: 0,
            standardPrice: e.standardPrice
            };
            let pglj = gljMap[e.projectGLJID];
            /*
            if (e.is_related && pglj) {
                gljOprObj.setGLJPrice(t, pglj);
                t.vender = pglj.vender;
                t.supply = pglj.supply;
                t.is_evaluate = pglj.is_evaluate;
                t.quantity = pglj.quantity;
            }
            /*/
            if (e.is_related && pglj) {
                let tenderCoe = gljUtil.getTenderPriceCoe(pglj,projectProperty);
                let result = gljUtil.getGLJPrice(pglj, {gljList:pgljList}, calcOptions, labourCoeDatas, decimalObj, false, _, scMathUtil, tenderCoe);
                t.marketPrice = result.marketPrice;
                t.tenderPrice = result.tenderPrice;
                t.basePrice =  result.basePrice;
                t.adjustPrice = result.adjustPrice;
                t.marketUnitFee = t.marketPrice;//更新树节点市场单价列的值
                t.taxRate = pglj.unit_price.taxRate;//税率
                  
                t.vender = pglj.vender;
                t.supply = pglj.supply;
                t.quantity = pglj.quantity;
                t.is_evaluate = pglj.is_evaluate;
            }
            //*/
            t.totalPrice = scMathUtil.roundForObj(parseFloat(t.quantity) * parseFloat(t.marketPrice), billsDecimal);
            datas.push(t);
        }
        return _.sortByAll(datas, 'code');
    },
    getPriceCoeDatas: function (projectGLJList, contractor_list, totalFee, projectProperty,_,scMathUtil) {
        let datas = [];
        let pgljList = projectGLJList ;
        let contractorList = contractor_list ;
        let decimalObj = projectProperty.decimal;  
        let calcOptions=projectProperty.calcOptions;
        let billsDecimal =  decimalObj.bills.totalPrice ;
        let gljMap = _.indexBy(pgljList, 'id');
        for (let e of contractorList) {
          let t = {
            ID: e.ID,
            projectID: e.projectID,
            is_related: e.is_related, //关联，1关，0不关
            projectGLJID: e.projectGLJID, //关联工料机ID
            seq: e.seq, //序号
            code: e.code,
            name: e.name,
            specs: e.specs,
            unit: e.unit,
            type: e.type,
            marketPrice: e.market_price,
            quantity: e.quantity,
            remark: e.remark,
            supply: e.supply,
            is_evaluate: 0,
            FO: e.FO,
            FI: e.FI
          };
          let pglj = gljMap[e.projectGLJID];
          if (e.is_related && pglj) {
            let tenderCoe = gljUtil.getTenderPriceCoe(pglj,projectProperty);
            t.marketPrice = gljUtil.getMarketPrice(pglj,{gljList:pgljList},calcOptions,decimalObj,false,_,scMathUtil,tenderCoe);
            t.vender = pglj.vender;
            t.supply = pglj.supply;
            t.quantity = pglj.quantity;
            t.is_evaluate = pglj.is_evaluate;
          }
          t.totalPrice = scMathUtil.roundForObj(parseFloat(t.quantity) * parseFloat(t.marketPrice), billsDecimal);
          if (totalFee !== 0) t.varWeight = scMathUtil.roundForObj(t.totalPrice / totalFee, 2);
          datas.push(t);
        }
        return _.sortByAll(datas, 'code');
    },      
    fixedFlag : {
        // 分部分项工程
        SUB_ENGINERRING: 1,
        // 措施项目
        MEASURE: 2,
        // 施工技术措施项目
        CONSTRUCTION_TECH: 3
    },
    gljType : {
        LABOUR: 1,                                  // 人工
        // ==============材料类型 ↓=================
        GENERAL_MATERIAL: 201,                      // 普通材料
        CONCRETE: 202,                              // 混凝土
        MORTAR: 203,                                // 砂浆
        MIX_RATIO: 204,                             // 配合比
        COMMERCIAL_CONCRETE: 205,                   // 商品混凝土
        COMMERCIAL_MORTAR: 206,                     // 商品砂浆
        OTHER_MATERIAL: 207,                        // 其它材料
        // ==============材料类型 ↑=================
        // ==============机械类型 ↓=================
        GENERAL_MACHINE: 301,                       // 机械台班
        MACHINE_COMPOSITION: 302,                   // 机械组成物
        MACHINE_LABOUR: 303,                        // 机上人工
        INSTRUMENT: 304,                            // 仪器仪表
        FUEL_POWER_FEE:305,                         // 燃料动力费
        DEPRECIATION_FEE:306,                       // 折旧费
        INSPECTION_FEE:307,                         // 检修费
        MAINTENANCE:308,                            // 维护费
        DISMANTLING_FREIGHT_FEE:309,                // 安拆费及场外运费
        VERIFICATION_FEE:310,                       // 校验费
        OTHER_FEE:311,                              // 其他费用
        OTHER_MACHINE_USED:312,                     // 其他施工机具使用费
        // ==============机械类型 ↑=================
        MAIN_MATERIAL: 4,                           // 主材
        EQUIPMENT: 5,                               // 设备
        MANAGEMENT_FEE: 6,                          // 企业管理费
        PROFIT: 7,                                  // 利润
        GENERAL_RISK_FEE: 8                         // 一般风险费
    },
    extraType:[6,7,8],//一些其它的工料机类型
    notEditType : [202,203,204,301,304,4],
    gljKeyArray : ['code','name','specs','unit','type'],
    materialKeyArray:['code','name','specs','unit'],
    rationType : {
        ration: 1,
        volumePrice: 2,
        gljRation: 3,
        install:4
    },
    hasCompMaterial:[202, 203, 204],//有组成物的材料
    hasCompMachine:[301],//有组成物的机械
    machineComposition:[302,303]//可以做为机械组成物的类型
}

if(typeof module !== 'undefined'){
  module.exports = gljUtil;
}