package com.sys.bus.sys.task;

import com.jfinal.aop.Enhancer;
import com.jfinal.plugin.cron4j.ITask;
import com.sys.bus.jx.service.MailService;
import com.sys.bus.sys.model.DtBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

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

public class JxWfTask implements ITask {
	Log log = LogFactory.getLog(this.getClass());

	static boolean flag = false;//防重复调用
	static MailService mailService = Enhancer.enhance(MailService.class);
	public void run() {
		log.info("JxWfTask任务进行中。。。。");
		if(flag){
			log.error("JxWfTask任务进行中。。。。本次跳出任务");
			return;
		}

		flag = true;
		try{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			// 2 评分待处理的  当同一个员工 多个kpi对应一个审核人  只展示一条记录
			String sql1 =
					"select entry_cyclename,entry_khpersonname,entry_orgname,entry_apptime,entry_apptype,entry_id,entry_no,kpi_id as id,'2' as idType,'40' as type from " +
							"        (select *,row_number() over (partition by kpi_graderid order by kpi_entryid ) as group_idx from " +
							"                (select entry_id,entry_cyclename,entry_khpersonname,entry_orgname,entry_apptime,entry_no,entry_apptype,kpi_id,kpi_graderid,kpi_entryid" +
							"                from ct_jx_kpi kpi left  join ct_jx_entry entry on kpi.kpi_entryid = entry.entry_id where kpi.kpi_wf='1'  " +
							"             )  t) t1 where t1.group_idx = 1 ";

			//1 获取上级领导审批kpi待处理
			String sql2 = "select entry_cyclename,entry_khpersonname,entry_orgname,entry_apptime,entry_apptype,entry_id,entry_no,entry_id as id,'1' as idType,'20' as type from ct_jx_entry e where  e.entry_apptype = '6' ";
			String sql = "select * from  (" + sql1 + " union all " + sql2 + "  ) t ";
			List<DtBean> dtBeans = new DtBean().dao().find(sql);
			for (DtBean dtBean : dtBeans) {
				String idType = dtBean.getStr("idType");
				String id = dtBean.getStr("id");
				String type = dtBean.getStr("type");
				try{
					mailService.sendJxEmail(id,idType,type);
				}catch (Exception e){
					log.error("任务发送代办发送邮件失败！"+e.getMessage());
				}

			}
		}catch (Exception e){
			log.error("邮件任务失败1！",e);
		}finally {
			flag = false;
		}



	}


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

}
