// LHJ 20190712 HWAG-BDH9V5 Start
//global class RollupToMaintenanceContractBatch implements Database.Batchable<AggregateResult> {
    global class RollupToMaintenanceContractBatch implements Database.Batchable<SObject> , Database.Stateful {
        // LHJ 20190712 HWAG-BDH9V5 End
                // LHJ 20190712 HWAG-BDH9V5 Start
                global Integer totalCount = 0; // 总件数
                global Integer failedCount = 0;
                global Id mcpId;
                global List<String> emailMessages = new List<String>();
                public List<Id> ConId;
        
                global RollupToMaintenanceContractBatch(List<Id> conID) {
                     this.ConId = conID;
                }
                // LHJ 20190712 HWAG-BDH9V5 End
        
                /**
                 * コンスタント
                 */
                global RollupToMaintenanceContractBatch() {
                }
                
                /**
                 * startには、queryを実行、维修合同を検索
                 */
                //global Iterable<AggregateResult> start(Database.batchableContext BC){
                global Database.QueryLocator start(Database.batchableContext BC){
                    //return new AggregateResultIterable();
                    /* CHAN-B7J5EK 2018/12/18 按照维修合同划分进行检索 start
                    return Database.getQueryLocator(
                        [select Id from User where Id = :UserInfo.getUserId()]
                    );
                        CHAN-B7J5EK 2018/12/18 按照维修合同划分进行检索 end
                    */
                    // LHJ 20190712 HWAG-BDH9V5 Start
                    //return Database.getQueryLocator(
                    //    [select Id from Maintenance_Contract__c]
                    //);
                    // 报价合并 20230524 start
                    if(ConId != null && ConId.size() > 0) {
                        return Database.getQueryLocator([select Id,PackageFlag__c,Limit_Price_Amount__c from Maintenance_Contract__c where Id in :ConId]);
                    } else {
                        // 20221117 ljh DB202211258553 start
                        // return Database.getQueryLocator([select Id from Maintenance_Contract__c]);
                        return Database.getQueryLocator([select Id,PackageFlag__c,Limit_Price_Amount__c from Maintenance_Contract__c where Status__c = '契約' OR (Status__c = '契約満了' and Contract_End_Date__c >= :Date.today().addMonths(-6))]);
                        // 20221117 ljh DB202211258553 end
                    }
                    // 报价合并 20230524 end
                    
                    // LHJ 20190712 HWAG-BDH9V5 End
        
                    // if(ConId != null && ConId.size() > 0) {
                    //     return Database.getQueryLocator()
                    // }
                }
                
                global void execute(Database.BatchableContext BC, List<Maintenance_Contract__c> mcList) {
                    // LHJ 20190712 HWAG-BDH9V5 Start
                    Savepoint sp = Database.setSavepoint();
                    totalCount += 1;
                    system.debug('输入集合=='+this.ConId);
                    try {
                    // LHJ 20190712 HWAG-BDH9V5 End
                        // 维修合同更新
                        Map<Id, Maintenance_Contract__c> updateMC = new Map<Id, Maintenance_Contract__c>();
                        /******************************* HWAG-AV2C67 2018/1/17 START ******************************/
                            //List<Id> mcids = new List<Id>();
                        // 报价合并 20230524 start
                        List<Id> mcids1 = new List<Id>();
                        Map<Id, Double> mcLimitPrice = new Map<Id, Double>();
                       for (Maintenance_Contract__c mc:mcList) {
                           if (mc.PackageFlag__c) {
                               mcids1.add(mc.id);
                           }
                           if (!mc.PackageFlag__c && mc.Limit_Price_Amount__c !=null && mc.Limit_Price_Amount__c !=0) {
                               mcLimitPrice.put(mc.id,mc.Limit_Price_Amount__c);
                           }
                       }
        
                        List<Maintenance_Contract__c> mc1List = [SELECT Id,Name,
                                                                        MaintanceContractPack__c,
                                                                        MaintanceContractPack__r.id,
                                                                        MaintanceContractPack__r.Sum_repair_price__c,
                                                                        MaintanceContractPack__r.Limit_Price_Amount__c 
                                                                FROM Maintenance_Contract__c
                                                                WHERE 
                                                                Id IN :mcids1];
                                                            
                        Map<Id, MaintanceContractPack__c> updateMCP = new Map<Id, MaintanceContractPack__c>();
                        Map<Id, MaintanceContractPack__c> mcpMap = new Map<Id, MaintanceContractPack__c>();
                        Map<Id, Double> repaList = new Map<Id, Double>();
                        Map<Id, Double> mcpTomcList = new Map<Id, Double>();
                        for (Maintenance_Contract__c mc :mc1List) {
                            if (mc.MaintanceContractPack__c != null) {
                                MaintanceContractPack__c mcp =new MaintanceContractPack__c();
                                mcp.id = mc.MaintanceContractPack__c;
                                mcpId = mcp.id;
                                mcp.Limit_Price_Amount__c = mc.MaintanceContractPack__r.Limit_Price_Amount__c;
                                // if (mc.MaintanceContractPack__r.Sum_repair_price__c!=null && mc1List.size()==1) {
                                //     mcp.Sum_repair_price__c = mc.MaintanceContractPack__r.Sum_repair_price__c;
                                // }else{
                                mcp.Sum_repair_price__c = 0;
                                // }
                                mcpMap.put(mc.id,mcp);
                                system.debug('mcpMap=='+mcpMap);
                            }
                        }
                        if (mc1List.size()==1) {
                            List<Maintenance_Contract__c> mc2List = [SELECT id,Name,Sum_repair_price_new__c,MaintanceContractPack__c 
                                                                FROM Maintenance_Contract__c
                                                                WHERE  MaintanceContractPack__c =:mcpId];
                            for (Maintenance_Contract__c mc: mc2List) {
                                system.debug('mc.id=='+mc.id);
                                system.debug('mc1List[0].id=='+mc1List[0].id);
                                if (mc.id != mc1List[0].id) {
                                    if (mcpMap.get(mc1List[0].id).Sum_repair_price__c!=null) {
                                        Decimal Sum_repairprice = mcpMap.get(mc1List[0].id).Sum_repair_price__c;
                                        system.debug('Sum_repairprice=='+Sum_repairprice);
                                        if (mc.Sum_repair_price_new__c!=null) {
                                            Sum_repairprice += mc.Sum_repair_price_new__c;
                                        }
                                        MaintanceContractPack__c mcp =new MaintanceContractPack__c();
                                        mcp.id = mc.MaintanceContractPack__c;
                                        if (mcpMap.get(mc1List[0].id).Limit_Price_Amount__c!=null) {
                                            mcp.Limit_Price_Amount__c = mcpMap.get(mc1List[0].id).Limit_Price_Amount__c;
                                        }
                                        mcp.Sum_repair_price__c = Sum_repairprice;
                                        system.debug('mcp不为空=='+mcp);
                                        mcpMap.put(mc1List[0].id,mcp);
                                    }else{
                                        MaintanceContractPack__c mcp =new MaintanceContractPack__c();
                                        mcp.id = mc.MaintanceContractPack__c;
                                        if (mcpMap.get(mc1List[0].id).Limit_Price_Amount__c!=null) {
                                            mcp.Limit_Price_Amount__c = mcpMap.get(mc1List[0].id).Limit_Price_Amount__c;
                                        }
                                        if (mc.Sum_repair_price_new__c!=null) {
                                           mcp.Sum_repair_price__c = mc.Sum_repair_price_new__c;
                                        }
                                        system.debug('mcp为空=='+mcp);
                                        mcpMap.put(mc1List[0].id,mcp);
                                    }  
                                }
                            }
                        }
                          
                        // 报价合并 20230524 end
                        // 已经SAP的循环汇总
                        List<Repair__c> sapRepairList = 
                                        [select Repair_List_Price_formula__c,
                                                Repair_cost__c,
                                                Maintenance_Contract__c,
                                                Maintenance_Contract__r.Contract_Start_Date__c,
                                                Maintenance_Contract__r.Limit_Price_Amount__c,
                                                Maintenance_Contract__r.Contract_End_Date__c,
                                                Failure_Occurrence_Date__c,
                                                Repair_Quotation_Id__r.LatestQuotationDate__c,
                                                Repair_Quotation_Id__c
                                        from Repair__c
                                        where Maintenance_Contract__c != null 
                                        /* CHAN-B7J5EK 2018/12/18 按照维修合同划分进行检索 start */
                                        and Maintenance_Contract__c in: mcList 
                                        /* CHAN-B7J5EK 2018/12/18 按照维修合同划分进行检索 end */
                                        and Status2__c !='00.删除' 
                                        and Status2__c !='00.取消' 
                                        and Repair_Quotation_Id__c !=null 
                                        and (CutPrice_Reason__c='维修合同' 
                                            or CutPrice_Reason__c='套餐折扣,维修合同'
                                            or CutPrice_Reason__c='营业对应,维修合同'
                                            or CutPrice_Reason__c='上限合同')
                                        order by Maintenance_Contract__c];
        
                        if (sapRepairList != null && sapRepairList.size() > 0) {
                            for (Repair__c rc : sapRepairList) {
                                Maintenance_Contract__c mc = new Maintenance_Contract__c();
                                if (updateMC.containsKey(rc.Maintenance_Contract__c)) {
                                    mc = updateMC.get(rc.Maintenance_Contract__c);
                                } else {
                                    mc.Id = rc.Maintenance_Contract__c;
                                    mc.Sum_repair_price__c=0.0;
                                    mc.Repair_Cost_Sum__c =0.0;
                                   
                                }
                                Date dTDate = rc.Failure_Occurrence_Date__c;
                                Date dSDate = rc.Maintenance_Contract__r.Contract_Start_Date__c;
                                Date dEDate = rc.Maintenance_Contract__r.Contract_End_Date__c;
        
                                if (dTDate >= dSDate && dTDate <= dEDate) {
                                    mc.Sum_repair_price__c += rc.Repair_List_Price_formula__c == null ? 0 : rc.Repair_List_Price_formula__c;
                                    mc.Repair_Cost_Sum__c += rc.Repair_cost__c == null ? 0 : rc.Repair_cost__c;
                                }
                                updateMC.put(rc.Maintenance_Contract__c, mc);
                            }
                        }
        
                        // 没有SAP的循环汇总
                        List<Repair__c> noSapRepairList = 
                                        [select Repair_List_Price_formula__c,
                                                Repair_cost__c,
                                                Maintenance_Contract__c,
                                                Maintenance_Contract__r.Contract_Start_Date__c,
                                                Maintenance_Contract__r.Contract_End_Date__c,
                                                Maintenance_Contract__r.Limit_Price_Amount__c,
                                                Maintenance_Contract__r.Remaining_Amount__c,
                                                Failure_Occurrence_Date__c,
                                                Repair_Quotation_Id__c
                                         from Repair__c
                                         where Maintenance_Contract__c != null 
                                        /* CHAN-B7J5EK 2018/12/18 按照维修合同划分进行检索 start */
                                        and Maintenance_Contract__c in: mcList 
                                        /* CHAN-B7J5EK 2018/12/18 按照维修合同划分进行检索 end */
                                         and Status2__c !='00.删除' 
                                         and Status2__c !='00.取消' 
                                         and Repair_Quotation_Id__c=null
                                         order by Maintenance_Contract__c];
                        if (noSapRepairList != null && noSapRepairList.size() > 0) {
                            for (Repair__c rc : noSapRepairList) {
                                Maintenance_Contract__c mc = new Maintenance_Contract__c();
                                if (updateMC.containsKey(rc.Maintenance_Contract__c)) {
                                    mc = updateMC.get(rc.Maintenance_Contract__c);
                                } else {
                                    mc.Id = rc.Maintenance_Contract__c;
                                    mc.Sum_repair_price__c=0.0;
                                    mc.Repair_Cost_Sum__c =0.0;
        
                                }
                                Date dTDate = rc.Failure_Occurrence_Date__c;
                                Date dSDate = rc.Maintenance_Contract__r.Contract_Start_Date__c;
                                Date dEDate = rc.Maintenance_Contract__r.Contract_End_Date__c;
        
                                if (dTDate >= dSDate && dTDate <= dEDate) {
                                    mc.Sum_repair_price__c += rc.Repair_List_Price_formula__c == null ? 0 : rc.Repair_List_Price_formula__c;
                                    mc.Repair_Cost_Sum__c += rc.Repair_cost__c == null ? 0 : rc.Repair_cost__c;
                                }
                                updateMC.put(rc.Maintenance_Contract__c, mc);
                            }
                        }
        
                        // LHJ 20190712 HWAG-BDH9V5 Start
        
                        List<Repair__c> newRepairList = 
                                        [select Id,Usage_Ratio_Price__c,
                                                Repair_cost__c,
                                                Maintenance_Contract__c,
                                                Maintenance_Contract__r.Contract_Start_Date__c,
                                                Maintenance_Contract__r.Contract_End_Date__c,
                                                Maintenance_Contract__r.Remaining_Amount__c,
                                                Maintenance_Contract__r.Limit_Price_Amount__c,
                                                Failure_Occurrence_Date__c,
                                                Repair_Quotation_Id__c,
                                                EquipmentGuaranteeFlg_Asset__c,
                                                if_Rental_Apply__c,
                                                Offer_Rental_New__c,
                                                Usage_Ratio_Price_Guarantee__c,
                                                VM_Maintenance_Contract__c,
                                                VM_Maintenance_Contract__r.RecordType_DeveloperName__c,
                                                Maintenance_Contract__r.RecordType_DeveloperName__c,
                                                VM_Maintenance_Contract__r.startDateGurantee__c,
                                                VM_Maintenance_Contract__r.endDateGurantee__c 
                                                ,Agreed_Date__c //用户同意日 上限合同 LY 20230210 add
                                                ,Limit_Price__c //上限修理 上限合同 LY 20230210 add
                                                ,Remaining_Amount__c // 剩余金额 报价合并 20230606add
                                         from Repair__c
                                         where (Maintenance_Contract__c != null or VM_Maintenance_Contract__c != null) 
                                        and (Maintenance_Contract__c in: mcList or VM_Maintenance_Contract__c in: mcList) 
                                         and Status2__c !='00.删除' 
                                         and Status2__c !='00.取消' 
                                         order by Maintenance_Contract__c
                                         ];
        
                        if (newRepairList != null && newRepairList.size() > 0) {
        
                            for (Repair__c rc : newRepairList) {
                                if (rc.Maintenance_Contract__c != null) {            
                                    Maintenance_Contract__c mc = new Maintenance_Contract__c();
                                    if (updateMC.containsKey(rc.Maintenance_Contract__c)) {
                                        mc = updateMC.get(rc.Maintenance_Contract__c);
                                    } else {
                                        mc.Id = rc.Maintenance_Contract__c;
                                        mc.Sum_repair_price_new__c=0.00;
                                       
                                    }
                                    Date dTDate = rc.Failure_Occurrence_Date__c;
                                    Date dSDate = rc.Maintenance_Contract__r.Contract_Start_Date__c;
                                    Date dEDate = rc.Maintenance_Contract__r.Contract_End_Date__c;
        
                                    if (mc.Sum_repair_price_new__c == null) {
                                        mc.Sum_repair_price_new__c = 0.00;
                                    }
                                    if (dTDate >= dSDate && dTDate <= dEDate) {  
                                        //上限合同 LY 20230210 start
                                           
                                        if (rc.Limit_Price__c == true) {
                                            if (rc.Agreed_Date__c!=null) {//报价同意后 修理的【计入合同消费率的修理金额】记入到维修合同的合同期间修理金额】  上限合同 LY add 20230210
                                                mc.Sum_repair_price_new__c += rc.Usage_Ratio_Price__c == null ? 0 : rc.Usage_Ratio_Price__c;
                                                // 报价合并 20230524 start
                                                MaintanceContractPack__c mcp = new MaintanceContractPack__c();
                                                Double RemainingAmount;
                                                if (updateMC.get(rc.Maintenance_Contract__c)!=null) {
                                                        RemainingAmount = updateMC.get(rc.Maintenance_Contract__c).Remaining_Amount__c;
                                                    }else{
                                                        RemainingAmount = rc.Maintenance_Contract__r.Remaining_Amount__c;
                                                }
                                                if (mcpMap.containsKey(mc.id)) {
                                                  system.debug('RemainingAmount='+RemainingAmount); 
                                                    mcp.id = mcpMap.get(mc.id).id;
                                                    system.debug('mcp.id======='+mcp.id);
                                                    system.debug('大合同期间修理金额1='+mcpMap.get(mc.id).Sum_repair_price__c); 
                                                    if (updateMCP.containsKey(mcp.id)) {
                                                        updateMCP.get(mcp.id).Sum_repair_price__c += rc.Usage_Ratio_Price__c == null ? 0 : rc.Usage_Ratio_Price__c;
                                                    }else{
                                                        mcp.Sum_repair_price__c = mcpMap.get(mc.id).Sum_repair_price__c;
                                                        mcp.Sum_repair_price__c += rc.Usage_Ratio_Price__c == null ? 0 : rc.Usage_Ratio_Price__c;
                                                        updateMCP.put(mcp.id,mcp);
                                                    }
                                                    system.debug('大合同期间修理金额2='+updateMCP.get(mcp.id).Sum_repair_price__c); 
                                                    if (mcpMap.get(mc.id).Limit_Price_Amount__c!=null &&updateMCP.get(mcp.id).Sum_repair_price__c!=null) {
                                                         RemainingAmount = mcpMap.get(mc.id).Limit_Price_Amount__c - updateMCP.get(mcp.id).Sum_repair_price__c;
                                                    }
                                                    // if (RemainingAmount!=null && RemainingAmount>0 && RemainingAmount<=20000) {
                                                    // }
                                                     system.debug('剩余金额====='+RemainingAmount);
                                                     mcpTomcList.put(mcp.id,updateMCP.get(mcp.id).Sum_repair_price__c);
                                                     repaList.put(mcp.id,RemainingAmount);
                                                }
                                                
                                                // 报价合并 20230524 end
                                            }
                                        }else{
                                            mc.Sum_repair_price_new__c += rc.Usage_Ratio_Price__c == null ? 0 : rc.Usage_Ratio_Price__c;
                                        }
                                        //上限合同 LY 20230210 end
                                    }
                                    System.debug('上限金额结束'+mcLimitPrice.get(mc.id));
                                    System.debug('修理金额结束'+mc.Sum_repair_price_new__c);
                                    updateMC.put(rc.Maintenance_Contract__c, mc);
                                }
                                //20210106 zh LJPH-BWM5HM 多年保修【合同期间修理金额】逻辑修改 start
                                if (rc.VM_Maintenance_Contract__c != null) {
                                    Maintenance_Contract__c mc = new Maintenance_Contract__c();
                                    if (updateMC.containsKey(rc.VM_Maintenance_Contract__c)) {
                                        mc = updateMC.get(rc.VM_Maintenance_Contract__c);
                                    } else {
                                        mc.Id = rc.VM_Maintenance_Contract__c;
                                        mc.Sum_repair_price_new__c=0.00;
                                    }
                                    Date dTDate = rc.Failure_Occurrence_Date__c;
                                    Date dSDate = rc.VM_Maintenance_Contract__r.startDateGurantee__c;
                                    Date dEDate = rc.VM_Maintenance_Contract__r.endDateGurantee__c;
        
                                    if (mc.Sum_repair_price_new__c == null) {
                                        mc.Sum_repair_price_new__c = 0.00;
                                    }
                                    // gzw LJPH-BZDA84 多年保合同修理价格不根据开始结束日算 start
                                    // if (dTDate >= dSDate && dTDate <= dEDate) {
                                        //20210106 zh LJPH-BWM5HM 多年保修【合同期间修理金额】逻辑修改 start
                                        // mc.Sum_repair_price_new__c += rc.Usage_Ratio_Price__c == null ? 0 : rc.Usage_Ratio_Price__c;
                                        if ('VM_Contract'.equals(rc.VM_Maintenance_Contract__r.RecordType_DeveloperName__c)) {
                                            mc.Sum_repair_price_new__c += rc.Usage_Ratio_Price_Guarantee__c == null ? 0 : rc.Usage_Ratio_Price_Guarantee__c;
                                        }
                                        //20210106 zh LJPH-BWM5HM 多年保修【合同期间修理金额】逻辑修改 end
                                    // }
                                    // // gzw LJPH-BZDA84 多年保合同修理价格不根据开始结束日算 end
                                    updateMC.put(rc.VM_Maintenance_Contract__c, mc);
                                    //20210106 zh LJPH-BWM5HM 多年保修【合同期间修理金额】逻辑修改 end
                                }
                            }
                        }
                        // 报价合并 20230524 start
                            Map<String,Double> mcids = new  Map<String,Double>();
                            List<Repair__c> upRepair = new List<Repair__c>();
                            List<Maintenance_Contract__c> upMc = new List<Maintenance_Contract__c>();
                            List<Maintenance_Contract__c> mcOne = [select id,MaintanceContractPack__c from Maintenance_Contract__c where MaintanceContractPack__c in :repaList.keySet()];
                            List<Maintenance_Contract__c> mcTwo = [select id,MaintanceContractPack__c from Maintenance_Contract__c where MaintanceContractPack__c in :mcpTomcList.keySet()];
                            List<Maintenance_Contract__c> mcThi = [select id,MaintanceContractPack__c,RecordType_Name__c from Maintenance_Contract__c where id in :updateMC.keySet()];
                            system.debug('mcpTomcList=='+mcpTomcList);
                            system.debug('mcOne=='+mcOne);
                            system.debug('mcTwo=='+mcTwo);
                            for (Maintenance_Contract__c mc :mcOne) {
                                if (repaList.containsKey(mc.MaintanceContractPack__c)) {
                                    mcids.put(mc.id,repaList.get(mc.MaintanceContractPack__c));
                                }  
                            }
                            for (Maintenance_Contract__c mc :mcTwo) {
                                Maintenance_Contract__c mc1 = new Maintenance_Contract__c();
                                mc1.id = mc.id;
                                if (mcpTomcList.containsKey(mc.MaintanceContractPack__c)) {
                                    mc1.Sum_repair_price_new_DB__c = mcpTomcList.get(mc.MaintanceContractPack__c);
                                    upMc.add(mc1);
                                }
                            }
                            for (Maintenance_Contract__c mc :mcThi) {
                                system.debug('断点1==');
                                if (updateMC.containsKey(mc.id) && mc.RecordType_Name__c != '多年保修合同') {
                                    system.debug('断点2==');
                                    if (mcLimitPrice.size()>0 &&updateMC.values()!=null) {
                                        system.debug('断点3==');
                                        system.debug('mcLimitPrice.get(mc.id)=='+mcLimitPrice.get(mc.id));
                                         system.debug('updateMC.get(mc.id)=='+updateMC.get(mc.id));
                                        system.debug('updateMC.get(mc.id).Sum_repair_price_new__c=='+updateMC.get(mc.id).Sum_repair_price_new__c);
                                        Double Remaining = mcLimitPrice.get(mc.id)-updateMC.get(mc.id).Sum_repair_price_new__c;
                                        mcids.put(mc.id,Remaining);
                                    }  
                                }
                                system.debug('断点4==');
                            }
                            List<Repair__c> repaupdate = [select id,Remaining_Amount__c,Maintenance_Contract__c from Repair__c where Maintenance_Contract__c in :mcids.keySet()];
                            for (Repair__c re :repaupdate) {
                                Repair__c re1 = new Repair__c();
                                re1.id = re.id;
                                if (mcids.containsKey(re.Maintenance_Contract__c)) {
                                    re1.Remaining_Amount__c = mcids.get(re.Maintenance_Contract__c);
                                    upRepair.add(re1);
                                }
                            }
                        // 报价合并 20230524 end
                        // LD 20200721 备品出借可视化管理 Start
                       
                        //根据维修合同ID查询所有对应维修合同
                        List<Maintenance_Contract__c> conList = [SELECT Id,Name,
                                                                        RentalRelatedCnt__c,
                                                                        NoRentalRelatedCnt__c,
                                                                        RentalRelatedRepairCnt__c,
                                                                        RentalRelatedApplyCnt__c,
                                                                        RentalRelatedSupplyCnt__c,
                                                                        NoRentalRelatedRepairCnt__c,
                                                                        NoRentalRelatedApplyCnt__c,
                                                                        NoRentalRelatedSupplyCnt__c
                                                                FROM Maintenance_Contract__c
                                                                WHERE 
                                                                Id IN :mcList];
        
                        //根据维修合同ID查询对应维修保有设备
                        List<Maintenance_Contract_Asset__c> assList = 
                        [SELECT Id, 
                        Asset__r.EGFlg_fromContract_asset__c
                        , Maintenance_Contract__c 
                            FROM Maintenance_Contract_Asset__c 
                            WHERE Maintenance_Contract__c = :mcList];
                        newRepairList = [
                            select id, EquipmentGuaranteeFlg_Asset__c,
                            if_Rental_Apply__c, Offer_Rental_New__c,Maintenance_Contract__c
                            from  Repair__c
                            where Maintenance_Contract__c in: mcList
                            and Status2__c !='00.删除' 
                            and Status2__c !='00.取消' 
                            order by Maintenance_Contract__c
        
                        ];
        
                        
                        //维修合同
                        if (conList != null && conList.size() > 0) {
                           for (Maintenance_Contract__c con : conList) {
        
                                if(updateMc.containsKey(con.Id)){
                                    con = updateMc.get(con.Id);
                                }
        
                                con.RentalRelatedCnt__c = 0;
                                con.NoRentalRelatedCnt__c = 0;
                                con.RentalRelatedRepairCnt__c = 0;
                                con.RentalRelatedApplyCnt__c = 0;
                                con.RentalRelatedSupplyCnt__c = 0;
                                con.NoRentalRelatedRepairCnt__c = 0;
                                con.NoRentalRelatedApplyCnt__c = 0;
                                con.NoRentalRelatedSupplyCnt__c = 0;
        
                                if (assList != null && assList.size() > 0) {
                                    for (Maintenance_Contract_Asset__c ass :  assList) {
                                        System.debug(ass.Maintenance_Contract__c+'====ass.CurrentContract__c');
                                        System.debug(con.Id+'====con.Id');
                                         if(ass.Maintenance_Contract__c == con.Id){
                                            if (ass.Asset__r.EGFlg_fromContract_asset__c == true) {
                                                con.RentalRelatedCnt__c = con.RentalRelatedCnt__c + 1;
                                            }else{
                                                con.NoRentalRelatedCnt__c = con.NoRentalRelatedCnt__c + 1;
                                            }
                                            updateMC.put(con.Id,con);
                                        }
                                    }
                                }
        
                                if (newRepairList != null && newRepairList.size() > 0) {
                                    for (Repair__c repc : newRepairList) {
                                        if( con.Id == repc.Maintenance_Contract__c){
                                            //备品确保提供选框为True
                                            if(repc.EquipmentGuaranteeFlg_Asset__c == true){
                                                con.RentalRelatedRepairCnt__c = con.RentalRelatedRepairCnt__c + 1;
                                                //是否申请备品选框为True
                                                if(repc.if_Rental_Apply__c == true){
                                                    con.RentalRelatedApplyCnt__c =  con.RentalRelatedApplyCnt__c + 1;
                                                }
                                                //是否提供备品选框为True
                                                if(repc.Offer_Rental_New__c == true){
                                                    con.RentalRelatedSupplyCnt__c = con.RentalRelatedSupplyCnt__c + 1;
                                                }
                                            }
                                            //备品确保提供对象为False
                                            if(repc.EquipmentGuaranteeFlg_Asset__c == false){
                                                con.NoRentalRelatedRepairCnt__c = con.NoRentalRelatedRepairCnt__c + 1;
                                                //是否申请备品选框为True
                                                if(repc.if_Rental_Apply__c == true){
                                                    con.NoRentalRelatedApplyCnt__c = con.NoRentalRelatedApplyCnt__c + 1;
                                                }
                                                //是否提供备品选框为True
                                                if(repc.Offer_Rental_New__c == true){
                                                    con.NoRentalRelatedSupplyCnt__c = con.NoRentalRelatedSupplyCnt__c + 1;
                                                }
                                            }
                                            updateMC.put(con.Id,con);
                                        }
                                    }
                                }    
                            } 
                        }
                        // LD 20200721 备品出借可视化管理 End
                        if (updateMC.size() > 0) {
                            update updateMC.values();
                        }
                        // 报价合并 20230524 start
                        if (upMc.size() > 0) {
                            update upMc;
                        }
                        system.debug('updateMCP======'+updateMCP);
                        if (updateMCP.size() > 0) {
                            update updateMCP.values();
                        }
                        if (upRepair.size() > 0) {
                            update upRepair;
                        }
                        // 报价合并 20230524 end
                    } catch (Exception e) {
                        Database.rollback(sp);
                        emailMessages.add(e.getMessage());
                        System.debug(emailMessages);
                        failedCount += mcList.size();
                        System.debug(failedCount);
                    }
                    // LHJ 20190712 HWAG-BDH9V5 End
        
                    
                    
                    
                    //for (SObject sobj : mcList) {
                    //  Maintenance_Contract__c mc = new Maintenance_Contract__c(Id=String.valueOf(sobj.get('Maintenance_Contract__c')));
                    //  initMC(mc);
                    //  updateMC.put(mc.Id, mc);
                    //  mcids.add(String.valueOf(sobj.get('Maintenance_Contract__c')));
                    //}
                    //筛选出需要更新的数据
                    //List<Maintenance_Contract__c> NeedUpdate = new List<Maintenance_Contract__c>();
                    // 修理 修理金额
                    // 要判断是否SAP
                    //已经SAP的循环汇总
                    //for (AggregateResult aggAst : [
                    //          select SUM(Repair_List_Price_formula__c) sum_Price,
                    //                 SUM(Repair_cost__c) sum_PricePr,
                    //                      Maintenance_Contract__c,
                    //                      Maintenance_Contract__r.Contract_Start_Date__c,
                    //                      Maintenance_Contract__r.Contract_End_Date__c,
                    //                      Failure_Occurrence_Date__c,
                    //                      Repair_Quotation_Id__r.LatestQuotationDate__c,
                    //                      Repair_Quotation_Id__c
                    //              from Repair__c
                    //           where Maintenance_Contract__c != null
                    //           and Status2__c !='00.删除' 
                    //           and Repair_Quotation_Id__c !=null 
                    //           and (CutPrice_Reason__c='维修合同' or CutPrice_Reason__c='套餐折扣,维修合同'or CutPrice_Reason__c='营业对应,维修合同') 
                    //           group by   Maintenance_Contract__c,Maintenance_Contract__r.Contract_Start_Date__c,Maintenance_Contract__r.Contract_End_Date__c,
                    //                      Failure_Occurrence_Date__c,Repair_Quotation_Id__r.LatestQuotationDate__c,Repair_Quotation_Id__c
                    //  ]) {
                    //          Id mcid = (Id) aggAst.get('Maintenance_Contract__c');
                    //          Maintenance_Contract__c mc = updateMC.get(mcid);
                    //          Date dRDate = Date.valueOf(aggAst.get('LatestQuotationDate__c'));
                    //          Date dTDate = Date.valueOf(aggAst.get('Failure_Occurrence_Date__c'));
                    //          Date dSDate = Date.valueOf(aggAst.get('Contract_Start_Date__c'));
                    //          Date dEDate = Date.valueOf(aggAst.get('Contract_End_Date__c'));
                    //          id RqcID  = (id) aggAst.get('Repair_Quotation_Id__c');
                    //          if (dTDate >= dSDate && dTDate <= dEDate) {
        
                    //              mc.Sum_repair_price__c += aggAst.get('sum_Price') == null ? 0 : Decimal.valueOf(String.valueOf(aggAst.get('sum_Price')));
                    //              mc.Repair_Cost_Sum__c += aggAst.get('sum_PricePr') == null ? 0 : Decimal.valueOf(String.valueOf(aggAst.get('sum_PricePr')));
                    //          }
                    //  }
                        
                        //没有SAP的循环汇总  
                        //for (AggregateResult aggAst : [
                        //      select SUM(Repair_List_Price_formula__c) sum_Price,
                        //              SUM(Repair_cost__c) sum_PricePr,
                        //                   Maintenance_Contract__c,
                        //                   Maintenance_Contract__r.Contract_Start_Date__c,
                        //                   Maintenance_Contract__r.Contract_End_Date__c,
                        //                   Failure_Occurrence_Date__c,
                        //                   Repair_Quotation_Id__c
                        //          from Repair__c
                        //       where Maintenance_Contract__c != null
                        //       and Status2__c !='00.删除' 
                        //       and Repair_Quotation_Id__c=null
                        //       group by   Maintenance_Contract__c,Maintenance_Contract__r.Contract_Start_Date__c,Maintenance_Contract__r.Contract_End_Date__c,
                        //                  Failure_Occurrence_Date__c,Repair_Quotation_Id__c
                        //]) {
                        //      Id mcid = (Id) aggAst.get('Maintenance_Contract__c');
                        //      Maintenance_Contract__c mc = updateMC.get(mcid);
                        //      Date dTDate = Date.valueOf(aggAst.get('Failure_Occurrence_Date__c'));
                        //      Date dSDate = Date.valueOf(aggAst.get('Contract_Start_Date__c'));
                        //      Date dEDate = Date.valueOf(aggAst.get('Contract_End_Date__c'));
                        //      id RqcID  = (id) aggAst.get('Repair_Quotation_Id__c');
                        //      if (dTDate >= dSDate && dTDate <= dEDate) {
        
                        //          mc.Sum_repair_price__c += aggAst.get('sum_Price') == null ? 0 : Decimal.valueOf(String.valueOf(aggAst.get('sum_Price')));
                        //          mc.Repair_Cost_Sum__c += aggAst.get('sum_PricePr') == null ? 0 : Decimal.valueOf(String.valueOf(aggAst.get('sum_PricePr')));
                        //      }
                        //}
                        /******************************* HWAG-AV2C67 2018/1/17 END ******************************/
                        
                        
                }
                //and (CutPrice_Reason__c='维修合同' or CutPrice_Reason__c='维修合同，套餐折扣'or CutPrice_Reason__c='营业对应，维修合同') 
                
                // LHJ 20190712 HWAG-BDH9V5 Start
                global void finish(Database.BatchableContext BC) {
                        // 今回はやることないです
                    sendFieldEmail();
                }
        
                private void sendFieldEmail() {
                    PretechBatchEmailUtil be = new PretechBatchEmailUtil();
                    String[] toList = new String[] {UserInfo.getUserEmail()};
                    String title = '维修合同更新失败';
                    String[] ccList = new String[] {};
                    if(System.Test.isRunningTest()){
                        be.successMail('', 1);
                    }
                    if (emailMessages.size() > 0) {
                        be.failedMail(toList, ccList, title,
                                      String.join(this.emailMessages, '\n'),
                                      totalCount, totalCount - failedCount, failedCount,'',false);
                        be.send();
                    }
                }
                // LHJ 20190712 HWAG-BDH9V5 End
                /******************************* HWAG-AV2C67 2018/1/17 START ******************************/
            //  private void initMC(Maintenance_Contract__c mc) {
            //      mc.Sum_repair_price__c = 0.0;
            //      mc.Repair_Cost_Sum__c =0.0;
            //  }
                
            //  public class AggregateResultIterator implements Iterator<AggregateResult> {
            //      AggregateResult [] results {get;set;}
            //      // tracks which result item is returned
            //      Integer index {get; set;}
                                 
            //      public AggregateResultIterator() {
            //              index = 0;
            //              // Fire query here to load the results
            //              Date tdate = Date.today();
            //                  Date before2day = tdate.addDays(-2);
            //              Date sdate = tdate.addDays(-30);
            //                  Datetime before2dayTime = Datetime.newInstance(before2day, Time.newInstance(0, 0, 0, 0));
            //              results = [
            //                          Select Maintenance_Contract__c
            //                              From Repair__c
            //                          Where Maintenance_Contract__c != null 
                                        
            //                          GROUP BY Maintenance_Contract__c
        
            //                  ];           
            //      }
                    
            //      public boolean hasNext(){
            //              return results != null && !results.isEmpty() && index < results.size();
            //      }   
                    
            //      public AggregateResult next(){       
            //              return results[index++];           
            //      }      
            //}
            
            //public class AggregateResultIterable implements Iterable<AggregateResult> {
            //      public Iterator<AggregateResult> Iterator(){
            //              return new AggregateResultIterator();
            //      }
            //}
            /******************************* HWAG-AV2C67 2018/1/17 END ******************************/
        }