global class InventorySendMailBatch implements Database.Batchable<sObject> , Database.Stateful{
	private boolean result;
	private string Errorstr;
	private string logstr;

    global InventorySendMailBatch() {
		this.result = true;
		this.Errorstr = '';
		this.logstr = '';
    }

    global Database.QueryLocator start(Database.BatchableContext BC) {
		if (Test.isRunningTest()) { 
			return Database.getQueryLocator(
				[select Id, Name, Email, Manager.Email from User where isActive = true and (ProfileId = :System.label.ProfileId_2S6 
					or ProfileId = :System.label.ProfileId_2S7 or ProfileId = :System.label.ProfileId_2S8) limit 1]
			);
		} else {
			return Database.getQueryLocator(
				[select Id, Name, Email, Manager.Email from User where isActive = true and (ProfileId = :System.label.ProfileId_2S6 
					or ProfileId = :System.label.ProfileId_2S7 or ProfileId = :System.label.ProfileId_2S8)]
			);
		}
				
    }

    global void execute(Database.BatchableContext BC, List<sObject> User) {
        List<User> UserList = User;
        Date toDate = Date.today();
        Integer day = Integer.valueOf(toDate.day());
        if(System.Test.isRunningTest()|| (UserList.size() > 0 && (day == 6 || day == 14))){
			sendMail(UserList);
        }	
    }

    global void finish(Database.BatchableContext BC) {
        saveResult();
    }

    public void saveResult() {
		BatchIF_Log__c iflog = new BatchIF_Log__c();
		iflog.Type__c = 'PushNotification';
		iflog.Log__c = 'InventorySendMailBatch start' + '\n';
		if (result) {
			iflog.Is_Error__c = 0;
			iflog.ErrorLog__c = '';
			if (logstr.length() > 65000) {
				logstr = logstr.substring(0, 65000);
				logstr += ' ...have more lines...';
			} 
			iflog.Log__c += '邮件成功发送\n end';
		} else {
			iflog.Is_Error__c = 1;
			if (Errorstr.length() > 65000) {
				Errorstr = Errorstr.substring(0, 65000);
				Errorstr += ' ...have more lines...';
			}
			if (logstr.length() > 65000) {
				logstr = logstr.substring(0, 65000);
				logstr += ' ...have more lines...';
			}
			iflog.Log__c += logstr;
			iflog.ErrorLog__c = Errorstr;
		}

		insert iflog;
    }

    public boolean sendMail(List<User> userList) {
		boolean rs = true;
		for(User user : userList){
			String title = '';
			String body = '';
			title = '【提醒】' + '办事处样本盘点工作的开展';
			body +=  user.Name + '您好：';
			body += '<br/>';
			body += '<br/>';
			body += '本月的样本盘点工作已经开始，请您及时进行样本盘点。<br/>';
			body += '若本月已经进行过样本盘点，还请忽略本邮件。<br/>';
			body += '<br/>';
			body += '<br/>';
			body += '谢谢！';
			//收件邮箱
			List<String> toMailList = new List<String>();
			toMailList.add(user.Email);
			//抄送的邮箱
			List<String> ccMailList = new List<String>();
			ccMailList.add(user.Manager.Email);
			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);

			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;
					Errorstr += 'sendMail error:' + results[i].errors[0].message + '\n';
					rs = false;
				}
			}
		}
		return rs;
    }
}