package com.sys.bus.sys.task;

import com.jfinal.plugin.cron4j.ITask;
import com.jfplugin.mail.MailKit;
import com.sys.bus.model.Email;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class EmailTask implements ITask {
	Log log = LogFactory.getLog(this.getClass());
	static boolean flag = false;//防重复调用
	public void run() {
		if(!flag){
			log.info("进入 EmailTask 。。。。开始发邮件");
			flag = true;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Calendar c = Calendar.getInstance();
			c.add(Calendar.MINUTE, -120);
			String time = sdf.format(c.getTime());
			List<String> maillist = new ArrayList<String>();
			try {
				String sql = "SELECT * FROM CT_JX_EMAIL WHERE EMAIL_STATUS='0' and EMAIL_TIME>'"+time+"'";
				List<Email> list = Email.dao.find(sql);
				log.info("开始发送邮件 。。。。 共计："+list.size());
				for(Email email:list){
					try {
						String s = email.getEmailTo()+email.getEmailTitle();//同样主题 同样人  只收到1次
						if(!maillist.contains(s)){
							String[] to = email.getEmailTo().split(",");
							List<String> tolist = new ArrayList<>();
							for (int i = 1; i < to.length; i++) {
								tolist.add(to[i]);
							}
							MailKit.send(to[0],tolist, email.getEmailTitle(), email.getEmailText());
							log.info("邮件发送>"+email.getEmailTo());
							maillist.add(s);
						}
						email.setEmailStatus("1");
						email.update();
					} catch (Exception e) {
						log.error("邮件发送失败>"+email.getEmailTo(),e);
					}

				}
			} catch (Exception e) {
				log.error("邮件发送失败>",e);
			}finally{
				flag = false;
			}

		}else{
			log.error("EmailTask 任务进行中。。。。本次跳出任务");
		}
	}

	public void stop() {
		log.info("------EmailTask stop-------------");
	}

}
