/* 2021-03-31  mzy  sla报告书任务开发
  创建服务合同报告书任务
*/
global class CreateNewMaintenanceTaskBatch implements Database.Batchable<sObject> {
    String tempMainId = '';//a0H1s000003ziv9
    Boolean IsNeedExecute = false;
    List<String> idList = new List<String>();
    BatchIF_log__c log1 = new BatchIF_Log__c();

    
    public CreateNewMaintenanceTaskBatch() {
    }

    public CreateNewMaintenanceTaskBatch(String id){
        this.tempMainId = id;
    }

    public CreateNewMaintenanceTaskBatch(Boolean NeedExecute){
        this.IsNeedExecute = NeedExecute;
    }

    public CreateNewMaintenanceTaskBatch(List<String> idList,Boolean NeedExecute){
        this.IsNeedExecute = NeedExecute;
    }

    public CreateNewMaintenanceTaskBatch(String id ,Boolean NeedExecute){
        this.tempMainId = id;
        this.IsNeedExecute = NeedExecute;
    }

    global Database.QueryLocator start(Database.BatchableContext bc) {
        System.debug('Start方法进来没?');
        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 '
                     //URF限次合同2期 LY 20220811 start
                     +'AND URF_Contract__c = false'
                     //URF限次合同2期 LY 20220811 end
                     +'AND Status__c = \'契約\' AND Contract_Conclusion_Date__c != NULL ';
        if (String.isNotBlank(this.tempMainId)) {
               query  += 'AND Id = :tempMainId';
        }
        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) {
        log1.Type__c='SLA_Report';
        log1.Log__c = 'Batch  execute  start\r\n';
        log1.Log__c += 'List :'+newMainContract.size() +'\r\n';
        log1.Log__c += 'List 内容:'+newMainContract +'\r\n';

        //定义变量-----start
        //定义list 存放需要生成服务合同报告书的合同
        List<Maintenance_Contract__c> NeedCreateNMC = new List<Maintenance_Contract__c>();
        //定义list 存放需要生成服务合同报告书的合同Id
        List<String> NeedCreateNMCId = new List<String>();
        //定义list 存放生成的服务合同报告书
        List<NewMaintenanceReport_Task__c>  NMCReportTList= new List<NewMaintenanceReport_Task__c>();
        //定义map  存放季度数  k:合同Id v:季度数
        Map<String,Integer> QuarterNumMap = new Map<String,Integer>();
        //定义map  存放是否需要合并日期
        //Map<String,Boolean> NeedMergeDateMap = new Map<String,Boolean>();
        //定义变量-----end

        //0.获取今天的日期
        Date today = Date.today();
        //1.获取需要生成服务合同报告书的合同
        for(Maintenance_Contract__c tempNMC : newMainContract){
            //判断是否生成服务合同报告书
           // if(tempNMC.Contract_Conclusion_Date__c.addDays(1) == today){

                //计算合同一共有几个季度
                //实际季度
                Decimal resultDecimal = 0;
                resultDecimal = Decimal.valueOf(tempNMC.Contract_Start_Date__c.monthsBetween(tempNMC.Contract_End_Date__c.addDays(1))) / 3;
                log1.Log__c +='正常:'+resultDecimal+'\r\n';
                //UP
                //Integer resultUp = Integer.valueOf(resultDecimal.round(System.RoundingMode.UP)); 
                //DOWN
                Integer resultUp = Integer.valueOf(resultDecimal.round(System.RoundingMode.DOWN)); 

                log1.Log__c += '日期 :实际季度: '+resultDecimal +' 向下取整:'+resultUp+' 是否合并日期:'+(resultDecimal >resultUp?true:false);

                //默认都是不需要合并日期
                //NeedMergeDateMap.put(tempNMC.Id , false);
                //实际大于向下取整
                //if(resultDecimal >resultUp){
                    //说明需要合并日期
                //    NeedMergeDateMap.put(tempNMC.Id , true);
                //}

                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);
                }
           // }
        }
        //4.已经生成报告书的合同将不再去生成  
        List<NewMaintenanceReport_Task__c> existNMCReprot = [select Id,Name,NewMaintenance_Contract__c  from NewMaintenanceReport_Task__c where NewMaintenance_Contract__c IN :NeedCreateNMCId ];
        log1.Log__c += '\r\n已经创建的长度 :'+existNMCReprot.size();
        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--;
                }
            }
        }

        log1.Log__c += '\r\n需要创建的长度 :'+NeedCreateNMC.size();

        //3.生成报告书
        if(NeedCreateNMC.size()>0){
            //遍历需要创建报告书的合同
            for(Maintenance_Contract__c tempNMC : NeedCreateNMC){
                // //定义变量,判断是否需要顺延
                Boolean isDelay = false;
                // //第一版:当合同生效日晚于【合同开始日+3个月】，第一次发放计划顺延为4/1~6/30 (下一季度)。
                // //第二版:合同盖章完毕日晚于【合同开始日+3个月】，不生成第一个区间(即 顺延为下一季度)。
                // //第三版:盖章完毕日晚于合同开始日1个月以上，自动从第二季度开始
                //2022-3-11 yjk 合同盖章日改为合同日
                 if(tempNMC.Contract_Conclusion_Date__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;
                    }

                    //2022-03-01  mzy SLA报告书上线后问题  start
                    //合同日
                    Date ContractConclusionDate = tempNMC.Contract_Conclusion_Date__c;
                    //2022-03-01  mzy SLA报告书上线后问题  end

                    //计算开始日期
                    Date DistributionStartDate= tempNMC.Contract_Start_Date__c.addMonths((qnum-1) * 3);
                    //计算结束日期
                    Date DistributionEndDate = tempNMC.Contract_Start_Date__c.addMonths((qnum) * 3).addDays(-1);
                    
                    //2022-03-01  mzy  SLA报告书上线后问题  start
                    //合同日到满一个季度的期间大于2个月则需要生成发放计划,小于2个月则不需要生成计划
                    //为了防止出现 55485 的那种情况(合同日所在区间之前的季度不再生成)
                    if ((ContractConclusionDate.addMonths(2)>DistributionEndDate) || (ContractConclusionDate > DistributionEndDate)) {
                        continue;
                    }
                    //2022-03-01  mzy  SLA报告书上线后问题  end

                    //开始生成服务合同报告书
                    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;

                    /*
                    //如果为最后一个季度,则判断是否需要合并日期
                    if(qnum == QuarterNumMap.get(tempNMC.Id)){
                    //如果需要合并日期,则结束日期赋值为  合同结束日期+1个月                       
                    //发放期间结束日期 + 1个月
                    tempNMCT.Distribution_End_Date__c = DistributionEndDate;
                    //发放期限
                    tempNMCT.CorrespondingPeriod__c =  Date.valueOf(tempNMC.Contract_End_Date__c ).addMonths(2).toStartOfMonth().addDays(-1);
                    //及时率的统计区间范围  start
                    //及时率开始统计日
                    tempNMCT.TimelyRateStartDate__c = DistributionStartDate.addMonths(2);
                    //及时率结束统计日
                    tempNMCT.TimelyRateEndDate__c =  Date.valueOf(tempNMC.Contract_End_Date__c ).addMonths(2).toStartOfMonth().addDays(-1);
                    //及时率的统计区间范围  end
                    
                    }else {
                    //如果不用合并日期,这正常赋值                                             
                    //发放期间结束日期
                    tempNMCT.Distribution_End_Date__c = DistributionEndDate;
                    //发放期限
                    tempNMCT.CorrespondingPeriod__c =  DistributionEndDate.addMonths(1);

                    //及时率的统计区间范围  start
                    //及时率开始统计日
                    tempNMCT.TimelyRateStartDate__c = DistributionStartDate.addMonths(2);
                    //及时率结束统计日
                    tempNMCT.TimelyRateEndDate__c =  DistributionEndDate.addMonths(1);
                    //及时率的统计区间范围  end
                    }    

                    */

                    /*//如果为最后一个季度,则判断是否需要合并日期
                    if(NeedMergeDateMap.get(tempNMC.id)&&qnum == QuarterNumMap.get(tempNMC.Id)){
                    //如果需要合并日期,则结束日期赋值为  合同结束日期                       
                    //发放期间结束日期
                    tempNMCT.Distribution_End_Date__c = tempNMC.Contract_End_Date__c;
                    //对应期限
                    tempNMCT.CorrespondingPeriod__c =  tempNMC.Contract_End_Date__c;
                    }else {
                    //如果不用合并日期,这正常赋值 
                    } */                        

                    //发放期间结束日期
                    tempNMCT.Distribution_End_Date__c = DistributionEndDate;
                    //发放期限
                    tempNMCT.CorrespondingPeriod__c =  DistributionEndDate;    

                    //发放人
                    tempNMCT.Distribution_Person__c =  '';
                    //服务合同
                    tempNMCT.NewMaintenance_Contract__c = tempNMC.Id;

                    //2021-07-27  mzy  update   start
                    //如果季度的计划开始日 是 8月1日之前的,则需要将实际发放次数 = 1
                    Date riqi = Date.newInstance(2021,08,01);
                    if(DistributionStartDate <riqi){
                        tempNMCT.ActualDistributionTimes_Quarter__c = 1;
                    }
                    //2021-07-27  mzy  update    end


                    NMCReportTList.add(tempNMCT);
                }

            }


        }

        if(NMCReportTList.size()>0){
            insert NMCReportTList;

            /*Set<String> nmcid = new Set<String>();
            for(NewMaintenanceReport_Task__c m : NMCReportTList){
                nmcid.add(m.NewMaintenance_Contract__c);
            }

            List<Task__c> taskList = [SELECT Id , Activity_Date__c ,Maintenance_Contract__c  FROM TASK__c WHERE Maintenance_Contract__c in : nmcid 
                                    AND taskStatus__c = '03 完成' AND RecordType.DeveloperName  = 'SLAReport_Task'];
            for(NewMaintenanceReport_Task__c m :NMCReportTList){
                //及时率
                integer timelylv = 0;
                //发放次数
                integer grantCount = 0;

                if(taskList.size()>0){                    
                    for (Task__c t :taskList){
                        //判断本季度内有没有已经完成的任务，如果>=1，计划发放次数为1，发放及时率为100%；本季度目前没有已完成的任务，都为0
                        if(m.Distribution_Start_Date__c <= t.Activity_Date__c
                            && t.Activity_Date__c <= m.Distribution_End_Date__c
                            && t.Maintenance_Contract__c == m.NewMaintenance_Contract__c){
                            timelylv = 100;
                            grantCount = 1;
                        }
                    }
                }

                m.ActualDistributionTimes_Quarter__c = grantCount;
            }

            update NMCReportTList;*/

        }
        system.debug('execute 执行完了');
       /* if(!''.equals(log1.Log__c)){
            insert log1;
        }*/


    }

    global void finish(Database.BatchableContext BC) {

        //2021-07-12  mzy update start  SLA定期任务开发
        if(!System.Test.isRunningTest() && IsNeedExecute == true){
            Database.executebatch(new CreateSLAReportTaskBatch(true));
        }
        //2021-07-12  mzy  update end  SLA定期任务开发
    }
}