global class ConsumptionRateWebService {
    

    @AuraEnabled
    WebService static String ToConsumptionRate(String mceId){
        Decimal Totalnumerator = 0;
        Date CreateTime;
        Integer AssCount = 0;
        Decimal EstimateAssetCnt;
        Decimal Contract_Range;
        Decimal Consumption_rate_Forecast_fenzi;
        Boolean CategoryOfNumberAsset; // >=100为true ，<100为false
        List<Maintenance_Contract_Asset_Estimate__c> mcaeList = [SELECT Id,Asset__c,Asset__r.id,Asset__r.CurrentContract_F__c,Asset__r.CurrentContract_F__r.Contract_Range__c,
                                                                    Asset__r.InstallDate,Asset__r.Asset_Year_Txt__c,
                                                                    Asset__r.CurrentContract_F__r.Contract_Start_Date__c, Asset__r.CurrentContract_F__r.Contract_End_Date__c,
                                                                    Asset__r.LastSFDCArankRepairReturn_day__c,Maintenance_Contract_Estimate__r.Contract_Range__c 
                                                                    ,Maintenance_Contract_Estimate__r.CreatedDate ,Asset__r.Category4__c,
                                                                    Asset__r.product2Id,Asset__r.product2.Asset_Model_No__c,Asset__r.product2.Category4__c,
                                                                    Maintenance_Contract_Estimate__r.CategoryOfNumberAsset__c,
                                                                    Maintenance_Contract_Estimate__r.Consumption_rate_Forecast_fenzi__c,
                                                                    Maintenance_Contract_Estimate__r.Estimate_Asset_Cnt__c,Asset__r.AccountId,Asset__r.Hospital__c,
                                                                    Product_Manual__r.id,Product_Manual__r.Asset_Model_No__c,Product_Manual__r.Category4__c  
                                                                FROM Maintenance_Contract_Asset_Estimate__c 
                                                                WHERE Maintenance_Contract_Estimate__c = :mceId];
        Double TotalPriceInMc = 0;
        Decimal TotalPrice = 0;
        Map<Id,Asset> updateAss = new Map<Id,Asset>();
        Map<Id,product2> updatePro = new Map<Id,Product2>();
        List<Maintenance_Contract_Asset_Estimate__c> updateMCAELi = new List<Maintenance_Contract_Asset_Estimate__c>();
        List<String> hasNoMcAssets = new List<String>();
        List<String> hasMcAssets = new List<String>();
        List<String> checkHasmcAss = new List<String>();
        Set<String> ProAssetModelNo = new Set<String>();
        Set<String> ProCategory4 = new Set<String>();
        Map<Id, Id> assToMcMap = new Map<Id, Id>();
        Map<Id, Double> assToDay = new Map<Id, Double>();
        Map<Id, Double> assTofeni = new Map<Id, Double>();
        Map<Id, Double> assTotalPriceInMcMap = new Map<Id, Double>();
        Map<Id, Maintenance_Contract__c> mcInfo = new Map<Id,Maintenance_Contract__c>();
        Map<Id, Asset> assInfo = new Map<Id,Asset>();
        Map<Id, Product2> proInfo = new Map<Id,Product2>();
        for (Maintenance_Contract_Asset_Estimate__c mcae: mcaeList) {
            if (CreateTime==null) {
                CreateTime = mcae.Maintenance_Contract_Estimate__r.CreatedDate.date();
            }
            if (EstimateAssetCnt==null) {
                EstimateAssetCnt = mcae.Maintenance_Contract_Estimate__r.Estimate_Asset_Cnt__c;
            }
            if (Contract_Range==null) {
                Contract_Range = mcae.Maintenance_Contract_Estimate__r.Contract_Range__c;
            }
            // if (Consumption_rate_Forecast_fenzi==null) {
            //     Consumption_rate_Forecast_fenzi = mcae.Maintenance_Contract_Estimate__r.Consumption_rate_Forecast_fenzi__c;
            // }
            if (CategoryOfNumberAsset==null) {
                if (mcae.Maintenance_Contract_Estimate__r.CategoryOfNumberAsset__c == '按第四分类') {
                    CategoryOfNumberAsset = false;
                }
                if (mcae.Maintenance_Contract_Estimate__r.CategoryOfNumberAsset__c == '按产品型号') {
                    CategoryOfNumberAsset = true;
                }
            }
            if (mcae.Asset__r.CurrentContract_F__c!=null) {
                assToMcMap.put(mcae.Asset__r.id,mcae.Asset__r.CurrentContract_F__c);
                assTotalPriceInMcMap.put(mcae.Asset__r.id,TotalPriceInMc);
                hasMcAssets.add(mcae.Asset__r.id);
                AssCount++;
            }else{
                if (mcae.Asset__r.id !=null) {
                    hasNoMcAssets.add(mcae.Asset__r.id);
                }
                if (mcae.Product_Manual__r.id !=null) {
                    hasNoMcAssets.add(mcae.Product_Manual__r.id);
                    ProAssetModelNo.add(mcae.Product_Manual__r.Asset_Model_No__c);
                    ProCategory4.add(mcae.Product_Manual__r.Category4__c);
                }
            }
            // 维修合同信息
            if (!mcInfo.containsKey(mcae.Asset__r.CurrentContract_F__c)) {
                Maintenance_Contract__c mc = new Maintenance_Contract__c();
                mc.id = mcae.Asset__r.CurrentContract_F__c;
                mc.Contract_Start_Date__c = mcae.Asset__r.CurrentContract_F__r.Contract_Start_Date__c;
                mc.Contract_End_Date__c = mcae.Asset__r.CurrentContract_F__r.Contract_End_Date__c;
                mc.Contract_Range__c = mcae.Asset__r.CurrentContract_F__r.Contract_Range__c;
                mcInfo.put(mc.id,mc);
            }
            // 保有设备信息
            if (!assInfo.containsKey(mcae.Asset__r.id)) {
                Asset ass = new Asset();
                Product2  Pro2 =  new Product2();
                pro2.id = mcae.Asset__r.product2Id;
                pro2.Asset_Model_No__c = mcae.Asset__r.product2.Asset_Model_No__c;
                pro2.Category4__c = mcae.Asset__r.product2.Category4__c;
                ass.id = mcae.Asset__r.id;
                ass.InstallDate =  mcae.Asset__r.InstallDate;
                ass.Asset_Year_Txt__c = mcae.Asset__r.Asset_Year_Txt__c;
                ass.LastSFDCArankRepairReturn_day__c = mcae.Asset__r.LastSFDCArankRepairReturn_day__c;
                ass.product2 = pro2;
                ass.AccountId = mcae.Asset__r.AccountId;
                ass.Hospital__c = mcae.Asset__r.Hospital__c;
                assInfo.put(ass.id,ass);
            }
             // 产品信息
            if (!proInfo.containsKey(mcae.Product_Manual__r.id)) {
                Product2  pro2 =  new Product2();
                pro2.id = mcae.Product_Manual__r.id;
                pro2.Asset_Model_No__c = mcae.Product_Manual__r.Asset_Model_No__c;
                pro2.Category4__c = mcae.Product_Manual__r.Category4__c;
                proInfo.put(pro2.id,pro2);
            }
        }
        // List<AggregateResult> assmodelList = [select id,MonthSizeAssetModelNo__c,Three_Years_HasMcAssetModelNo__c from asset where product2.Asset_Model_No__c in :ProAssetModelNo  group by product2.Asset_Model_No__c];
        if (assToMcMap.keySet()!=null) {
          List<Repair__c> reps = [SELECT id,Failure_Occurrence_Date__c,Repair_List_Price_formula__c,Maintenance_Contract__c,Delivered_Product__c FROM Repair__c 
                                    WHERE Maintenance_Contract__c in :assToMcMap.values() and Delivered_Product__c in :assTotalPriceInMcMap.keySet() and Status2__c !='00.删除' and Status2__c !='00.取消'  order by Delivered_Product__c,Failure_Occurrence_Date__c desc];
            assTotalPriceInMcMap.clear();  
            Set<Id> assetIdsWithRelatedRepairs = new Set<Id>();
                         
            for (Repair__c rep :reps) {
                 
                if (rep.Maintenance_Contract__c == assToMcMap.get(rep.Delivered_Product__c)) {
                    assetIdsWithRelatedRepairs.add(rep.Delivered_Product__c);
                    if (rep.Delivered_Product__c=='02i10000003F6MUAA0') {
                        system.debug('修理=='+rep.id);
                        system.debug('设备=='+rep.Delivered_Product__c);
                    }
                    
                    Boolean IsCanJoin = true;
                    Date AssetDate;
                    Id assId  = rep.Delivered_Product__c;
                    Maintenance_Contract__c mc = mcInfo.get(rep.Maintenance_Contract__c);
                    Asset ass = assInfo.get(assId);
                    if (ass !=null) {
                        if (ass.InstallDate!=null) {
                            AssetDate = ass.InstallDate;
                        }else{
                            if (ass.Asset_Year_Txt__c!=null) {
                                AssetDate = Date.valueOf(ass.Asset_Year_Txt__c);
                            }
                        }
                        if (AssetDate!=null) {
                            //如果参保设备发生的合同修理是在安装日（有安装日取安装日，无安装日取【设备日期】）1年以内
                            if (rep.Failure_Occurrence_Date__c>=AssetDate && rep.Failure_Occurrence_Date__c<=AssetDate.addyears(1)) {
                                IsCanJoin = false;
                                assTotalPriceInMcMap.remove(assId);
                            }
                            //如果合同修理正好只有1个小于等于一年期的合同，且合同修理和安装日期之后的一年和合同期间重合了半年以上，【有效年度的合同修理合计】的情况等同于【否】
                            if (mc.Contract_Range__c !=null && mc.Contract_Range__c<=12) {
                                if (areIntervalsOverlapHalfYear(mc.Contract_Start_Date__c,mc.Contract_End_Date__c,AssetDate.addyears(1),rep.Failure_Occurrence_Date__c)) {
                                    if(!hasNoMcAssets.contains(assId)){
                                        hasNoMcAssets.add(assId);
                                    }
                                    IsCanJoin = false;
                                    assTotalPriceInMcMap.remove(assId);
                                    system.debug('【有效年度的合同修理合计】的情况等同于【否】'+assId);
                                    system.debug('【有效年度的合同修理合计】的情况等同于【否】的型号'+ass.product2.Asset_Model_No__c);
                                }
                            }  
                        }
                        if (rep.Delivered_Product__c=='02i10000003F6MUAA0') {
                            system.debug('【IsCanJoin】'+IsCanJoin);
                        }
                        //【有效年度的合同修理合计】计算
                        if (IsCanJoin) {
                            if (assTotalPriceInMcMap.containsKey(assId)) {
                                Double price1 = assTotalPriceInMcMap.get(assId);
                                price1 += rep.Repair_List_Price_formula__c;
                                if (assId=='02i10000003F6MUAA0') {
                                    system.debug('【IsCanJoin=true进入集合】'+assId);
                                }
                                
                                assTotalPriceInMcMap.put(assId,price1);  
                            }else{
                                if (assId=='02i10000003F6MUAA0') {
                                    system.debug('修理添加'+rep.Repair_List_Price_formula__c);
                                }
                                assTotalPriceInMcMap.put(assId,rep.Repair_List_Price_formula__c);
                            }
                            // 经历天数

                                Double ElapsedDays;
                                if (CreateTime !=null) {
                                    if (mc.Contract_End_Date__c>CreateTime) {
                                        ElapsedDays = (Double)(mc.Contract_Start_Date__c.daysBetween(CreateTime));
                                    }else{
                                        ElapsedDays = (Double)(mc.Contract_Start_Date__c.daysBetween(mc.Contract_End_Date__c));
                                    }
                                }else{
                                    if (mc.Contract_End_Date__c>Date.today()) {
                                        ElapsedDays = (Double)(mc.Contract_Start_Date__c.daysBetween(Date.today()));
                                    }else{
                                        ElapsedDays = (Double)(mc.Contract_Start_Date__c.daysBetween(mc.Contract_End_Date__c));
                                    }
                                }
                                String mcassStr = assId+':'+mc.Id;
                                if (!assToDay.containsKey(assId)) {
                                    assToDay.put(assId,ElapsedDays);
                                    checkHasmcAss.add(mcassStr);
                                }else{
                                    if (!checkHasmcAss.contains(mcassStr)) {
                                        Double days = assToDay.get(assId);
                                        days += ElapsedDays;
                                        assToDay.put(assId,days);
                                        checkHasmcAss.add(mcassStr);
                                    }  
                                }
                        }                   
                    }
                }
            }
            for (String assetid : hasMcAssets) {
                if (!assetIdsWithRelatedRepairs.contains(assetid)) {
                    // if (assetid=='02i10000003F6MUAA0') {
                    //     system.debug('assetid加入hasNoMcAssets=='+assetid);
                    // }
                    hasNoMcAssets.add(assetid);
                }
            }
            for (Id assid:assTotalPriceInMcMap.keySet()) {
              // 消费率单个分子
              Decimal  numerator=0;
              Id mcId = assToMcMap.get(assid);
              Maintenance_Contract__c mc = mcInfo.get(mcId);
              // 经历天数
              if (Contract_Range!=null) {
                  Asset ass  = new Asset();
                  ass.id = assid;
                  Decimal price = assTotalPriceInMcMap.get(assid);
                  Double ElapsedDay;
                  if (assToDay.containsKey(assid)) {
                     ass.ExperienceDays__c = assToDay.get(assid); 
                     ElapsedDay  = assToDay.get(assid);
                  }
                  if (ElapsedDay!=null && ElapsedDay!=0) {
                      numerator = (price/ElapsedDay*30*Contract_Range);
                  }
                  Totalnumerator += numerator;
                  
                  
                  ass.TotalPriceInMc__c = price;
                  // if (assid=='02i10000003F6MUAA0') {
                  //       system.debug('设备经历天数='+ElapsedDay);
                  //         system.debug('有效年度的修理合计='+price);
                  //         system.debug('合同月数='+Contract_Range);
                  //         system.debug('情况等同于【是】加入'+assid);
                  //         system.debug('预测消费率分子='+numerator);
                  //   }
                  
                  if (updateAss.get(ass.id) == null) {
                      updateAss.put(ass.id,ass);
                  }
                  
                  assTofeni.put(ass.id,numerator);
              }
            }
        }
            system.debug('参保设备总数=='+EstimateAssetCnt);
        if(CategoryOfNumberAsset == null){
            if (AssCount<100) {
                CategoryOfNumberAsset = false;
            }
            if (AssCount>=100) {
                CategoryOfNumberAsset = true;
            }
        }
        TotalPrice += Totalnumerator;
        List<String> MDMOrCategory4List = new List<String>();
        Map<Id,Id> AccIdMap = new Map<Id,Id>();
        Map<Id,Boolean> IsIn3YearMap = new Map<Id,Boolean>();
        Map<String,Double> Category4Map = new Map<String,Double>();
        Map<String,Double> Category4MapNum = new Map<String,Double>();
        Map<String,Double> MDMMap = new Map<String,Double>();
        Map<String,Double> MDMMapNum = new Map<String,Double>();
        for (Id assid : hasNoMcAssets) {
             Asset ass = assInfo.get(assid);
             if (ass.Hospital__c !=null) {
                 AccIdMap.put(ass.id,ass.Hospital__c);
             }
        }
        // ComputeLTYRepair(hasNoMcAssets,mceId,MDMOrCategory4List,CategoryOfNumberAsset);

        List<Maintenance_Contract_Asset_Estimate__c> mcaeList3  = [SELECT id,Asset__r.product2.Category4__c,Asset__r.product2.Asset_Model_No__c
                                                                    ,Asset__r.Three_Years_HasMcAssetModelNo__c
                                                                    ,Asset__r.Three_Years_HasMcCategory4__c
                                                                    ,Asset__r.MonthSizeAssetModelNo__c
                                                                    ,Asset__r.MonthSizeCategory4__c  
                                                                    FROM Maintenance_Contract_Asset_Estimate__c 
                                                                    WHERE Maintenance_Contract_Estimate__c = :mceId ];
        List<AggregateResult> mcList = [SELECT min(Contract_Start_Date__c) minStartDate ,Hospital__c FROM Maintenance_Contract__c 
                                                                     WHERE Hospital__c IN :AccIdMap.values() group by Hospital__c]; 
        for (AggregateResult Rpc : mcList) {
            id hpid = String.valueOf(Rpc.get('Hospital__c'));
            Date contractStartDate = (Date)Rpc.get('minStartDate');
            Date today = Date.today(); 
            //所在医院在我司累计签约达到了3年以上
            if (today.addyears(-3)>contractStartDate && hpid!=null) {
                IsIn3YearMap.put(hpid,true);
            }else{
                IsIn3YearMap.put(hpid,false);
            }
        }         
         system.debug('是否按产品略称=='+CategoryOfNumberAsset);                                          
        //按第四分类计算
        if (!CategoryOfNumberAsset) {
            for (Maintenance_Contract_Asset_Estimate__c mcae :mcaeList3) {
                  // Double mcNumAll;
                  if (!Category4Map.containsKey(mcae.Asset__r.product2.Category4__c)) {
                        Category4Map.put(mcae.Asset__r.product2.Category4__c,mcae.Asset__r.Three_Years_HasMcCategory4__c);
                  }   
                  if (!Category4MapNum.containsKey(mcae.Asset__r.product2.Category4__c)) {
                        Category4MapNum.put(mcae.Asset__r.product2.Category4__c,mcae.Asset__r.MonthSizeCategory4__c  );
                  }                                                                        
            } 
        }  
        //按产品略称  产品型号（MDM）
        if (CategoryOfNumberAsset) {
            for (Maintenance_Contract_Asset_Estimate__c mcae :mcaeList3) {
                  // Double mcNumAll;
                  if (!MDMMap.containsKey(mcae.Asset__r.product2.Asset_Model_No__c)) {
                        MDMMap.put(mcae.Asset__r.product2.Asset_Model_No__c,mcae.Asset__r.Three_Years_HasMcAssetModelNo__c);
                  }
                  if (!MDMMapNum.containsKey(mcae.Asset__r.product2.Asset_Model_No__c)) {
                        MDMMapNum.put(mcae.Asset__r.product2.Asset_Model_No__c,mcae.Asset__r.MonthSizeAssetModelNo__c);
                  }                                                                                        
            }
        }
        // system.debug('按第四分类金额=='+Category4Map);
        // system.debug('按第四分类月份=='+Category4MapNum);
        // for(String sn :MDMMap.keySet()){
        //     system.debug('按产品略称='+sn+'***金额为=='+MDMMap.get(sn));
        // }
        // for(String sn :MDMMapNum.keySet()){
        //     system.debug('按产品略称='+sn+'***换算为12个月件数为=='+MDMMapNum.get(sn));
        // }
        Decimal hasNoMcAssetsPriceAll=0;                                                                                                                
        for (Id assid : hasNoMcAssets) {
            Asset ass = assInfo.get(assid);
            // Product2 pro = proInfo.get(assid);
            // if (assid=='02i10000003F6MUAA0') {
            // system.debug('计算开始=='+assid);

            // }
             Decimal AverageContractRepair=0;
             Decimal hasNoMcAssetsPrice=0;
             Boolean toBreak = false;
             Boolean toBreak2 = false;
            if (ass !=null) {
                //申请合同的设备参保件数大于100件以上，且所在医院在我司累计签约达到了3年以上，计算出按第四分类的每个分类平均修理金额，
                    if (EstimateAssetCnt>100) {
                         Id accId = AccIdMap.get(assid);
                         if (IsIn3YearMap.containskey(accId)) {
                             Boolean IsIn3Year = IsIn3YearMap.get(accId);
                             if (IsIn3Year) {
                                if (Category4Map.get(ass.product2.Category4__c) !=null && Category4MapNum.get(ass.product2.Category4__c) !=null) {
                                    AverageContractRepair = Category4Map.get(ass.product2.Category4__c)/Category4MapNum.get(ass.product2.Category4__c);
                                    system.debug('按签约达到了3年以上计算=='+ass.product2.Category4__c);
                                }
                             }
                         }
                         toBreak = true;
                     }

                 if (!toBreak) {
                  //参保设备的上次大中修理日期是在报价制作日之前1年以内，用0赋值，如果设备是安装在1年之内，用0赋值。
                         if ((ass.LastSFDCArankRepairReturn_day__c!=null&&CreateTime.addyears(-1)<ass.LastSFDCArankRepairReturn_day__c&&CreateTime>ass.LastSFDCArankRepairReturn_day__c)
                            ||(ass.InstallDate!=null&&CreateTime.addyears(-1)<ass.InstallDate&&CreateTime>ass.InstallDate)) {
                             AverageContractRepair = 0;
                            toBreak2 = true;
                         system.debug('参保设备的上次大中修理日期是在报价制作日之前1年以内计算=='+ass.product2.Asset_Model_No__c+':'+ass.id);
                         }
                     if (!toBreak2) {
                         //如果有合同的设备总数小于100，则按第四分类计算，取对应型号的过去3年期间有合同的的全国合同修理金额合计/对应型号的设备总数换算为12个月的件数
                         if (!CategoryOfNumberAsset) {
                            if (Category4Map.get(ass.product2.Category4__c) !=null && Category4MapNum.get(ass.product2.Category4__c) !=null) {
                                AverageContractRepair = Category4Map.get(ass.product2.Category4__c)/Category4MapNum.get(ass.product2.Category4__c);
                            }
                            if (assid=='02i10000003F6MUAA0') {
                                system.debug('第四分类分子=='+Category4Map.get(ass.product2.Category4__c));
                                system.debug('第四分类分母=='+Category4MapNum.get(ass.product2.Category4__c));
                                system.debug('按第四分类计算=='+ass.product2.Category4__c);
                            }
                            
                         }
                         //如果有合同的设备总数大于等于100，则按产品略称，取对应型号的过去3年期间的有合同的的全国合同修理金额合计/对应型号的设备总数换算为12个月的件数
                         if (CategoryOfNumberAsset) {
                            if (MDMMap.get(ass.product2.Asset_Model_No__c) !=null && MDMMapNum.get(ass.product2.Asset_Model_No__c) !=null) {
                                AverageContractRepair = MDMMap.get(ass.product2.Asset_Model_No__c)/MDMMapNum.get(ass.product2.Asset_Model_No__c);
                            }
                            if (assid=='02i10000003F6MUAA0') {
                                system.debug('产品略称分子=='+MDMMap.get(ass.product2.Asset_Model_No__c));
                                system.debug('产品略称分母=='+MDMMapNum.get(ass.product2.Asset_Model_No__c));
                                system.debug('按产品略称计算=='+ass.product2.Asset_Model_No__c);
                            }
                            
                         }
                     }
                 }
                // system.debug('合同月数=='+Contract_Range);
                 if (Contract_Range!=0 && Contract_Range!=null) {
                     hasNoMcAssetsPrice = AverageContractRepair*Contract_Range;
                     if (!assTofeni.containsKey(assid)) {
                         assTofeni.put(assid,hasNoMcAssetsPrice);
                     }
                     
                     if (assid=='02i10000003F6MUAA0') {
                         system.debug('设备进入assTofeni==>'+assid);
                     }
                    
                 }else{
                    system.debug('此设备的没有进assTofeni==>'+assid);
                    system.debug('此设备的==Contract_Range>'+Contract_Range);
                 }
                 if (assid=='02i10000003F6MUAA0') {
                     system.debug('此设备的hasNoMcAssetsPrice=='+hasNoMcAssetsPrice);
                 }
                 
                 hasNoMcAssetsPriceAll += hasNoMcAssetsPrice;
                 Double MonthSize=0;
                 Double MonthSize2=0;
                 Asset ass1 = new Asset();
                 ass1.id = assid;
                 // if (CategoryOfNumberAsset && MDMMap.get(ass.product2.Asset_Model_No__c) !=null && MDMMapNum.get(ass.product2.Asset_Model_No__c) !=null) {
                 //    ass1.AverageContractRepair__c = MDMMap.get(ass.product2.Asset_Model_No__c)/MDMMapNum.get(ass.product2.Asset_Model_No__c);
                 // }
                 // if (!CategoryOfNumberAsset && Category4Map.get(ass.product2.Category4__c) !=null && Category4MapNum.get(ass.product2.Category4__c) !=null) {
                    // ass1.AverageContractRepair__c = Category4Map.get(ass.product2.Category4__c)/Category4MapNum.get(ass.product2.Category4__c);
                 // }
                 ass1.AverageContractRepair__c = AverageContractRepair;
                 // if (!CategoryOfNumberAsset && Category4MapNum.get(ass.product2.Category4__c)!=null) {
                 //     MonthSize = Category4MapNum.get(ass.product2.Category4__c);
                 // }
                 // if (CategoryOfNumberAsset && MDMMapNum.get(ass.product2.Asset_Model_No__c)!=null) {
                 //     MonthSize2 = MDMMapNum.get(ass.product2.Asset_Model_No__c);
                 // }
                 // if (MonthSize != 0 ) {
                 //   ass1.MonthSizeCategory4__c = MonthSize;
                 // }
                 // if (MonthSize2 != 0 ) {
                 //   ass1.MonthSizeAssetModelNo__c = MonthSize2;
                 // }
                 // system.debug('情况等同于【否】加入'+assid);
                if (updateAss.get(ass1.id) == null) {
                    updateAss.put(ass1.id,ass1);
                }
            }
            // if (pro !=null) {

            //      //如果有合同的设备总数小于100，则按第四分类计算，取对应型号的过去3年期间有合同的的全国合同修理金额合计/对应型号的设备总数换算为12个月的件数
            //      if (!CategoryOfNumberAsset) {
            //         if (Category4Map.get(pro.Category4__c) !=null && Category4MapNum.get(pro.Category4__c) !=null) {
            //             AverageContractRepair = Category4Map.get(pro.Category4__c)/Category4MapNum.get(pro.Category4__c);
            //         }
            //         if (pro.id=='02i10000003F6MUAA0') {
            //             system.debug('第四分类分子=='+Category4Map.get(pro.Category4__c));
            //             system.debug('第四分类分母=='+Category4MapNum.get(pro.Category4__c));
            //             system.debug('按第四分类计算=='+pro.Category4__c);
            //         }
                    
            //      }
            //      //如果有合同的设备总数大于等于100，则按产品略称，取对应型号的过去3年期间的有合同的的全国合同修理金额合计/对应型号的设备总数换算为12个月的件数
            //      if (CategoryOfNumberAsset) {
            //         if (MDMMap.get(pro.Asset_Model_No__c) !=null && MDMMapNum.get(pro.Asset_Model_No__c) !=null) {
            //             AverageContractRepair = MDMMap.get(pro.Asset_Model_No__c)/MDMMapNum.get(pro.Asset_Model_No__c);
            //         }
            //         if (pro.id=='02i10000003F6MUAA0') {
            //             system.debug('产品略称分子=='+MDMMap.get(pro.Asset_Model_No__c));
            //             system.debug('产品略称分母=='+MDMMapNum.get(pro.Asset_Model_No__c));
            //             system.debug('按产品略称计算=='+pro.Asset_Model_No__c);
            //         }
                    
            //      }
            //     // system.debug('合同月数=='+Contract_Range);
            //      if (Contract_Range!=0 && Contract_Range!=null) {
            //          hasNoMcAssetsPrice = AverageContractRepair/12*Contract_Range;
            //          assTofeni.put(pro.id,hasNoMcAssetsPrice);
            //          if (pro.id=='02i10000003F6MUAA0') {
            //              system.debug('产品进入assTofeni==>'+pro.id);
            //          }
                    
            //      }
            //      if (pro.id=='02i10000003F6MUAA0') {
            //          system.debug('此产品的hasNoMcAssetsPrice=='+hasNoMcAssetsPrice);
            //      }
                 
            //      hasNoMcAssetsPriceAll += hasNoMcAssetsPrice;
            //      product2 pro1 = new product2();
            //      pro1.id = pro.id;
            //      pro1.AverageContractRepair__c = AverageContractRepair;
            //     if (updatePro.get(pro1.id) == null) {
            //         updatePro.put(pro1.id,pro1);
            //     }
            // }
             
        }

        TotalPrice += hasNoMcAssetsPriceAll;
        Maintenance_Contract_Estimate__c mce = new Maintenance_Contract_Estimate__c();
        mce.id =  mceId;
        system.debug('以往报价分子为：'+Consumption_rate_Forecast_fenzi);
        // if (Consumption_rate_Forecast_fenzi!=null) {
        //      mce.Consumption_rate_Forecast_fenzi__c = TotalPrice+Consumption_rate_Forecast_fenzi;
        // }else{
        //     mce.Consumption_rate_Forecast_fenzi__c = TotalPrice;
        // }
        if (CategoryOfNumberAsset) {
           mce.CategoryOfNumberAsset__c  = '按产品型号';      
        }
        if (!CategoryOfNumberAsset) {
           mce.CategoryOfNumberAsset__c  = '按第4分类';   
        }
        List<Maintenance_Contract_Asset_Estimate__c> McaeLi = new List<Maintenance_Contract_Asset_Estimate__c>();
        for (Maintenance_Contract_Asset_Estimate__c mcae: mcaeList) {
            if (mcae.Asset__r.id=='02i10000003F6MUAA0') {
                system.debug('是否存在=='+assTofeni.containsKey(mcae.Asset__r.id)+mcae.Asset__r.id);
            }
                
            if (assTofeni.containsKey(mcae.Asset__r.id)) {
                Maintenance_Contract_Asset_Estimate__c mcae1= new Maintenance_Contract_Asset_Estimate__c();
                mcae1.id = mcae.id;
                mcae1.Consumption_rate_Forecast_fenzi__c = assTofeni.get(mcae.Asset__r.id);
                if (!McaeLi.contains(mcae1)) {
                    McaeLi.add(mcae1);
                }
            }
            // if (assTofeni.containsKey(mcae.Product_Manual__r.id)) {
            //     Maintenance_Contract_Asset_Estimate__c mcae1= new Maintenance_Contract_Asset_Estimate__c();
            //     mcae1.id = mcae.id;
            //     mcae1.Consumption_rate_Forecast_fenzi__c = assTofeni.get(mcae.Product_Manual__r.id);
            //     if (!McaeLi.contains(mcae1)) {
            //         McaeLi.add(mcae1);
            //     }
            // }
        }
        system.debug('更新报价为=='+mce);
        try{
            update mce;
            if (updateAss.size()>0) {
                // system.debug('updateAss:::::' + updateAss);
                update updateAss.values();
            }
            // if (updatePro.size()>0) {
                // system.debug('updateAss:::::' + updateAss);
                // update updatePro.values();
            // }
            if (McaeLi.size()>0) {
                system.debug('McaeLi:::::' + McaeLi);
                // update McaeLi;
            }
            return '计算完成';
        }catch(Exception e){
            if (e.getMessage().contains(',') && e.getMessage().contains('[')){
                String eMessage = e.getMessage();
                Integer left = eMessage .indexof(',') + 1;
                Integer right = eMessage.lastIndexof('[')-2;
                return eMessage.substring(left,right);
            }else {
                return e.getMessage();
            }
        }
        
        
    }

    public ConsumptionRateWebService() {}
    
   // 计算是否重合半年
    public static Boolean areIntervalsOverlapHalfYear(Date timeA, Date timeB, Date timeC, Date timeD) {
        // 将日期转换为日期时间，时间部分设为最早或最晚的时间
        DateTime dateTimeA = DateTime.newInstance(timeA, Time.newInstance(0, 0, 0, 0));
        DateTime dateTimeB = DateTime.newInstance(timeB, Time.newInstance(0, 0, 0, 0));
        DateTime dateTimeC = DateTime.newInstance(timeC, Time.newInstance(0, 0, 0, 0));
        DateTime dateTimeD = DateTime.newInstance(timeD, Time.newInstance(0, 0, 0, 0));

        // 确保时间区间按照从小到大的顺序排列
        if (dateTimeA.getTime() > dateTimeB.getTime()) {
            DateTime temp = dateTimeA;
            dateTimeA = dateTimeB;
            dateTimeB = temp;
        }
        if (dateTimeC.getTime() > dateTimeD.getTime()) {
            DateTime temp = dateTimeC;
            dateTimeC = dateTimeD;
            dateTimeD = temp;
        }

        // 计算时间区间重叠部分的起始时间和结束时间
        DateTime overlapStart = dateTimeA.getTime() > dateTimeC.getTime() ? dateTimeA : dateTimeC;
        DateTime overlapEnd = dateTimeB.getTime() < dateTimeD.getTime() ? dateTimeB : dateTimeD;

        // 计算时间区间重叠部分的月份数
        Integer months = monthDifference(overlapStart, overlapEnd);

        // 判断重叠的月份数是否超过半年
        return months >= 6;
    }

    private static Integer monthDifference(Datetime startDate, Datetime endDate) {
        Integer startYear = startDate.year();
        Integer startMonth = startDate.month();
        Integer endYear = endDate.year();
        Integer endMonth = endDate.month();

        return (endYear - startYear) * 12 + (endMonth - startMonth);
    }


  
}