/*
 *  这个batch的运行是为了给下月所有工作日创建空日报一览
 *  创建空日报条件为：
 *  （1） 职种为 销售推广、 销售市场 或 销售服务 且 职位 为一般 、 高级 或 主管 的用户；
 *   (2)  只就工作日创建空日报。
 *   batch运行参数：
 *  1）如果什么都不输，就创建符合条件的日报
 *  2）如果参数为 1 个string, 则认为其为用户ID,则创建该用户符合条件的日报
 *  3）如果参数为 List<string>, 则认为其为用户ID 的List,则创建这些用户符合条件的日报
 *  4）如果参数为两个Date, 则创建 所有符合条件的用户，以第一个日期开始，第二个日期前一天为结束，创建空日报
 */


global class createEmptyDailyReportBatch implements Database.Batchable<sObject> , Database.Stateful {
  String userID;
  Date StartDate;
  Date endDate;
  list<String> userIDList;
  global List<String> emailMessages = new List<String>();
  global Integer totalCount = 0; // 总件数
  global Integer failedCount = 0;
    // Boolean ebFlag = false;
  global createEmptyDailyReportBatch() {
    // ebFlag = true;
  }
  //判定只要有参数就是手动执行,生成空日报
  //yuxiaolin 2020/11/4 start
  global createEmptyDailyReportBatch(Integer eb) {
    
  }
  //yuxiaolin 2020/11/4 end
  global createEmptyDailyReportBatch(Date StartDate, Date endDate) {
    this.StartDate = StartDate;
    this.endDate = endDate;
  }
  global createEmptyDailyReportBatch(String userID) {
    this.userID = userID;
  }
  global createEmptyDailyReportBatch(List<String> userIDList) {
    this.userIDList = userIDList;
  }
    global createEmptyDailyReportBatch(List<String> userIDList,Date StartDate, Date endDate) {
    this.userIDList = userIDList;
        this.StartDate = StartDate;
    this.endDate = endDate;
  }
  global Database.QueryLocator start(Database.BatchableContext BC) {
    /*  string query = 'select id from user where IsActive = true and ' +
               '(Job_Category__c = \'销售推广\' or Job_Category__c = \'销售市场\' or Job_Category__c = \'销售服务\') and ' +
               '(Post__c = \'一般\' or Post__c = \'高级\' or Post__c = \'主管\') and ' +
               'ProfileId not in ( \'00e10000000tiVV\', \'00e10000000NawV\', ' +
               ' \'00e10000000tiSh\' , \'00e1000000121A3\'  , \'00e10000000NbA3\' '
               + ' , \'00e10000000NbC9\' , \'00e10000000tk6N\' )  ';
               */
    //WLIG-BUR5Y4 yuxiaolin 2020/10/27 start
    string query = 'select id from user where IsActive = true and ' +
                   '(Job_Category__c = \'销售推广\' or Job_Category__c = \'销售市场\' or Job_Category__c = \'销售服务\') and ' +
                   '((Post__c = \'一般\' or Post__c = \'高级\' or Post__c = \'主管\') or ((Post__c = \'经理\' or Post__c  = \'部长\' or Post__c  = \'副部长\'or Post__c  = \'副经理\') and (Salesdepartment__c = \'5.华东\' or Salesdepartment__c = \'6.华南\'))) and ' +
                   'ProfileId not in ( '+System.label.emptyDaily_1+', '+System.label.emptyDaily_2+', ' +
                   System.label.emptyDaily_3+' , '+System.label.emptyDaily_4+'  , '+System.label.emptyDaily_5+ ', '+System.label.emptyDaily_6+' , '+System.label.emptyDaily_7+ ')  ';
     //WLIG-BUR5Y4 yuxiaolin 2020/10/27  end  niwu 00e10000000NawV-emptyDaily_2  00e10000000tiSh -emptyDaily_3 00e1000000121A3-emptyDaily_4  00e10000000NbA3 -emptyDaily_5 00e10000000NbC9 -emptyDaily_6  00e10000000tk6N - emptyDaily_7
    if (!System.Test.isrunningTest()) {
      query += ' and id != \''+System.label.emptyDaily_8+'\' ';//niwu -00510000005sEEM
    }

    if (!string.isblank(userID)) {
      query += ' and id = :userID ';
    }

    if (userIDList != null) {
      query += ' and id in: userIDList ';
    }
    system.debug('id');
    return Database.getQueryLocator(query);
  }
  global void execute(Database.BatchableContext BC, List<User> userList) {
    date NextfirstDate = Date.today().toStartOfMonth().addMonths(1);
    date Next2firstDate = Date.today().toStartOfMonth().addMonths(2);
    totalCount ++;
    Savepoint sp = Database.setSavepoint();
    try {
      if (StartDate != null && endDate != null) {
        NextfirstDate = StartDate;
        Next2firstDate = endDate;
      }

      List<id> UserIdList = new list<ID>();
      for (User tempUser : userList) {
        UserIdList.add(tempUser.id);
      }
      List<Daily_Report__c> existDRList =
          [select id, Daily_Report_Key__c   from Daily_Report__c
           where Reporter__c in: UserIdList and
           Reported_Date__c >= :NextfirstDate and
           Reported_Date__c < : Next2firstDate
          ];

      map<String, Daily_Report__c> ExistDRmap = new map<String, Daily_Report__c>();

      for (Daily_Report__c tempDR : existDRList) {
        ExistDRmap.put(tempDR.Daily_Report_Key__c
                       , tempDR);
      }
      list<Date> NextMonthWorkDateList = getNextMonthWorkDay(StartDate, endDate);
      List<Daily_Report__c> insertedDRList = new List<Daily_Report__c>();
      for (ID tempID : UserIdList) {
        for (Date tempDate : NextMonthWorkDateList ) {
          if (!ExistDRmap.containsKey( tempDate.format().ReplaceAll('/', '-')
                                       + ('' + tempID).substring(0, 15) )
             ) {
            insertedDRList.add(createDR(tempID, tempDate));
          }
        }
      }
      if (insertedDRList.size() > 0) {
        insert insertedDRList;
      }
      if (System.Test.isrunningTest()) {
        throw new ControllerUtil.myException('test。');
      }
    } catch (Exception e) {
      Database.rollback(sp);
      emailMessages.add(e.getMessage());
      System.debug(emailMessages);
      failedCount += userList.size();
      System.debug(failedCount);

    }



  }
  public static List<Date> getNextMonthWorkDay(date NextfirstDate, date Next2firstDate ) {
    List<Date> tempDateList = new List<Date>();
    if (NextfirstDate == null) {
      NextfirstDate = Date.today().toStartOfMonth().addMonths(1);
    } if (Next2firstDate == null) {
      Next2firstDate = Date.today().toStartOfMonth().addMonths(2);
    }
    List<OlympusCalendar__c> workday =
        [
            select Id, Date__c, IsWorkDay__c
            from OlympusCalendar__c
            where Date__c >= :NextfirstDate and
            Date__c < : Next2firstDate
            and IsWorkDay__c = 1
                               order by Date__c];
    for (OlympusCalendar__c tempOlyDate : workday) {
      tempDateList.add(tempOlyDate.Date__c);
    }

    return tempDateList;

  }
  private Daily_Report__c createDR( id userId, Date reportDate) {

    Daily_Report__c report = new Daily_Report__c();
    report.Reporter__c = userId;
    report.Status__c = '作成中';
    report.Daily_Report_Data_Type__c = '通常';
    report.Reported_Date__c = reportDate;
    report.Working_Time_From__c =
        Datetime.newInstance(reportDate.year(),
                             reportDate.month(),
                             reportDate.day(), 8, 45, 0);
    report.Working_Time_To__c =
        Datetime.newInstance(reportDate.year(),
                             reportDate.month(),
                             reportDate.day(),
                             17, 30, 0);
    report.OwnerId = userId;
    return report;
  }
  global void finish(Database.BatchableContext BC) {
    sendFieldEmail();
    // if(!test.isRunningTest() && ebFlag == true){
    //  Database.executebatch(new CreatePassiveTaskBatch(), 10);
    // }
  }
  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);
      be.send();
    }
        

  }
}