global class ContactInstructCountNSetNullBatch implements Database.Batchable<sObject>, Database.Stateful {
    public String query;

    private Date today = Date.today();
    private Date mon1stDate  = Date.newInstance(today.year(), today.month(), 1);
    private Date monLastDate = mon1stDate.addMonths(1).addDays(-1);
    private Date lastMon1stDate = Date.newInstance(today.year(), today.month(), 1).addMonths(-1);
    private Date lastMonLastDate = mon1stDate.addDays(-1);
    private Integer month = today.month();
    private Boolean mon1stDateFlag =  today == mon1stDate;
    private Boolean april_11Flag = today == Date.newInstance(today.year(), 4, 11);

    global Integer totalCount = 0; // 总件数
    global Integer failedCount = 0;
    global List<String> emailMessages = new List<String>();

    global String specifiedYearMonth;
    global Integer specifiedMonth;

    Boolean IsNeedExecute = false; // 2021-03-03  mzy  WLIG-BYHD79  SFDC环境batch合并调查  是否符合执行条件
    global ContactInstructCountNSetNullBatch() {

    }
    //手动清空上一财年的数据
    global ContactInstructCountNSetNullBatch(Boolean april_11Flag) {
        this.april_11Flag = april_11Flag;
    }
    //没有实际用途，跑测试程序使用
    global ContactInstructCountNSetNullBatch(Integer month) {
        this.month = month;
    }

    //指定去跑某年某月数据
    global ContactInstructCountNSetNullBatch(String specifiedYearMonth) {

        this.specifiedYearMonth = specifiedYearMonth;
    }
    //2021-03-03  mzy  WLIG-BYHD79  SFDC环境batch合并调查  start
    global ContactInstructCountNSetNullBatch(Boolean tempNeedExecute , Boolean needExecute) {

        this.IsNeedExecute = needExecute;
    }
    //2021-03-03  mzy  WLIG-BYHD79  SFDC环境batch合并调查  end

    global Database.QueryLocator start(Database.BatchableContext bc) {
        //Integer specifiedMonth ;
        String query =
            ' Select Id,Name,Instruct_report__r.ReportDate__c,Instruct_report__r.Status__c,ContactID__c ';
        //query += ', ContactID__r.Instruct_Count1__c,ContactID__r.Instruct_Count2__c,';
        //query += ' ContactID__r.Instruct_Count3__c,ContactID__r.Instruct_Count4__c,';
        //query += ' ContactID__r.Instruct_Count5__c,ContactID__r.Instruct_Count6__c,';
        //query += ' ContactID__r.Instruct_Count7__c,ContactID__r.Instruct_Count8__c,';
        //query += ' ContactID__r.Instruct_Count9__c,ContactID__r.Instruct_Count10__c,';
        //query += ' ContactID__r.Instruct_Count11__c,ContactID__r.Instruct_Count12__c';
        query += ' from Instructed_staff__c ';
        query += ' where Instruct_report__r.Status__c = \'批准\'';

        if (april_11Flag) {

            query = sqlConditionspell(13, mon1stDateFlag, query);
        } else if (String.isNotBlank(specifiedYearMonth)) {

            specifiedMonth = Integer.valueOf(specifiedYearMonth.split(',')[1]);
            query = sqlConditionspell(specifiedMonth, mon1stDateFlag, query);
        } else {
            query = sqlConditionspell(month, mon1stDateFlag, query);
        }

        if (mon1stDateFlag) {
            query += ' AND Instruct_report__r.ReportDate__c >= :lastMon1stDate';
            query += ' AND Instruct_report__r.ReportDate__c <= :lastMonLastDate';
        } else if (String.isNotBlank(specifiedYearMonth)) {

            Integer specifiedYear = Integer.valueOf(specifiedYearMonth.split(',')[0]);
            Date startDate = Date.newInstance(specifiedYear, specifiedMonth, 1);
            Date endDate = startDate.addMonths(1).addDays(-1);
            system.debug('startDate--->' + startDate);
            system.debug('endDate--->' + endDate);
            query += ' AND Instruct_report__r.ReportDate__c >= :startDate';
            query += ' AND Instruct_report__r.ReportDate__c <= :endDate';
        } else {

            query += ' AND Instruct_report__r.ReportDate__c >= :mon1stDate';
            query += ' AND Instruct_report__r.ReportDate__c <= :monLastDate';
        }

        // 2021-03-03  mzy  WLIG-BYHD79  SFDC环境batch合并调查  start
        //  4月2日至4月10日外每天  不满足运行时间，可以使查询到的结果为空
        //Date mon1stDate = Date.newInstance(today.year(), today.month(), 1);
        Date inexecutionDateStart = Date.newInstance(today.year(), 4, 2);
        Date inexecutionDateEnd = Date.newInstance(today.year(), 4, 10);
        Boolean inexecutionDateFlag = (inexecutionDateStart <= today) &&  (today <= inexecutionDateEnd);
        System.debug('query__C : ' + inexecutionDateFlag + ' mon1stDate :' + mon1stDate + ' monLastDate :' + monLastDate);
        if (inexecutionDateFlag && IsNeedExecute == true) {
            query = 'Select Id from Instructed_staff__c where Name = \'\' AND Name != \'\' ';
        }
        //2021-03-03  mzy  WLIG-BYHD79  SFDC环境batch合并调查 end

        system.debug('query→→→SetNull' + query);
        System.debug(Database.getQueryLocator(query));
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, list<Instructed_staff__c> InstructedstaffList) {

        Map<Id, Contact> updateContactMap = new Map<Id, Contact>();
        system.debug('InstructedstaffList------->' + InstructedstaffList);
        Savepoint sp = Database.setSavepoint();
        totalCount += InstructedstaffList.size();
        try {
            for (Instructed_staff__c staff : InstructedstaffList) {
                Contact contact = new Contact();
                contact.Id = staff.ContactID__c;
                if (april_11Flag) {
                    //清空之前应该有一个备份
                    contact = StatisticsInstructedStaffBatch.updateInstruct_CountN(13, mon1stDateFlag, contact, 0);
                } else if (String.isNotBlank(specifiedYearMonth)) {
                    specifiedMonth = Integer.valueOf(specifiedYearMonth.split(',')[1]);
                    contact = StatisticsInstructedStaffBatch.updateInstruct_CountN(specifiedMonth, mon1stDateFlag, contact, 0);
                } else {
                    contact = StatisticsInstructedStaffBatch.updateInstruct_CountN(month, mon1stDateFlag, contact, 0);
                }
                updateContactMap.put((Id)staff.ContactID__c, contact);
            }

            if (updateContactMap.size() > 0) {

                update updateContactMap.values();
            }
        } catch (Exception e) {
            Database.rollback(sp);
            emailMessages.add(e.getMessage());
            System.debug(emailMessages);
            failedCount += InstructedstaffList.size();
            System.debug(failedCount);
        }

    }

    global void finish(Database.BatchableContext BC) {
        // sendFieldEmail();
        // 2021-03-03  mzy  WLIG-BYHD79  SFDC环境batch合并调查  start
        //  4月2日至4月10日外每天  不满足运行时间，可以使查询到的结果为空
        //Date mon1stDate = Date.newInstance(today.year(), today.month(), 1);
        Date inexecutionDateStart = Date.newInstance(today.year(), 4, 2);
        Date inexecutionDateEnd = Date.newInstance(today.year(), 4, 10);
        Boolean inexecutionDateFlag = (inexecutionDateStart <= today) &&  (today <= inexecutionDateEnd);
        System.debug('query__C : ' + inexecutionDateFlag + ' mon1stDate :' + mon1stDate + ' monLastDate :' + monLastDate);
        if ((inexecutionDateFlag && IsNeedExecute == true) || (IsNeedExecute == false)) {
            if (String.isNotBlank(specifiedYearMonth)) {
                Database.executebatch(new StatisticsInstructedStaffBatch(specifiedYearMonth, true), 100);
            } else {
                Database.executebatch(new StatisticsInstructedStaffBatch(), 100);
            }
        }
        //2021-03-03  mzy  WLIG-BYHD79  SFDC环境batch合并调查  start
        if (!Test.isRunningTest() && IsNeedExecute == true) {
            //batch里调用下一个batch时，希望跟原有的Schedule里面传的条数保持一致
            Id execBTId = Database.executebatch(new UpdateThreeMonthlyContactBatch(true), 50);
        }
        //2021-03-03  mzy  WLIG-BYHD79  SFDC环境batch合并调查 end


    }

    public void sendFieldEmail() {

        PretechBatchEmailUtil be = new PretechBatchEmailUtil();
        //String[] toList = new String[] {UserInfo.getUserEmail()};
        String[] toList = new String[] {'xinhonglu@prec-tech.com'};
        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();
        }
    }

    global static String sqlConditionspell(Integer month, Boolean mon1stDateFlag, String query) {

        switch on month {
        when 1 {
            if (mon1stDateFlag) {
                    query +=  ' AND  ContactID__r.Instruct_Count12__c != 0';
                } else {
                    query +=  ' AND  ContactID__r.Instruct_Count1__c != 0';
                }
            }
            when 2 {
                if (mon1stDateFlag) {
                    query +=  ' AND  ContactID__r.Instruct_Count1__c != 0';
                } else {
                    query +=  ' AND  ContactID__r.Instruct_Count2__c != 0';
                }
            }
            when 3 {
                if (mon1stDateFlag) {
                    query +=  ' AND  ContactID__r.Instruct_Count2__c != 0';
                } else {
                    query +=  ' AND  ContactID__r.Instruct_Count3__c != 0';
                }

            }
            when 4 {
                if (mon1stDateFlag) {
                    query +=  ' AND  ContactID__r.Instruct_Count3__c != 0';
                } else {
                    query +=  ' AND  ContactID__r.Instruct_Count4__c != 0';
                }

            }
            when 5 {
                if (mon1stDateFlag) {
                    query +=  ' AND  ContactID__r.Instruct_Count4__c != 0';
                } else {
                    query +=  ' AND  ContactID__r.Instruct_Count5__c != 0';
                }
            }
            when 6 {
                if (mon1stDateFlag) {
                    query +=  ' AND  ContactID__r.Instruct_Count5__c != 0';
                } else {
                    query +=  ' AND  ContactID__r.Instruct_Count6__c != 0';
                }

            }
            when 7 {
                if (mon1stDateFlag) {
                    query +=  ' AND  ContactID__r.Instruct_Count6__c != 0';
                } else {
                    query +=  ' AND  ContactID__r.Instruct_Count7__c != 0';
                }
            }
            when 8 {
                if (mon1stDateFlag) {
                    query +=  ' AND  ContactID__r.Instruct_Count7__c != 0';
                } else {
                    query +=  ' AND  ContactID__r.Instruct_Count8__c != 0';
                }
            }
            when 9 {
                if (mon1stDateFlag) {
                    query +=  ' AND  ContactID__r.Instruct_Count8__c != 0';
                } else {
                    query +=  ' AND  ContactID__r.Instruct_Count9__c != 0';
                }
            }
            when 10 {
                if (mon1stDateFlag) {
                    query +=  ' AND  ContactID__r.Instruct_Count9__c != 0';
                } else {
                    query +=  ' AND  ContactID__r.Instruct_Count10__c != 0';
                }
            }
            when 11 {
                if (mon1stDateFlag) {
                    query +=  ' AND  ContactID__r.Instruct_Count10__c != 0';
                } else {
                    query +=  ' AND  ContactID__r.Instruct_Count11__c != 0';
                }
            }
            when 12 {
                if (mon1stDateFlag) {
                    query +=  ' AND  ContactID__r.Instruct_Count11__c != 0';
                } else {
                    query +=  ' AND  ContactID__r.Instruct_Count12__c != 0';
                }
            }

            when 13 {
                query +=  ' AND  ( ';
                query +=  ' ContactID__r.Instruct_Count1__c  != 0 OR ContactID__r.Instruct_Count2__c  != 0 OR ';
                query +=  ' ContactID__r.Instruct_Count3__c  != 0 OR ContactID__r.Instruct_Count4__c  != 0 OR ';
                query +=  ' ContactID__r.Instruct_Count5__c  != 0 OR ContactID__r.Instruct_Count6__c  != 0 OR ';
                query +=  ' ContactID__r.Instruct_Count7__c  != 0 OR ContactID__r.Instruct_Count8__c  != 0 OR ';
                query +=  ' ContactID__r.Instruct_Count9__c  != 0 OR ContactID__r.Instruct_Count10__c  != 0 OR ';
                query +=  ' ContactID__r.Instruct_Count11__c != 0 OR ContactID__r.Instruct_Count12__c  != 0 ';
                query +=  ' )';
            }
        }

        return query;
    }
}