/*2021-04-29  mzy  sla报告书任务
   查询当前季度实际发放次数为0的服务合同报告书任务
   当前季度是否有sla主动任务,
   没有的话则在 季度开始日 + 30日  生成被动任务
*/
global class CreateSLAReportTaskBatch implements Database.Batchable<sObject> {
    public String tempMainId;
    //public Date today = Date.newInstance(2021,04,31);
    //public Date today = Date.today();
    Boolean IsNeedExecute = false;

    BatchIF_log__c log1 = new BatchIF_Log__c();

    public CreateSLAReportTaskBatch() {
    }
    public CreateSLAReportTaskBatch(String tempMainId) {
        this.tempMainId = tempMainId;
    }
    public CreateSLAReportTaskBatch(Boolean NeedExecute) {
        this.IsNeedExecute = NeedExecute;
    }
    public CreateSLAReportTaskBatch(String id ,Boolean NeedExecute){
        this.tempMainId = id;
        this.IsNeedExecute = NeedExecute;
    }
    
    global Database.QueryLocator start(Database.BatchableContext bc) {
        Date today30ago = Date.today().addDays(-30);
        String query = 'SELECT Id ,Distribution_Start_Date__c,Distribution_End_Date__c,NewMaintenance_Contract__c , '
                     + ' NewMaintenance_Contract__r.Service_Contract_Staff__c, NewMaintenance_Contract__r.Department__c , '
                     + ' NewMaintenance_Contract__r.Department__r.Name,NewMaintenance_Contract__r.Service_Contract_Staff__r.IsActive  '
                     + 'FROM NewMaintenanceReport_Task__c  '
                     + 'WHERE Distribution_Start_Date__c = :today30ago AND (ActualDistributionTimes_Quarter__c=0 or ActualDistributionTimes_Quarter__c = null)';
            if (String.isNotBlank(this.tempMainId)) {
               query  += 'AND Id = :tempMainId';
            }
            
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, list<NewMaintenanceReport_Task__c> NMCReportT) {

        log1.Type__c='SLAReport_Task';
        log1.Log__c = 'Batch  execute  start';
        log1.Log__c += '\r\n 查询结果 :'+NMCReportT;

        //定义变量 ---- start
        //定义变量保存今天时间
        Date today = Date.today();
        //定义变量保存记录类型
        Id SLAReport_TaskId = Schema.SObjectType.task__c.getRecordTypeInfosByDeveloperName().get('SLAReport_Task').getRecordTypeId();
        //定义变量保存这一季度合同的Id
        List<String> NMCId = new List<String>();
        //定义变量保存需要更新的报告书
        List<NewMaintenanceReport_Task__c> NeedUpdateReport = new List<NewMaintenanceReport_Task__c>();
        //定义变量保存需要生成的任务
        List<Task__c> NeedInsertTask = new List<Task__c>();        
        //定义Map保存服务合同报告书   k:合同Id v:报告书
        Map<String,NewMaintenanceReport_Task__c> NMCReportMap = new Map<String,NewMaintenanceReport_Task__c>();
        //定义变量 ---- end
        
        for(NewMaintenanceReport_Task__c tempMCT :NMCReportT){
            NMCId.add(tempMCT.NewMaintenance_Contract__c);
            NMCReportMap.put(tempMCT.NewMaintenance_Contract__c , tempMCT);
        }   

        //查询这一季度合同的所有任务
        List<Task__c> taskList = [SELECT Id,Maintenance_Contract__c,Activity_Date__c,taskStatus__c FROM task__c 
                                    WHERE taskDifferent__c = '主动任务' 
                                    AND RecordType.DeveloperName  = 'SLAReport_Task'
                                    AND Maintenance_Contract__c in :NMCId 
                                    ORDER BY Activity_Date__c DESC];

        //筛选这一季度 没有SLA主动任务的服务合同报告书
        log1.Log__c += '\r\n 任务集合 start:'+taskList +'\r\n' ;
        if(taskList.size()>0){
            for(task__c t : taskList){
                String mcid = t.Maintenance_Contract__c;
                NewMaintenanceReport_Task__c NMRt = NMCReportMap.get(mcid) == null ? new NewMaintenanceReport_Task__c() : NMCReportMap.get(mcid);
                if(NMRt.Distribution_Start_Date__c <= t.Activity_Date__c 
                    && t.Activity_Date__c <= NMRt.Distribution_End_Date__c){
                    //拜访日期是今天之前
                    if(t.Activity_Date__c <today){
                        //如果状态不是 延期 取消 未执行 则不需要发送被动任务
                        if(t.taskStatus__c != '05 延期' && t.taskStatus__c != '04 取消' && t.taskStatus__c != '07 未执行'){               
                            //不需要生成被动任务
                            NMCReportMap.remove(mcid);
                        }
                    }else if(today <t.Activity_Date__c){                        
                    //今天之后,本季度结束日期
                        //如果状态是 接受,则不需要发送被动任务
                        if(t.taskStatus__c == '02 接受'){
                            //不需要生成被动任务
                            NMCReportMap.remove(mcid);
                        } 
                    }
                }
            }
        }

        //季度开始日期 + 30
        /* for(NewMaintenanceReport_Task__c tempMCT : NMCReportMap.values()){
            if(tempMCT.Distribution_Start_Date__c.addDays(30) != today){
                //今天不需要生成被动任务
                NMCReportMap.remove(tempMCT.NewMaintenance_Contract__c);
            }
        }
        */
        log1.Log__c += '\r\n NMCReportMap :'+NMCReportMap ;
        //遍历报告书map
        for(NewMaintenanceReport_Task__c tempMCT : NMCReportMap.values()){
            //生成任务
            if(tempMCT.NewMaintenance_Contract__r.Service_Contract_Staff__r.IsActive){//2021-08-30 yjk 增加逻辑：任务的用户必须为Active
                Task__c tempTask = new Task__c();
                tempTask.RecordTypeId = SLAReport_TaskId;
                tempTask.taskDifferent__c = '被动任务';
                tempTask.taskStatus__c = '01 分配';
                tempTask.Maintenance_Contract__c = tempMCT.NewMaintenance_Contract__c;
                tempTask.assignee__c = tempMCT.NewMaintenance_Contract__r.Service_Contract_Staff__c;
                tempTask.account__c = tempMCT.NewMaintenance_Contract__r.Department__c;
                tempTask.Name = '服务合同发放报告书任务（' + tempMCT.NewMaintenance_Contract__r.Department__r.Name + '）';
                tempTask.OwnerId = tempMCT.NewMaintenance_Contract__r.Service_Contract_Staff__c;
                tempTask.NewMaintenanceReport_Task__c = tempMCT.Id;
                NeedInsertTask.add(tempTask);
            }
        }


        if(NeedInsertTask.size()>0){
            insert NeedInsertTask;
            log1.Log__c += '\r\n 任务 :'+NeedInsertTask ;
           //更新报告书 
            for(NewMaintenanceReport_Task__c tempMCT : NMCReportMap.values()){
               tempMCT.Is_Generate_Task__c = true;

               NeedUpdateReport.add(tempMCT);
           }

           update NeedUpdateReport;
            
           log1.Log__c += '\r\n 报告书 :'+NeedUpdateReport ;
        }

       // insert log1;
    }

    global void finish(Database.BatchableContext BC) {

        //2021-07-12  mzy update start  SLA定期任务开发
        //更新 已过或当前季度标识
        if(!System.Test.isRunningTest() && IsNeedExecute == true){
            Database.executebatch(new UpdateNewMaintenanceTaskBatch(true));
        }
        //2021-07-12  mzy  update end  SLA定期任务开发

    }
}