global class Email888AlarmBatch implements Database.Batchable<sObject> , Database.AllowsCallouts, Database.Stateful{
    public Date nowDate = Date.today();
    public Boolean sendEmailSuccess { get; set; }
    public Map<String,String> provinceMap { get; set; }

    global Email888AlarmBatch() {
        
        provinceMap = (Map<String,String>)JSON.deserialize(System.Label.ProvinceMapStr, Map<String,String>.class);
    }

    global Database.QueryLocator start(Database.BatchableContext bc) {
        /*String query = 'Select Id FROM Alarm_888_Month__c ';
        query += 'Where Alarm_Date__c = ' + nowDate;*/
        return Database.getQueryLocator([Select Id,Asset_ID__c FROM Alarm_888_Month__c  Where Nth_Operating_Day__c >=:nowDate AND Nth_Operating_Day__c <=:nowDate.addMonths(2)]);
    }

    global void execute(Database.BatchableContext BC,List<Alarm_888_Month__c> alarm888List) {
        System.debug(LoggingLevel.INFO, '*** alarm888List: ' + alarm888List);
        if (alarm888List.size() > 0) {
            //判断是否有数据
            List<Id>  assetIds= new List<Id>();
            for (Alarm_888_Month__c alarm888: alarm888List) {
                assetIds.add(alarm888.Asset_ID__c);
            }
            System.debug(LoggingLevel.INFO, '*** assetIds: ' + assetIds);
            //获取  
            List<Asset> assetData = [Select Id,Salesdepartment_Dept__c,OCSM_man_province_HP__c FROM Asset WHERE Id IN :assetIds];
            //发送大区，窗口，cc抄送领导
            Set<String> address = new Set<String>();
            Set<String> ccAddress = new Set<String>();
            System.debug(LoggingLevel.INFO, '*** assetData: ' + assetData);
            for (Asset asset: assetData) {
                //销售本部如果没有值
                if (asset.Salesdepartment_Dept__c.indexOf('.') == -1) {
                    continue;
                }
                String assetProvince = asset.Salesdepartment_Dept__c.split('\\.')[1];
                System.debug(LoggingLevel.INFO, '*** assetProvince: ' + assetProvince);
                if (assetProvince == '华东') {
                    ccAddress.add(provinceMap.get('赵伟'));
                    address.add(provinceMap.get('郭思琦'));
                }else if (assetProvince == '华南') {
                    String province = provinceMap.get(asset.OCSM_man_province_HP__c);
                    if (province != null) {
                        address.add(province);
                        ccAddress.add(provinceMap.get('位静'));
                    }
                }else if (assetProvince == '西南') {
                    address.add(provinceMap.get('西南'));
                    ccAddress.add(provinceMap.get('周卫东'));
                }else if (assetProvince == '华北') {
                    address.add(provinceMap.get('华北'));
                    ccAddress.add(provinceMap.get('孙燕'));
                }else if (assetProvince== '东北') {
                    address.add(provinceMap.get('东北'));
                    ccAddress.add(provinceMap.get('孙燕'));
                }else if (assetProvince== '西北') {
                    address.add(provinceMap.get('西北'));
                    ccAddress.add(provinceMap.get('宇文崇发'));
                }
            }
            List<String> addressList = new List<String>(address);
            List<String> ccAddressList = new List<String>(ccAddress);
            System.debug(LoggingLevel.INFO, '*** addressList: ' + addressList);
            System.debug(LoggingLevel.INFO, '*** ccaddressList: ' + ccAddressList);
            if (address.size() > 0 && ccAddress.size() > 0) {             
                //发送邮件  报表
                sendEmail(addressList,ccAddressList);
            }
        }
    }

    public PageReference sendEmail(List<String> address,List<String> ccAddress) {
        System.debug(LoggingLevel.INFO, '*** in sendEmail: '+address);
        System.debug(LoggingLevel.INFO, '*** in sendEmail: '+ccAddress);

        EmailTemplate temp =  [
            SELECT Id, Name, Subject, HtmlValue, Body, BrandTemplateId
            FROM EmailTemplate
            WHERE DeveloperName = 'Alarm888Email'
            LIMIT 1
            ];
        System.debug(LoggingLevel.INFO, '*** temp: '+ temp);

        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
         Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

            email = Messaging.renderStoredEmailTemplate(temp.Id, null, null);
            // email = Messaging.renderStoredEmailTemplate(temp.Id, null, this.estimate.Id);

            email.setTemplateId(temp.Id);
            email.setSaveAsActivity(false);
            email.setToAddresses(address);
            email.setCcAddresses(ccAddress);
            emails.add(email);
            System.debug(LoggingLevel.INFO, '*** email: ' + email);
        
        if(emails.size()>0){
            try{
                Messaging.sendEmail(emails);
                sendEmailSuccess = true;
                // System.debug(LoggingLevel.INFO, '*** sendEmail hasSendEmail: ' + hasSendEmail);
                System.debug(LoggingLevel.INFO, '*** sendEmailSuccess: ' + sendEmailSuccess);
                System.debug(LoggingLevel.INFO, '*** 邮件发送成功！: ');
            }catch(Exception e){
                System.debug(e.getMessage());
                sendEmailSuccess = false;
                System.debug(LoggingLevel.INFO, '*** 邮件发送失败，请联系管理员！ ');
            }
        }
        return null;
    }

    // public String getUserEmail(String userName){
    //     try {
    //         User u = [SELECT Id,Email FROM User WHERE Name =:userName];
    //         return u.Email+'.valid';
    //     }catch (Exception e) {
    //         return null;
    //     }
    // }
    

    global void finish(Database.BatchableContext BC) {

    }
}