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

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


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

    global String sendMail;
    global String specifiedYearMonth;
    global Integer specifiedMonth;
    global StatisticsInstructedStaffBatch() {
       
    }
    //执行上个月的最后一次执行入口
    global StatisticsInstructedStaffBatch(Boolean mon1stDateFlag) {
        this.mon1stDateFlag = mon1stDateFlag;
    }
    //发送报表链接出现错误，重新发送入口
    global StatisticsInstructedStaffBatch(String sendMailFlag) {
        this.sendMail = sendMailFlag;
    }

    global StatisticsInstructedStaffBatch(String specifiedYearMonth,Boolean  specified_YearMonth) {
        this.specifiedYearMonth = specifiedYearMonth;
    }

    global Database.QueryLocator start(Database.BatchableContext bc) {

        String query =
            ' Select Id,Name,Instruct_report__r.ReportDate__c,Instruct_report__r.Status__c,ContactID__c ';
        query += ' from Instructed_staff__c ';
        query += ' where Instruct_report__r.Status__c = \'批准\'';

        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]);
            specifiedMonth = Integer.valueOf(specifiedYearMonth.split(',')[1]);

            Date startDate = Date.newInstance(specifiedYear, specifiedMonth, 1);
            Date endDate = startDate.addMonths(1).addDays(-1);

            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';
        }
        system.debug('query→→→Staff' + query);
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, list<Instructed_staff__c> InstructedstaffList) {
        Savepoint sp = Database.setSavepoint();
        totalCount += InstructedstaffList.size();
        //totalCount += 1;
        
        Map<Id,Contact> updateContactMap = new Map<Id,Contact>();
        try {
            for (Instructed_staff__c staff : InstructedstaffList) {
                Contact contact = new Contact();
                contact.Id = staff.ContactID__c;
                if (String.isNotBlank(specifiedYearMonth)) {
                    contact = updateInstruct_CountN(specifiedMonth, mon1stDateFlag, contact, 1);
                } else {
                    system.debug('month--->'+month);
                    system.debug('mon1stDateFlag--->'+mon1stDateFlag);
                    system.debug('month--->'+month);
                    contact = updateInstruct_CountN(month, mon1stDateFlag, contact, 1);
                }

                updateContactMap.put((Id)staff.ContactID__c,contact);
            }

            if (updateContactMap.size() > 0) {
                system.debug('updateContactMap---->'+updateContactMap);
                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();
        Date today = Date.today();
        Boolean april_1Flag = today == Date.newInstance(today.year(), 4, 1);

        if (april_1Flag || 'sendMail'.equals(sendMail)) {

            if (!sendMail()) {
                system.debug('发送失败，请检查');
            }
        }

    }
    // 发送更新失败的消息
    private 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 Contact updateInstruct_CountN(Integer month, Boolean mon1stDateFlag, Contact contact, Integer SetNumber) {

        switch on month {
        when 1 {
            if (mon1stDateFlag) {
                    contact.Instruct_Count12__c = SetNumber;
                } else {
                    contact.Instruct_Count1__c = SetNumber;
                }
            }
            when 2 {
                if (mon1stDateFlag) {
                    contact.Instruct_Count1__c = SetNumber;
                } else {
                    contact.Instruct_Count2__c = SetNumber;
                }
            }
            when 3 {
                if (mon1stDateFlag) {
                    contact.Instruct_Count2__c = SetNumber;
                } else {
                    contact.Instruct_Count3__c = SetNumber;
                }

            }
            when 4 {
                if (mon1stDateFlag) {
                    contact.Instruct_Count3__c = SetNumber;
                } else {
                    contact.Instruct_Count4__c = SetNumber;
                }

            }
            when 5 {

                if (mon1stDateFlag) {
                    contact.Instruct_Count4__c = SetNumber;
                } else {
                    contact.Instruct_Count5__c = SetNumber;
                }
            }
            when 6 {
                if (mon1stDateFlag) {
                    contact.Instruct_Count5__c = SetNumber;
                } else {
                    contact.Instruct_Count6__c = SetNumber;
                }

            }
            when 7 {
                if (mon1stDateFlag) {
                    contact.Instruct_Count6__c = SetNumber;
                } else {
                    contact.Instruct_Count7__c = SetNumber;
                }
            }
            when 8 {
                if (mon1stDateFlag) {
                    contact.Instruct_Count7__c = SetNumber;
                } else {
                    contact.Instruct_Count8__c = SetNumber;
                }
            }
            when 9 {
                if (mon1stDateFlag) {
                    contact.Instruct_Count8__c = SetNumber;
                } else {
                    contact.Instruct_Count9__c = SetNumber;
                }
            }
            when 10 {
                if (mon1stDateFlag) {
                    contact.Instruct_Count9__c = SetNumber;
                } else {
                    contact.Instruct_Count10__c = SetNumber;
                }
            }
            when 11 {
                if (mon1stDateFlag) {
                    contact.Instruct_Count10__c = SetNumber;
                } else {
                    contact.Instruct_Count11__c = SetNumber;
                }
            }
            when 12 {
                if (mon1stDateFlag) {
                    contact.Instruct_Count11__c = SetNumber;
                } else {
                    contact.Instruct_Count12__c = SetNumber;
                }
            }
            when 13 {
                contact.Instruct_Count1__c  = SetNumber;
                contact.Instruct_Count2__c  = SetNumber;
                contact.Instruct_Count3__c  = SetNumber;
                contact.Instruct_Count4__c  = SetNumber;
                contact.Instruct_Count5__c  = SetNumber;
                contact.Instruct_Count6__c  = SetNumber;
                contact.Instruct_Count7__c  = SetNumber;
                contact.Instruct_Count8__c  = SetNumber;
                contact.Instruct_Count9__c  = SetNumber;
                contact.Instruct_Count10__c = SetNumber;
                contact.Instruct_Count11__c = SetNumber;
                contact.Instruct_Count12__c = SetNumber;
            }
        }
        system.debug('赋值之后的contact'+ contact);
        return contact;
    }

    public static boolean sendMail() {

        Boolean result = true;
        String title = '';
        String body = '';
        List<String> toMailList = new List<String>();
        List<String> ccMailList = new List<String>();
        List<String> statementIdList = new List<String>();
        Date today = Date.today();
        Integer NPnum = today.year() - 1 - 2004 + 137;

        //辛洪禄<xinhonglu@prec-tech.com>
        String  toMail = System.Label.toMail;
        ccMailList.add('xinhonglu@prec-tech.com');
        toMailList.add(toMail);
        
        //string query = 'select id , Email from user where id in (';
        //query += System.Label.contactPopulationReport.replaceall('\'', '\\\'') + ')';
        //List<user> toUserList = Database.Query(query);

        //for (user toUser : toUserList) {
        //    if (!String.isBlank(toUser.Email)) {
        //        toMailList.add(toUser.Email);
        //    }
        //}

        String NPnumP = NPnum + 'P';
        title = '您好,新的财年要开始了，请您将上一财年的客户人员的带教数相关的报表进行下载:';
        body += '以下报表为:' + NPnumP + '财年的客户人员带教相关报表,请在4月10日之前确认并下载。<br/>';
        body += '<br/>';
        for (String  nameAndId : System.Label.Statementlink.split(',')) {
            List<String> nameAndIdSplit = nameAndId.split(':');
            body += nameAndIdSplit[0] + ':报表链接：<a href="' + URL.getSalesforceBaseUrl().toExternalForm() + '/' + nameAndIdSplit[1] + '">' + URL.getSalesforceBaseUrl().toExternalForm() + '/' + nameAndIdSplit[1] + '</a><br/>';
        }



        List<Messaging.SingleEmailMessage> sendMails = new List<Messaging.SingleEmailMessage>();
        Messaging.SingleEmailMessage messageNEW = new Messaging.SingleEmailMessage();
        messageNEW.subject = title;
        messageNEW.htmlBody = body;
        messageNEW.setCharset('UTF-8');
        messageNEW.toAddresses = toMailList;
        messageNEW.ccAddresses = ccMailList;

        sendMails.add(messageNEW);
        if (sendMails.size() > 0) {
            Messaging.SendEmailResult[] results = messaging.sendEmail(sendMails);
            for (Integer i = 0; i < results.size(); i++) {
                if (results[i].success == false) {
                    system.debug('=====send mail error:' + results[i].errors[0].message);
                    result = false;
                }
            }
        }

        return result;

    }
}