global class ServiceMaintenanceHistoryBatch implements Database.Batchable<sObject> {
    List<String> idList = new List<String>();
    public ServiceMaintenanceHistoryBatch(){
        
    }
    public ServiceMaintenanceHistoryBatch(List<String> idList){
        this.idList = idList;
    }
    global Database.QueryLocator start(Database.BatchableContext bc) {
        String query = 'SELECT Id,Status__c,Contract_Start_Date__c,Contract_print_completed__c,Contract_End_Date__c,Contract_Conclusion_Date__c,RecordType.DeveloperName '
                     +'FROM Maintenance_Contract__c '
                     +'WHERE RecordType.DeveloperName = \'NewMaintenance_Contract\' AND Contract_Start_Date__c != NULL AND Contract_End_Date__c != NULL '
                     +'AND (Status__c = \'契約\' OR Status__c = \'契約満了\') AND Contract_Conclusion_Date__c != NULL ';
        if (idList.size()>0) {
               query  += 'AND Id in :idList';
        }
        system.debug('Start:'+query);
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, list<Maintenance_Contract__c> newMainContract) {
        List<Maintenance_Contract__c> NeedCreateNMC = new List<Maintenance_Contract__c>();
        List<String> NeedCreateNMCId = new List<String>();
        List<NewMaintenanceReport_Task__c>  NMCReportTList= new List<NewMaintenanceReport_Task__c>();
        Map<String,Integer> QuarterNumMap = new Map<String,Integer>();
        Date today = Date.today();
        Date tempDate = Date.newInstance(2021, 8, 1);
        for(Maintenance_Contract__c tempNMC : newMainContract){
            Decimal resultDecimal = 0;
            resultDecimal = Decimal.valueOf(tempNMC.Contract_Start_Date__c.monthsBetween(tempNMC.Contract_End_Date__c.addDays(1))) / 3;
            Integer resultUp = Integer.valueOf(resultDecimal.round(System.RoundingMode.DOWN)); 
            if(tempNMC.Contract_Start_Date__c.monthsBetween(tempNMC.Contract_End_Date__c.addDays(1)) > 0&& !QuarterNumMap.containsKey(tempNMC.Id)){
                QuarterNumMap.put(tempNMC.Id , resultUp);
                NeedCreateNMC.add(tempNMC);
                NeedCreateNMCId.add(tempNMC.Id);
            }
        }
        List<NewMaintenanceReport_Task__c> existNMCReprot = [select Id,Name,NewMaintenance_Contract__c  from NewMaintenanceReport_Task__c where NewMaintenance_Contract__c IN :NeedCreateNMCId ];
        Map<String,NewMaintenanceReport_Task__c> existNMCReportMap = new Map<String,NewMaintenanceReport_Task__c>();
        if(existNMCReprot.size()>0){
            for(NewMaintenanceReport_Task__c NMrt :existNMCReprot){
                existNMCReportMap.put(NMrt.NewMaintenance_Contract__c , NMrt);
            }
        }
        if(NeedCreateNMC.size()>0){
            for(Integer i = 0; i<NeedCreateNMC.size();i++){
                Maintenance_Contract__c tempNMC = NeedCreateNMC.get(i);
                if(existNMCReportMap.get(tempNMC.Id) != null){
                    NeedCreateNMC.remove(i);
                    i--;
                }
            }
        }
        if(NeedCreateNMC.size()>0){
            //遍历需要创建报告书的合同
            for(Maintenance_Contract__c tempNMC : NeedCreateNMC){
                //定义变量,判断是否需要顺延
                Boolean isDelay = false;
                if(tempNMC.Contract_print_completed__c > tempNMC.Contract_Start_Date__c.addMonths(1)){
                    isDelay = true;
                }
        
                //获取当前遍历的合同的季度数 并遍历 生成报告书
                for(Integer qnum = 1;qnum <= QuarterNumMap.get(tempNMC.Id);qnum++){
                    //如果 当合同生效日晚于【合同开始日+3个月】, 顺延为第二季度
                    if(isDelay){
                        isDelay = false;
                        continue;
                    }
        
                    //计算开始日期
                    Date DistributionStartDate= tempNMC.Contract_Start_Date__c.addMonths((qnum-1) * 3);
                    //计算结束日期
                    Date DistributionEndDate = tempNMC.Contract_Start_Date__c.addMonths((qnum) * 3).addDays(-1);
        
                    //开始生成服务合同报告书
                    NewMaintenanceReport_Task__c tempNMCT = new NewMaintenanceReport_Task__c();
                    //报告书名字
                    if(qnum<10){
                        tempNMCT.Name = 'FWreport-0'+qnum;
                    }else {
                        tempNMCT.Name = 'FWreport-'+qnum;
                    }
                    //季度数
                    tempNMCT.QuartersNum__c = qnum;
                    //发放季度
                    tempNMCT.Distribution_Quarter__c = '第'+qnum+'季度';
                    //发放期间开始日期
                    tempNMCT.Distribution_Start_Date__c = DistributionStartDate; 
                    //发放期间结束日期
                    tempNMCT.Distribution_End_Date__c = DistributionEndDate;
                    //发放期限
                    tempNMCT.CorrespondingPeriod__c =  DistributionEndDate;    
                    //发放人
                    tempNMCT.Distribution_Person__c =  '';
                    //服务合同
                    tempNMCT.NewMaintenance_Contract__c = tempNMC.Id;
                    if(DistributionStartDate < tempDate){
                        tempNMCT.ActualDistributionTimes_Quarter__c = 1;
                    }
                    NMCReportTList.add(tempNMCT);
                }
        
            }
        }
        
        if(NMCReportTList.size()>0){
            insert NMCReportTList;
        }
        
    }
    global void finish(Database.BatchableContext BC) {}
}