// 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 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]
            //);

            
            if(ConId != null && ConId.size() > 0) {
                return Database.getQueryLocator([select Id from Maintenance_Contract__c where Id in :ConId]);
            } else {
                return Database.getQueryLocator([select Id from Maintenance_Contract__c]);
            }

            
            // LHJ 20190712 HWAG-BDH9V5 End

            // if(ConId != null && ConId.size() > 0) {
            //     return Database.getQueryLocator()
            // }
        }
        
        global void execute(Database.BatchableContext BC, List<SObject> mcList) {
            // LHJ 20190712 HWAG-BDH9V5 Start
            Savepoint sp = Database.setSavepoint();
            totalCount += 1;

            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>();

                // 已经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.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='营业对应,维修合同')
                                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,
                                        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,
                                        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 
                                 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) {   
                                mc.Sum_repair_price_new__c += rc.Usage_Ratio_Price__c == null ? 0 : rc.Usage_Ratio_Price__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
                        }
                    }
                }

                // 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();
                }
            } 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 ******************************/
}