// 1.现在系统里的规则是:希望到货日前三天的草案中的OPD会发送邮件提醒。To出借担当 Cc备品助理;操作者
// 2.未提交审批的申请单邮件提醒，具体逻辑为希望到货日-7自然日，通过Batch来检索出这些申请单，然后给相应的担当和助理发邮件提醒
// 3.该逻辑加上之后OPD相关的申请单会收到两次提醒，其他备品借出申请单按原有逻辑提醒。

global class RentalApplyAutoDailyBatch implements Database.Batchable<sObject>,Database.Stateful {
    
    private Boolean checkTest = false;
    global RentalApplyAutoDailyBatch() {
        
    }
    global RentalApplyAutoDailyBatch(Boolean checkTest) {
        this.checkTest = true;
    }

    global Database.QueryLocator start(Database.BatchableContext bc) {
        
        // String query = 'SELECT Id, Status__c, Request_shipping_day__c, Person_In_Charge__r.Email, Rental_Assistant__r.Email from Rental_Apply__c WHERE Demo_purpose1__c = \'产品试用\' AND Status__c = \'草案中\' AND Request_shipping_day__c = NEXT_N_DAYS:7';
        String query = 'SELECT Id, Status__c, Request_shipping_day__c, Person_In_Charge__r.Email, Rental_Assistant__r.Email, Demo_purpose1__c,RecordType.DeveloperName from Rental_Apply__c WHERE Status__c != \'完了\' AND Status__c != \'取消\' AND Status__c != \'删除\' AND Demo_purpose1__c = \'产品试用\' AND Request_shipping_day__c = NEXT_N_DAYS:7';
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, list<Sobject> scope) {
        System.debug('scope====' + scope);
        
        List<Rental_Apply__c> raList = new List<Rental_Apply__c>();
        raList = scope;
        //今天日期
        Date today = Date.today();

        EmailTemplate et=[Select id from EmailTemplate where name =:'提醒草案中需要提交的申请' limit 1];
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
        List<String> raIdList = new List<String>();
        for(Rental_Apply__c ra : raList){
            //|| ra.Status__c == '申请中' || ra.Status__c == '申请中（OPD未通过）'
            if (ra.Status__c == '草案中'){
                //未提交审批的申请单邮件提醒，具体逻辑为希望到货日-7自然日，通过Batch来检索出这些申请单，然后给相应的担当和助理发邮件提醒
                System.debug(ra.Request_shipping_day__c + '====' + Date.today().addDays(7));
                System.debug('zyhtest==========='+(ra.Request_shipping_day__c <= Date.today().addDays(7)));
                if(ra.Request_shipping_day__c  == Date.today().addDays(7)){
                    List<String> ccEmails = new List<String>();
                    //发送邮件
                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                    mail = Messaging.renderStoredEmailTemplate(et.Id, null , ra.Id);
                    mail.setSaveAsActivity(false);
                    System.debug(ra.Person_In_Charge__r.Email + '====' + ra.Rental_Assistant__r.Email);
                    //To 备品出借担当  Cc 备品助理
                    if(ra.Person_In_Charge__r.Email != null){
                        mail.setToAddresses(new List<String>{ra.Person_In_Charge__r.Email,'sunxia@prec-tech.com'}); 
                    }
                    if(ra.Rental_Assistant__r.Email != null){
                        mail.setCcAddresses(new List<String>{ra.Rental_Assistant__r.Email});
                    }
                    emails.add(mail);
                }
                
            } else {
                // 希望到货日是七天内的 && 记录类型是备品申请的,自动分单
                //UAT注释
                // if(ra.Request_shipping_day__c <= Date.today().addDays(7) && ra.RecordType.DeveloperName == 'StandardRequest'){
                //     raIdList.add(ra.Id);
                // }
            }
        }
        if(emails.size()>0){
            Messaging.sendEmail(emails);
        }
        if(raIdList.size() > 0){
            //UAT注释 s
            //AuthRentalApplySplitController arasc = new AuthRentalApplySplitController(raIdList);
            //UAT注释 e
            // arasc.init(raIdList);
        }

    }

    global void finish(Database.BatchableContext BC) {
        //UAT注释
        System.debug('2023-12-09zyhfinish' + DateTime.now());
        if (checkTest == false && !Test.isRunningTest()) {  // 2024-1-3 zyh 测试判断
            Database.executeBatch( new AuthRentalApplyRepairBatch(),1);
        }
        // Database.executeBatch( new AuthRentalApplyRepairBatch(),1);
    }
    
}