/**
 * 使用目的2为保修用户和市场多年保修的备品出借申请，在备品出库日之后的第7个工作日仍然没有将维修品送修的，则发送邮件提醒申请人注意该申请单的最新预定归还日信息。
 * 邮件内容为：您的备品出借申请单中的“最新预定归还日”可能在明天发生更新，请您及时关注申请单相关信息，并依据更新结果跟进备品回收管理“。
 * 邮件发送的时间应为备品出库日之后的第7个工作日的凌晨时段。
 * */
global class FinalReplyDayUpdateAlertBatch implements Schedulable, Database.Batchable<sObject>, Database.Stateful {

    public static List<String> statusList = new List<String>{
            '已出库', '申请者已收货', '申请者收货NG', '医院已装机确认'
    };

    global void execute(SchedulableContext sc) {
        Database.executeBatch(new FinalReplyDayUpdateAlertBatch());
    }

    global FinalReplyDayUpdateAlertBatch() {
    }

    global Database.QueryLocator start(Database.BatchableContext bc) {
        Date today = Date.today();
        return Database.getQueryLocator([
                SELECT Id, Bollow_Date_Add_7_WD__c, Rental_Apply__c, Rental_Apply__r.Person_In_Charge__r.Email 
                FROM Rental_Apply_Equipment_Set__c 
                WHERE Rental_Apply__r.DataMigration_Flag__c = FALSE
                AND Demo_purpose2__c IN ('保修用户','市场多年保修')
                AND Rental_Apply__r.RC_Ordered_Date__c = null
                AND Bollow_Date_Add_7_WD__c =: today
                AND Repair_Status_Text__c != '0.删除'
                AND Repair_Status_Text__c != '0.取消'
                AND RAES_Status__c IN: statusList
                ORDER BY Rental_Apply__c]);
    }

    global void execute(Database.BatchableContext BC, list<Rental_Apply_Equipment_Set__c> scope) {
		System.debug('scope====='+scope);
        EmailTemplate et = [Select Id from EmailTemplate where name = '最新预定归还日更新邮件提醒' limit 1];
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
        OrgWideEmailAddress[] owea = [select Id from OrgWideEmailAddress where Address = 'olympus@prec-tech.com'];

        String raId = null;
        Boolean isFirst = true;
        for (Rental_Apply_Equipment_Set__c raesObj : scope) {
            if (isFirst) {
                raId = raesObj.Rental_Apply__c;
            }

            // 同一申请单只发送一封邮件提醒
            if (isFirst || raId != raesObj.Rental_Apply__c) {
                String[] toAddresses = new List<String>{raesObj.Rental_Apply__r.Person_In_Charge__r.Email};
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                mail = Messaging.renderStoredEmailTemplate(et.Id, null, raesObj.Rental_Apply__c);
                mail.setSaveAsActivity(false);
                mail.setToAddresses(toAddresses);
                mail.setOrgWideEmailAddressId(owea.get(0).Id);
                emails.add(mail);
            }

            isFirst = false;
            raId = raesObj.Rental_Apply__c;
        }

        Messaging.sendEmail(emails);
    }

    global void finish(Database.BatchableContext BC) {
        if (!Test.isRunningTest()) {
            Database.executeBatch(new RentalApplyAutoDailyBatch(), 20);
            Integer num = Integer.valueOf(System.Label.AutoSplitNum);
            Database.executeBatch( new AuthRentalApplySplitBatch(System.Label.BeijingEmail),num);
            Database.executeBatch( new AuthRentalApplySplitBatch(System.Label.GuangzhouEmail),num);
            Database.executeBatch( new AuthRentalApplySplitBatch(System.Label.ShanghaiEmai),num);
        }
    }
}