package com.nms.server.service;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.nms.server.bean.ContactSetInfo;
import com.nms.server.bean.EmailInfo;
import com.nms.server.common.CommonResources;
import com.nms.server.common.Constants;
import com.nms.server.common.EmailTypeConstants;
import com.nms.server.dao.CommonDao;
import com.nms.server.util.SQLExecuteTimeoutException;

/**
 *  创建并保存邮件信息
 *  查询邮件信息并将邮件信息整理成单一邮件进行查询
 *  @date Feb 6, 2012 10:17:56 AM
 *	@author ZhangGang
 *
 */
public class EmailService {
	private final Logger logger = Logger.getLogger(EmailService.class);
	SimpleDateFormat format = new SimpleDateFormat(Constants.COMMON_DATE_FORMAT);
	private CommonDao dao = null;

	public EmailService(CommonDao dao){
		this.dao = dao;
	}
	
	public List<EmailInfo> getEmailInfoList(){
		String selectSql = "select et.id , et.to_address ,et.action_type ,et.action_desc ,et.action_ip ,to_char(et.action_date,'"+Constants.DB_DATE_FORMAT+"') action_date,et.content from email_table et where et.send_flag = ? order by et.to_address asc,et.action_type asc,et.action_desc asc,et.action_ip asc,et.action_date asc";
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("id");
		fields.add("to_address");
		fields.add("action_type");
		fields.add("action_desc");
		fields.add("action_ip");
		fields.add("action_date");
		fields.add("content");
		
		Object [] params = new Object[]{EmailTypeConstants.FLAG_SEND_LATER};
		List<EmailInfo> eiList = new LinkedList<EmailInfo>();
		try {
			ArrayList<Map<String, String>> mapsList = dao.dbSelect(selectSql, fields, EmailTypeConstants.FLAG_SEND_LATER);
			if(mapsList!=null && mapsList.size()>0){
				for(Map<String, String> maps : mapsList){
					EmailInfo ei = new EmailInfo();
					ei.setId(StringUtils.isEmpty(maps.get("id"))?null:Long.parseLong(maps.get("id")));
					ei.setToAddress(maps.get("to_address"));
					ei.setActionType(StringUtils.isEmpty(maps.get("action_type"))?null:Integer.parseInt(maps.get("action_type")));
					ei.setActionDesc(maps.get("action_desc"));
					ei.setActionIp(maps.get("action_ip"));
					ei.setActionDate(maps.get("action_date"));
					ei.setContent(maps.get("content"));
					eiList.add(ei);
				}
			}
		} catch (SQLException e) {
			logger.error("Failure of mail information query", e);
		}
		
		return eiList;
	}
	
	public String getEmailTypeDescByTypeValue(int type){
		switch (type) {
		
		case EmailTypeConstants.TYPE_DETECTION_INFO_RECOVER:
			return EmailTypeConstants.DESC_DETECTION_INFO_RECOVER;
		case EmailTypeConstants.TYPE_DETECTION_INFO_EXCEPTION:
			return EmailTypeConstants.DESC_DETECTION_INFO_EXCEPTION;
		case EmailTypeConstants.TYPE_DETECTION_INFO_TIMEOUT:
			return EmailTypeConstants.DESC_DETECTION_INFO_TIMEOUT;
			
		case EmailTypeConstants.TYPE_ALARM_INFO_EXCEPTION:
			return EmailTypeConstants.DESC_ALARM_INFO_EXCEPTION;
		case EmailTypeConstants.TYPE_ALARM_INFO_RECOVER:
			return EmailTypeConstants.DESC_ALARM_INFO_RECOVER;
			
		case EmailTypeConstants.TYPE_TASK_NODE_RESULT_ERROR:
			return EmailTypeConstants.DESC_TASK_NODE_RESULT_ERROR;
		case EmailTypeConstants.TYPE_TASK_STATE_CHANGE:
			return EmailTypeConstants.DESC_TASK_STATE_CHANGE;
			
		case EmailTypeConstants.TYPE_SYSTEM_RUNNING_EXCEPTION:
			return EmailTypeConstants.DESC_SYSTEM_RUNNING_EXCEPTION;
		case EmailTypeConstants.TYPE_SYSTEM_RUNNING_RECOVER:
			return EmailTypeConstants.DESC_SYSTEM_RUNNING_RECOVER;

		default:
			return null;
		}
		
	}
	public void sendEmailForDetectionBySeqId(Long dId,Long seqId,EmailInfo emailInfo){
		
		//-- 邮件功能是否开启
		if(Constants.flag_email != 1){
			logger.info("邮件功能已关闭");
			return;
		}
		
		//-- 数据校验 无效返回
		if(dId==null || dId.longValue() == 0l || seqId==null || seqId.longValue() == 0l){
			return;
		}
		
		//-- 查询联系人设置信息
		ContactSetInfo contactSetInfo  = this.getContactSetInfoByDetecId(dId);
		
		//-- 获取联系人列表
		List<EmailInfo> eiList = new LinkedList<EmailInfo>();
		List<String> emaiList = this.getEmailList(contactSetInfo, seqId);
		logger.debug("邮件数量 "+(emaiList==null?null:emaiList.size()));
		if(emaiList!=null && emaiList.size()>0){

			for (Iterator emailIte = emaiList.iterator(); emailIte.hasNext();) {
				String addr = (String) emailIte.next();
				if(StringUtils.isEmpty(addr))continue;		//邮件地址不为空
				EmailInfo emailInfo2 = new EmailInfo(emailInfo);
				emailInfo2.setToAddress(addr);
				eiList.add(emailInfo2);
			}
			
			try {
				saveEmailInfoList(eiList);
			} catch (SQLExecuteTimeoutException e) {
				logger.error("",e);
			} catch (SQLException e) {
				logger.error("",e);
			}
		}
	}
	
	public void sendEmailForMissionBySeqId(Long mId,int missionType,Long seqId,EmailInfo emailInfo){
		//-- 邮件功能是否开启
		if(Constants.flag_email != 1){
			logger.info("邮件功能已关闭");
			return;
		}
		
		//-- 数据校验 无效返回
		if(mId==null || mId.longValue() == 0l || missionType==0 || seqId==null || seqId.longValue() == 0l){
			return;
		}
		
		//-- 查询联系人设置信息
		ContactSetInfo contactSetInfo  = this.getContactSetInfoByMissionId(mId);
		
		//-- 获取联系人列表
		List<EmailInfo> eiList = new LinkedList<EmailInfo>();
		List<String> emaiList = this.getEmailList(contactSetInfo, seqId);
		logger.debug("邮件数量 "+(emaiList==null?null:emaiList.size()));
		
		//-- 发邮件
		if(emaiList!=null && emaiList.size()>0){

			for (Iterator emailIte = emaiList.iterator(); emailIte.hasNext();) {
				String addr = (String) emailIte.next();
				if(StringUtils.isEmpty(addr))continue;
				EmailInfo emailInfo2 = new EmailInfo(emailInfo);
				emailInfo2.setToAddress(addr);
				eiList.add(emailInfo2);
			}
		}
		
		try {
			saveEmailInfoList(eiList);
		} catch (SQLExecuteTimeoutException e) {
			logger.error("",e);
		} catch (SQLException e) {
			logger.error("",e);
		}
		//-结束
	}
	
	/**
	 * 任务执行邮件通知方法
	 * 任务类型 1 根据 系统 用户组 指定用户处理
	 * 任务类型 4 根据 系统 用户组 指定用户处理
	 * 任务类型 6 根据 下发机器 的管理用户发送通知
	 * @time Mar 28, 2012-1:53:56 PM
	 * @param mission	任务信息
	 * @param emaiTitle	主题
	 * @param emailContext	内容
	 */
	public void sendEmailForMission(Long missionId,String emaiTitle,String emailContext){
		//-- 邮件功能是否开启
		if(Constants.flag_email != 1){
			logger.info("邮件功能已关闭");
			return;
		}
		
		//-- 参数校验
		if(missionId==null || StringUtils.isEmpty(emaiTitle) || StringUtils.isEmpty(emailContext)){
			return;
		}
		
		ContactSetInfo info = this.getContactSetInfoByMissionId(missionId);
		LinkedList<String> emailList = null;
		
		ResourceBundle res = ResourceBundle.getBundle(CommonResources.class.getName());
//		ContactSetInfo info = getContactSetInfoByMissionId(mId,mType);
		String startTime = "";
		String endTime = "";
		if(info.getStartTime()!=null){
			startTime = format.format(info.getStartTime());
		}
		if(info.getEndTime()!=null){
			endTime = format.format(info.getEndTime());
		}
		
		String sendInfo = "";
		
		if(info.getMissionType().longValue()==4l){
//			sendInfo += " \n周期任务：" +(info.getIsLoop()==null?"否":(info.getIsLoop().longValue()==1l?"是":"否"));
//			sendInfo +=  " \n计划执行时间：" +  startTime+" -- "+endTime;
//			sendInfo += " \nPeriodic Task：" +(info.getIsLoop()==null?"No":(info.getIsLoop().longValue()==1l?"Yes":"No"));
//			sendInfo +=  " \nPlan Execution Time：" +  startTime+" -- "+endTime;
			sendInfo += " \ni18n_server.EmailService.loopMission_n81i：" +(info.getIsLoop()==null?"i18n_server.EmailService.no_n81i":(info.getIsLoop().longValue()==1l?"i18n_server.EmailService.yes_n81i":"i18n_server.EmailService.no_n81i"));
			sendInfo +=  " \ni18n_server.EmailService.plantime_n81i：" +  startTime+" -- "+endTime;
		}
//		sendInfo += " \n任务状态：" + res.getObject("ms_"+info.getMissionState().intValue())
//		+ " \n节点组：" + info.getNodeGroupName()
//		+ " \n节点：" + info.getNodeIpsName()
//		+ " \n" + emailContext;
//		sendInfo += " \nTask state：" + res.getObject("ms_"+info.getMissionState().intValue())
//		+ " \nNode Group：" + info.getNodeGroupName()
//		+ " \nNode：" + info.getNodeIpsName()
//		+ " \n" + emailContext;
		sendInfo += " \ni18n_server.EmailService.missionState_n81i：" + res.getObject("ms_"+info.getMissionState().intValue())
		+ " \ni18n_server.EmailService.nodegroup_n81i：" + info.getNodeGroupName()
		+ " \ni18n_server.EmailService.node_n81i：" + info.getNodeIpsName()
		+ " \n" + emailContext;
		
		EmailInfo emailInfo = new EmailInfo();
		emailInfo.setActionDesc(info.getMissionName()+"("+res.getObject("mt_"+info.getMissionType().longValue())+")");
		emailInfo.setActionDate(new SimpleDateFormat(Constants.COMMON_DATE_FORMAT).format(new Date()));
		emailInfo.setActionType(EmailTypeConstants.TYPE_TASK_STATE_CHANGE);
		emailInfo.setSendFlag(EmailTypeConstants.FLAG_SEND_LATER);
		emailInfo.setContent(sendInfo);
		emailInfo.setSendLevel(EmailTypeConstants.URGENT_IMMEDIATELY);//2013-6-24 hyx 任务状态改变由不紧急修改为紧急
		//- 发送邮件业务
		try {
			//-- 查询联系人参数过滤
			switch (info.getMissionType().intValue()) {
			case 6:
				info.setViewLevel(3l);	// 升级部署 通知均为系统内通知
				emailList = getEmailList(info, null);
				break;
			default:	//任务1 任务4 均按原有业务发送邮件
				emailList = getEmailList(info, null);
				break;
			}
			logger.debug("邮件数量 "+(emailList==null?null:emailList.size()));
			
			//-- 发送邮件
			List<EmailInfo> eiList = new LinkedList<EmailInfo>();
			if(emailList !=null && emailList.size()>0){
				for (Iterator emailIte = emailList.iterator(); emailIte.hasNext();) {
					String addr = (String) emailIte.next();
					if(StringUtils.isEmpty(addr))continue;
					EmailInfo emailInfo2 = new EmailInfo(emailInfo);
					emailInfo2.setToAddress(addr);
					eiList.add(emailInfo2);

				}

				saveEmailInfoList(eiList);

			}
			
		} catch (Exception e) {
			logger.error("",e);
		}
		logger.info("任务下发 邮件通知 发送完成");
		
		//-结束
	}
	
	public boolean saveEmailInfoList(List<EmailInfo> eiList) throws SQLExecuteTimeoutException,SQLException {
		
		String insertSql = " insert into email_table (to_address,action_type,content,send_flag,action_ip,action_date,action_desc,send_level,CREATE_TIME)" +
				" values(?,?,?,?,?,to_date(?,'"+Constants.DB_DATE_FORMAT+"'),?,?,to_date(?,'"+Constants.DB_DATE_FORMAT+"'))" ;
		List<String[]> paramsList = new LinkedList<String[]>();
		if(eiList != null && eiList.size()>0){
			String createTime = format.format(new Date());
			for(EmailInfo ei :eiList){
				paramsList.add(new String[]{ei.getToAddress(),ei.getActionType()+"",ei.getContent(),ei.getSendFlag()+"",ei.getActionIp(),ei.getActionDate(),ei.getActionDesc(),/*ei.getActionDesc2(),*/ei.getSendLevel()==null?EmailTypeConstants.URGENT_LATER+"":ei.getSendLevel()+"",createTime});
			}
			return dao.dbUpdateByBatch(insertSql, paramsList);
		}
		return false;
	}
	
	/*private void sendEmailForDetectionBySeqId(Long dId,Long seqId,String emaiTitle,String emailContext){

		//-- 数据校验 无效返回
		if(dId==null || dId.longValue() == 0l || seqId==null || seqId.longValue() == 0l){
			return;
		}
		//-- 查询联系人设置信息
		ContactSetInfo contactSetInfo  = this.getContactSetInfoByDetecId(dId);
		//-- 获取联系人列表
		List<String> emaiList = this.getEmailList(contactSetInfo, seqId);
		logger.debug("邮件数量 "+(emaiList==null?null:emaiList.size()));
		//-- 发邮件
		if(emaiList!=null && emaiList.size()>0){
			SendMail cn = new SendMail();
			for (Iterator emailIte = emaiList.iterator(); emailIte.hasNext();) {
				String addr = (String) emailIte.next();
				if(StringUtils.isEmpty(addr))continue;
				logger.debug("邮件 To "+(addr));
				 // 设置发件人地址、收件人地址和邮件标题
				 cn.setAddress(Constants.EMAIL_ADDRESS, addr, emaiTitle);
				 cn.send(emailContext);
			}
		}
		//-结束
	}*/
	
	
	
	/*private void sendEmailForMissionBySeqId(Long mId,int missionType,Long seqId,String emaiTitle,String emailContext){

		//-- 数据校验 无效返回
		if(mId==null || mId.longValue() == 0l || missionType==0 || seqId==null || seqId.longValue() == 0l){
			return;
		}
		//-- 查询联系人设置信息
		ContactSetInfo contactSetInfo  = this.getContactSetInfoByMissionId(mId);
		//-- 获取联系人列表
		List<String> emaiList = this.getEmailList(contactSetInfo, seqId);
		logger.debug("邮件数量 "+(emaiList==null?null:emaiList.size()));
		//-- 发邮件
		if(emaiList!=null && emaiList.size()>0){
			SendMail cn = new SendMail();
			for (Iterator emailIte = emaiList.iterator(); emailIte.hasNext();) {
				String addr = (String) emailIte.next();
				if(StringUtils.isEmpty(addr))continue;
				logger.debug("邮件 To "+(addr));
				// 设置发件人地址、收件人地址和邮件标题
				cn.setAddress(Constants.EMAIL_ADDRESS, addr, emaiTitle);
				cn.send(emailContext);
			}
		}
		//-结束
	}*/
	
	/**
	 * 任务执行邮件通知方法
	 * 任务类型 1 根据 系统 用户组 指定用户处理
	 * 任务类型 4 根据 系统 用户组 指定用户处理
	 * 任务类型 6 根据 下发机器 的管理用户发送通知
	 * @time Mar 28, 2012-1:53:56 PM
	 * @param mission	任务信息
	 * @param emaiTitle	主题
	 * @param emailContext	内容
	 */
	/*private void sendEmailForMission(Long missionId,String emaiTitle,String emailContext){

		//-- 参数校验
		if(missionId==null || StringUtils.isEmpty(emaiTitle) || StringUtils.isEmpty(emailContext)){
			return;
		}
		ContactSetInfo info = this.getContactSetInfoByMissionId(missionId);
		LinkedList<String> emailList = null;
		
		ResourceBundle res = ResourceBundle.getBundle(CommonResources.class.getName());
//		ContactSetInfo info = getContactSetInfoByMissionId(mId,mType);
		String startTime = "";
		String endTime = "";
		if(info.getStartTime()!=null){
			startTime = format.format(info.getStartTime());
		}
		if(info.getEndTime()!=null){
			endTime = format.format(info.getEndTime());
		}
		
		String sendInfo = "任务名称："+info.getMissionName()
		+ " \n任务类型：" + res.getObject("mt_"+info.getMissionType().longValue());
		
		if(info.getMissionType().longValue()==4l){
			sendInfo += " \n周期任务：" +(info.getIsLoop()==null?"否":(info.getIsLoop().longValue()==1l?"是":"否"));
		}
		sendInfo += " \n任务状态：" + res.getObject("ms_"+info.getMissionState().intValue());
		sendInfo +=  " \n计划执行时间：" +  startTime+" -- "+endTime
		+ " \n节点组：" + info.getNodeGroupName()
		+ " \n节点：" + info.getNodeIpsName()
		+ " \n" + emailContext;
		
		//- 发送邮件业务
		try {
			//-- 查询联系人参数过滤
			switch (info.getMissionType().intValue()) {
			case 6:
				info.setViewLevel(3l);	// 升级部署 通知均为系统内通知
				emailList = getEmailList(info, null);
				break;
			default:	//任务1 任务4 均按原有业务发送邮件
				emailList = getEmailList(info, null);
				break;
			}
			logger.debug("邮件数量 "+(emailList==null?null:emailList.size()));
			
			//-- 发送邮件
			if(emailList !=null && emailList.size()>0){
				SendMail cn = new SendMail();
				for (Iterator emailIte = emailList.iterator(); emailIte.hasNext();) {
					String addr = (String) emailIte.next();
					if(StringUtils.isEmpty(addr))continue;
					logger.debug("邮件 To "+(addr));
					// 设置发件人地址、收件人地址和邮件标题
					cn.setAddress(Constants.EMAIL_ADDRESS, addr, emaiTitle);
					cn.send(sendInfo);
				}
			}
		} catch (Exception e) {
			logger.error("",e);
		}
		logger.info("任务下发 邮件通知 发送完成");
		
		//-结束
	}*/
	
	private LinkedList<String> getEmailList(ContactSetInfo contactSetInfo,Long seqId) {
		LinkedList<String> emailList = new LinkedList<String>();
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("email");
			if(contactSetInfo!=null && contactSetInfo.getViewLevel()!=null){
				try {
					if(contactSetInfo.getViewLevel().intValue()==1){	//个人查看	邮件发送给 创建者
						String sql1 = "select distinct xyj.email from xt_yh_jbxx xyj where xyj.yhid = '"+contactSetInfo.getCreateUserId()+"' and xyj.is_receiveemail='0' ";
						List<Map<String, String>> map1 = (List<Map<String, String>>)dao.dbSelect(sql1, fields);
						if(map1 != null && map1.size()>0){
							emailList.add(map1.get(0).get("email"));
						}
					}else {		//非个人
						//-- 无限制 或 未指定联系人情况
						if(contactSetInfo.getViewLevel().intValue()==4 || (contactSetInfo.getContactUserIds()==null || contactSetInfo.getContactUserIds().length()==0)){
							/**
							 * 查询seqId所在的系统
							 * 系统关联的用户维护组的有效维护人员接收邮件信息
							 * */
							StringBuffer selectSql = new StringBuffer();
							selectSql.append("select distinct xyj.email ");
							selectSql.append("from xt_yh_jbxx xyj ");
							selectSql.append("left join xt_yh_js_index xyji on xyji.yhid = xyj.yhid ");
							selectSql.append("left join xt_js_jbxx xjj on xjj.jsbh = xyji.jsbh ");
							selectSql.append("left join gorup_system_table gst on gst.user_group_id = xjj.jsbh ");
							selectSql.append("left join system_table st on st.system_id = gst.system_id ");
							selectSql.append("left join node_table nt on nt.system_id = gst.system_id ");
							selectSql.append("left join nodegroup_table ngt on ngt.group_id = nt.node_group_id ");
							selectSql.append("where xyj.is_receiveemail='0' ");
							
							selectSql.append("and nt.node_state = 0 ");		//  节点有效状态 0有效
							selectSql.append("and ngt.is_valid = 1 ");		//  节点组有效状态 1有效
							selectSql.append("and st.system_state  = 0 ");		//  系统有效状态 0有效
							selectSql.append("and xjj.zxbz = 0 ");		//  用户组有效状态 0有效
							selectSql.append("and xjj.type = 1 ");		//  组类别状态 1是用户组 0是角色
							selectSql.append("and xyj.zxbz = 0 ");		//  用户有效状态 0 有效
							if(seqId != null && seqId.longValue() != 0){
								selectSql.append("and nt.seq_id = "+seqId);		
							}
							//-- 无限制 情况
							if(contactSetInfo.getViewLevel().intValue()==4){	
								
							}else
							//-- 系统内 情况
								if(contactSetInfo.getViewLevel().intValue()==3){
								selectSql.append("and nt.system_id = '"+contactSetInfo.getSystemId()+"' ");
							}else 
							//-- 组内 情况
								if(contactSetInfo.getViewLevel().intValue()==2){
								selectSql.append("and xjj.jsbh =  '"+contactSetInfo.getCreateUserGroupId()+"' "); 
							}
							List<Map<String, String>> mapList = (List<Map<String, String>>) dao.dbSelect(selectSql.toString(), fields);
							if(mapList != null && mapList.size()>0){
								for (Iterator<Map<String,String>> mapIte = mapList.iterator(); mapIte.hasNext();) {
									Map<String,String> map = mapIte.next();
									emailList.add(map.get("email"));
								}
							}
						}
						//-- 组或系统内指定联系人情况
						else{
							String sql0 = "select distinct xyj.email from xt_yh_jbxx xyj where xyj.yhid in ("+contactSetInfo.getContactUserIds()+") ";
							List<Map<String, String>> map0List = (List<Map<String, String>>)dao.dbSelect(sql0, fields);
							if(map0List != null && map0List.size()>0){
								for (Iterator<Map<String,String>> map0Ite = map0List.iterator(); map0Ite.hasNext();) {
									Map<String,String> map0 = map0Ite.next();
									emailList.add(map0.get("email"));
								}
							}
						}
					}
				} catch (Exception e) {
					logger.error(" Fail to query the list of email addresses to be sent to failure",e);
				}finally{
					dao.clearConn();
				}
			}
		 
		return emailList;
	}
	
	private ContactSetInfo getContactSetInfoByDetecId(Long dId){
		ContactSetInfo contactSetInfo = null;
		StringBuffer selectSql = new StringBuffer();
		selectSql.append("select ");
		selectSql.append("dsi.view_level, ");
		selectSql.append("dsi.create_user_id, ");
		selectSql.append("dsi.create_usergroup_id, ");
		selectSql.append("dsi.system_id, ");
		selectSql.append("dsi.contact_user_ids ");
		selectSql.append("from detection_set_info dsi where dsi.id= '"+dId+"' ");
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("view_level");
		fields.add("create_user_id");
		fields.add("create_usergroup_id");
		fields.add("system_id");
		fields.add("contact_user_ids");
		try {
			ArrayList<Map<String, String>> mapList = dao.dbSelect(selectSql.toString(), fields);
			if(mapList!=null && mapList.size()>0){
				Map<String, String> map0 = mapList.get(0);
				 contactSetInfo = new ContactSetInfo();
				 contactSetInfo.setViewLevel(map0.get("view_level")==null?null:Long.parseLong(map0.get("view_level")));
				 contactSetInfo.setCreateUserId(map0.get("create_user_id")==null?null:Long.parseLong(map0.get("create_user_id")));
				 contactSetInfo.setCreateUserGroupId(map0.get("create_usergroup_id")==null?null:Long.parseLong(map0.get("create_usergroup_id")));
				 contactSetInfo.setSystemId(map0.get("system_id")==null?null:Long.parseLong(map0.get("system_id")));
				 contactSetInfo.setContactUserIds(map0.get("contact_user_ids"));
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return contactSetInfo;
	}
		
	private ContactSetInfo getContactSetInfoByMissionId(Long mId){
		ContactSetInfo contactSetInfo = null;
		StringBuffer selectSql = new StringBuffer();
		selectSql.append("select ");
		selectSql.append("mst.mission_id, ");
		selectSql.append("mst.mission_name, ");
//		selectSql.append("ngt.group_name node_group_name, ");
//		selectSql.append("mpt.node_groups_id, ");
//		selectSql.append("mpt.node_ips_id, ");
		selectSql.append("mst.mission_type, ");
		selectSql.append("mst.mission_state, ");
		selectSql.append("mst.is_loop , ");
		selectSql.append("to_char(mst.start_time,'"+Constants.DB_DATE_FORMAT+"' ) start_time, ");
		selectSql.append("to_char(mst.end_time,'"+Constants.DB_DATE_FORMAT+"' ) end_time, ");
		selectSql.append("mst.view_level, ");
		selectSql.append("mst.user_id, ");
		selectSql.append("mst.group_id, ");
		selectSql.append("mst.system_id, ");
		selectSql.append("mst.contact_user_ids ");
		selectSql.append("from mission_state_table mst ");
//		selectSql.append("left join mission_parameter_table"+missionType+" mpt on mpt.mission_id = mst.mission_id ");
//		selectSql.append("left join nodegroup_table ngt on ngt.group_id = mpt.node_groups_id ");
		selectSql.append("where mst.mission_id= '"+mId+"' ");
		
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("mission_id");
		fields.add("mission_name");
//		fields.add("node_groups_id");
//		fields.add("node_ips_id");
		fields.add("mission_type");
		fields.add("mission_state");
		fields.add("is_loop");
		fields.add("start_time");
		fields.add("end_time");
		fields.add("view_level");
		fields.add("user_id");
		fields.add("group_id");
		fields.add("system_id");
		fields.add("contact_user_ids");
		try {
			ArrayList<Map<String, String>> mapList = dao.dbSelect(selectSql.toString(), fields);
			if(mapList!=null && mapList.size()>0){
				Map<String, String> map = mapList.get(0);
				 contactSetInfo = new ContactSetInfo();
				 contactSetInfo.setMissionId(map.get("mission_id")==null?null:Long.parseLong(map.get("mission_id")));
				 contactSetInfo.setMissionName(map.get("mission_name"));
				 contactSetInfo.setMissionType(map.get("mission_type")==null?null:Long.parseLong(map.get("mission_type")));
				 contactSetInfo.setMissionState(map.get("mission_state")==null?null:Long.parseLong(map.get("mission_state")));
				 contactSetInfo.setIsLoop(map.get("is_loop")==null?null:Long.parseLong(map.get("is_loop")));
				 contactSetInfo.setStartTime(map.get("start_time")==null?null:format.parse(map.get("start_time")));
				 contactSetInfo.setEndTime(map.get("end_time")==null?null:format.parse(map.get("end_time")));
				 contactSetInfo.setViewLevel(map.get("view_level")==null?null:Long.parseLong(map.get("view_level")));
				 contactSetInfo.setCreateUserId(map.get("user_id")==null?null:Long.parseLong(map.get("user_id")));
				 contactSetInfo.setCreateUserGroupId(map.get("group_id")==null?null:Long.parseLong(map.get("group_id")));
				 contactSetInfo.setSystemId(map.get("system_id")==null?null:Long.parseLong(map.get("system_id")));
				 contactSetInfo.setContactUserIds(map.get("contact_user_ids"));
				 
				 ArrayList<String> paramsFields = new ArrayList<String>();
				 paramsFields.add("node_groups_id");
				 paramsFields.add("node_ips_id");
				 String paramsSql = "select mpt.node_groups_id,mpt.node_ips_id from mission_parameter_table"+contactSetInfo.getMissionType().intValue()+" mpt where mpt.mission_id=?";
				 ArrayList<Map<String, String>> paramsMapList = dao.dbSelect(paramsSql.toString(), paramsFields,mId);
				 
				 if(paramsMapList!= null && paramsMapList.size()>0){
					 Map<String, String> map0 = paramsMapList.get(0);
					 contactSetInfo.setNodeGroupsId(map0.get("node_groups_id"));
					 contactSetInfo.setNodeIpsId(map0.get("node_ips_id"));
				 }
			}
			
			
			
			//节点组和节点名称填写
			if(contactSetInfo!= null){
				if(contactSetInfo.getNodeGroupsId()!= null){
					//查询节点组名称
					ArrayList<String> ngnFields = new ArrayList<String>();
					ngnFields.add("group_name");
					String ngNameSql = "select ngt.group_name from nodegroup_table ngt where ngt.group_id in ("+contactSetInfo.getNodeGroupsId()+")";
					ArrayList<Map<String, String>> ngnMapList = dao.dbSelect(ngNameSql.toString(), ngnFields);
					if(ngnMapList != null && ngnMapList.size()>0){
						StringBuffer ngnsb = new StringBuffer();
						for(Map<String, String> map : ngnMapList){
							ngnsb.append(","+map.get(ngnFields.get(0)));
						}
						if(ngnsb.length()>0){
							ngnsb.deleteCharAt(0);
						}
						contactSetInfo.setNodeGroupName(ngnsb.toString());
					}
					
					//查询节点名称
					ArrayList<String> nnFields = new ArrayList<String>();
					nnFields.add("node_name");
					String nnNameSql = null;
					ArrayList<Map<String, String>> nnMapList = null;
					if(contactSetInfo.getNodeIpsId()!= null){
						nnNameSql = "select nt.node_name from node_table nt where nt.node_id in ("+contactSetInfo.getNodeIpsId()+")";
						nnMapList = dao.dbSelect(nnNameSql.toString(), nnFields);
					}else{
						nnNameSql = "select nt.node_name from node_table nt where nt.node_group_id in ("+contactSetInfo.getNodeGroupsId()+") ";
						if(contactSetInfo.getIsLoop()==null || contactSetInfo.getIsLoop()==0){	//非周期任务
							nnNameSql += "and nt.seq_id in (select mrt.seq_id from mission_result_table"+contactSetInfo.getMissionType()+" mrt where mrt.mission_id=?)";
						}else{	//周期任务
							nnNameSql += "and nt.seq_id in (select distinct mrt.seq_id from mission_result_table4 mrt where mrt.mission_id in (select lmst.cur_mission_id from loopmission_state_table lmst where lmst.mission_id=?))";
						}
						nnMapList = dao.dbSelect(nnNameSql.toString(), nnFields,mId);
					}
					if(nnMapList != null && nnMapList.size()>0){
						StringBuffer nnsb = new StringBuffer();
						for(Map<String, String> map : nnMapList){
							nnsb.append(","+map.get(nnFields.get(0)));
						}
						if(nnsb.length()>0){
							nnsb.deleteCharAt(0);
						}
						contactSetInfo.setNodeIpsName(nnsb.toString());
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			dao.clearConn();
		}
		return contactSetInfo;
	}
	
	public static void main(String [] args){
		CommonDao dao = null;
		try {
			dao = new CommonDao();
			EmailService emailService = new EmailService(dao);
			EmailInfo  emailInfo = new EmailInfo(11,"测试名称","10.0.6.113",new SimpleDateFormat(Constants.COMMON_DATE_FORMAT).format(new Date()),"这是一条关于监测设置的测试信息",EmailTypeConstants.FLAG_SEND_LATER,EmailTypeConstants.URGENT_LATER);
			//113监测邮件测试
			Constants.flag_email = 1;
//			emailService.sendEmailForDetectionBySeqId(2570l, 85l, emailInfo);
//			EmailInfo  emailInfo2 = new EmailInfo(31,"任务XXX","10.0.6.113",new SimpleDateFormat(Constants.COMMON_DATE_FORMAT).format(new Date()),"这是一条关于任务结果的测试信息",0);
//			emailService.sendEmailForMissionBySeqId(2570l, 6, 85l, emailInfo2);
			emailService.sendEmailForMission(2570l, "任务XXX", "这是一条关于任务状态的测试信息");
			
			pl("测试邮件入库完毕");
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(dao!=null){
				dao.close();
				dao=null;
			}
		}
		
	}
	private static void pl(Object object) {
		System.out.println(object==null?null:object.toString());
	}
}
