package com.nms.server.service;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

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

import com.nms.server.bean.EmailInfo;
import com.nms.server.bean.LoopMissionRoundInfo;
import com.nms.server.bean.MissionResult;
import com.nms.server.bean.MissionResult2;
import com.nms.server.bean.MissionStateTable;
import com.nms.server.bean.Task1;
import com.nms.server.bean.Task4;
import com.nms.server.bean.Task6;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.common.EmailTypeConstants;
import com.nms.server.common.MissionConstants;
import com.nms.server.dao.CommonDao;
import com.nms.server.thread.mission.NMSClientTask4Cancel;
import com.nms.server.util.BoneCPPool;
import com.nms.server.util.DateUtil;
import com.nms.server.util.MD5Util;
import com.nms.server.util.socket.SocketUtils;
import com.socket.utils.FileComment;


public class UpgradeService extends CommonService{
	private final Logger logger = Logger.getLogger(UpgradeService.class);
	private final SimpleDateFormat format = new SimpleDateFormat(Constants.COMMON_DATE_FORMAT);		//Java Date 类型数据格式化格式
//	private CommonDao dao = null;
	public UpgradeService(CommonDao dao){
		super(dao);
//		this.dao = dao;
	}
	/**
	 * 获取新任务信息，加载到 任务执行操作中
	 * @time Mar 23, 2012-3:28:41 PM
	 * @param missionId 为空时，不指定missionId查询
	 * @return
	 */
	public ArrayList<MissionStateTable> getNewMessionList(Long missionId){
		//-- 查询可执行的任务
		StringBuffer searchSQL = new StringBuffer();
		searchSQL.append("select mst.mission_id,");
		searchSQL.append("mst.mission_type,");
		searchSQL.append("mst.mission_state,");
		searchSQL.append("mst.system_id,");
		searchSQL.append("mst.group_id,");
		searchSQL.append("to_char(mst.start_time,'"+Constants.DB_DATE_FORMAT+"') start_time,");
		searchSQL.append("to_char(mst.end_time,'"+Constants.DB_DATE_FORMAT+"') end_time,");
		searchSQL.append("mst.is_loop,");
		searchSQL.append("mst.loop_delay ");
		searchSQL.append("from mission_state_table mst ");
		searchSQL.append("where 1=1 ");
		//2012-03-20 取消任务时间过滤，将对所有任务进行处理 
//		searchSQL.append("and (mst.end_time>sysdate or mst.end_time is null) ");// 周期任务（未过时）  or  非周期任务
		if (missionId!=null && missionId.longValue() !=0l) {
			searchSQL.append("and mst.mission_id = '"+missionId.longValue()+"' ");
		}else{
			searchSQL.append("and mst.mission_state in (1,5) ");	//以创建任务 准备撤销任务 均作为新任务周期性载入
		}
		searchSQL.append("order by mst.create_time,mst.mission_id asc ");
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("mission_id");
		fields.add("mission_type");
		fields.add("mission_state");
		fields.add("system_id");
		fields.add("group_id");
		fields.add("start_time");
		fields.add("end_time");
		fields.add("is_loop");
		fields.add("loop_delay");
		ArrayList<Map<String, String>> rs = null;
		ArrayList<MissionStateTable> mstList = new ArrayList<MissionStateTable>();
		try {
			rs = dao.dbSelect(searchSQL.toString(), fields);
			if(rs!=null && rs.size()>0){
				for(Map<String, String> maps : rs){
					MissionStateTable mission = new MissionStateTable();
//					mission.setMissionName(maps.get("mission_name"));
					mission.setMissionId(StringUtils.isEmpty(maps.get("mission_id"))?null:Long.parseLong(maps.get("mission_id")));
					mission.setMissionType(StringUtils.isEmpty(maps.get("mission_type"))?null:Long.parseLong(maps.get("mission_type")) );
					mission.setMissionState(StringUtils.isEmpty(maps.get("mission_state"))?null:Long.parseLong(maps.get("mission_state")));
					mission.setSystemId(StringUtils.isEmpty(maps.get("system_id"))?null:Long.parseLong(maps.get("system_id")));
					mission.setGroupId(StringUtils.isEmpty(maps.get("group_id"))?null:Long.parseLong(maps.get("group_id")));
					mission.setStartTime(StringUtils.isEmpty(maps.get("start_time"))?null:format.parse(maps.get("start_time")));
					mission.setEndTime(StringUtils.isEmpty(maps.get("end_time"))?null:format.parse(maps.get("end_time")));
					mission.setLoopFlag(StringUtils.isEmpty(maps.get("is_loop"))?null:Long.parseLong(maps.get("is_loop")));
					mission.setLoopDelay(StringUtils.isEmpty(maps.get("loop_delay"))?null:Long.parseLong(maps.get("loop_delay")));
					mstList.add(mission);
				}
			}
			return mstList;
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return mstList;
	}
	
	/**
	 * 获取正在执行状态的任务
	 * 用于任务下发线程初始化操作
	 * @time Mar 23, 2012-3:28:05 PM
	 * @param ids
	 * @return
	 */
	public ArrayList<MissionStateTable> getStartMessionList(String ids){
		//-- 查询可执行的任务
		StringBuffer searchSQL = new StringBuffer();
		searchSQL.append("select mst.mission_id,");
		searchSQL.append("mst.mission_type,");
		searchSQL.append("mst.mission_state,");
		searchSQL.append("mst.system_id,");
		searchSQL.append("mst.group_id,");
		searchSQL.append("to_char(mst.start_time,'"+Constants.DB_DATE_FORMAT+"') start_time,");
		searchSQL.append("to_char(mst.end_time,'"+Constants.DB_DATE_FORMAT+"') end_time,");
		searchSQL.append("mst.is_loop,");
		searchSQL.append("mst.loop_delay ");
		searchSQL.append("from mission_state_table mst ");
		searchSQL.append("where 1=1 ");
//		searchSQL.append("and (mst.end_time>sysdate or mst.end_time is null) ");
		searchSQL.append("and mst.mission_state in(2,6) ");	
		if(StringUtils.isNotEmpty(ids)){
			searchSQL.append("and mst.mission_id in ("+ids+") ");
		}
		searchSQL.append("order by mst.create_time,mst.mission_id asc ");
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("mission_id");
		fields.add("mission_type");
		fields.add("mission_state");
		fields.add("system_id");
		fields.add("group_id");
		fields.add("start_time");
		fields.add("end_time");
		fields.add("is_loop");
		fields.add("loop_delay");
		ArrayList<Map<String, String>> rs = null;
		ArrayList<MissionStateTable> mstList = new ArrayList<MissionStateTable>();
		try {
			rs = dao.dbSelect(searchSQL.toString(), fields);
			if(rs!=null && rs.size()>0){
				for(Map<String, String> maps : rs){
					MissionStateTable mission = new MissionStateTable();
					mission.setMissionId(StringUtils.isEmpty(maps.get("mission_id"))?null:Long.parseLong(maps.get("mission_id")));
					mission.setMissionType(StringUtils.isEmpty(maps.get("mission_type"))?null:Long.parseLong(maps.get("mission_type")) );
					mission.setMissionState(StringUtils.isEmpty(maps.get("mission_state"))?null:Long.parseLong(maps.get("mission_state")));
					mission.setSystemId(StringUtils.isEmpty(maps.get("system_id"))?null:Long.parseLong(maps.get("system_id")));
					mission.setGroupId(StringUtils.isEmpty(maps.get("group_id"))?null:Long.parseLong(maps.get("group_id")));
					mission.setStartTime(StringUtils.isEmpty(maps.get("start_time"))?null:format.parse(maps.get("start_time")));
					mission.setEndTime(StringUtils.isEmpty(maps.get("end_time"))?null:format.parse(maps.get("end_time")));
					mission.setLoopFlag(StringUtils.isEmpty(maps.get("is_loop"))?null:Long.parseLong(maps.get("is_loop")));
					mission.setLoopDelay(StringUtils.isEmpty(maps.get("loop_delay"))?null:Long.parseLong(maps.get("loop_delay")));
					mstList.add(mission);
				}
			}
			return mstList;
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return mstList;
	}	
	

	public JSONArray getMissionForAgentStart(Long uuid){
		try{
			if(uuid==null || uuid.longValue() == 0l){
				return null;
			}
			StringBuffer groupsIdsSQL = new StringBuffer();
			//当节点组不为空时，查询该节点组的叶子节点组及其父系节点组ID		
			if(uuid != null ){
				//--正向查询SQL 查询相关叶子节点组
				StringBuffer groupsIdsSQLN = new StringBuffer();
				groupsIdsSQLN.append("select nt.node_group_id from NODE_TABLE nt where 1=1 ");
				groupsIdsSQLN.append("and nt.seq_id = "+uuid+" and nt.node_state=0 ");
				
				//--逆向查询SQL 查询包括叶子节点组在内的父节点组
//				StringBuffer groupsIdsSQLW = new StringBuffer();
//				groupsIdsSQLW.append("select distinct ngt.group_id from NODEGROUP_TABLE ngt ");
//				groupsIdsSQLW.append("start with ngt.group_id in ( ");
//				groupsIdsSQLW.append(groupsIdsSQLN);
//				groupsIdsSQLW.append(") connect by prior  ngt.parent_group_id = ngt.group_id ");
//				groupsIdsSQL.append(groupsIdsSQLW);
				//@2018年4月26日15:56:55 适配mysql 数据库
				String groupIds = dao.startWithConnectByReverse("NODEGROUP_TABLE", null, "group_id in ( " + groupsIdsSQLN.toString() +" ) ", "group_id", "parent_group_id");
				groupsIdsSQL.append(groupIds);
				
				
			}
			
			String missionSql4 = "select distinct t.mission_id from v_mission_node_group_4 t where t.node_group_id in ("+groupsIdsSQL+")";
			String missionSql6 = "select distinct t.mission_id from v_mission_node_group_6 t where t.node_group_id in ("+groupsIdsSQL+")";
			JSONArray infoArray = new JSONArray();
			ArrayList<String> fields = new ArrayList<String>();
			StringBuffer searchSql = new StringBuffer();
			ArrayList<Map<String, String>> mapsList = new ArrayList<Map<String,String>>();
			//-- Task4 For once Mission
			mapsList.clear();
			fields.clear();
			fields.add("mission_id");
			fields.add("mission_type");
			fields.add("command_type");
			fields.add("command_ename");
			fields.add("command_para");
			fields.add("start_time");
			fields.add("end_time");
			fields.add("result");
			fields.add("version");
			searchSql.delete(0, searchSql.length());
			searchSql.append("select t.mission_id,t.mission_type,to_char(t.start_time,'"+Constants.DB_DATE_FORMAT+"') start_time,to_char(t.end_time,'"+Constants.DB_DATE_FORMAT+"') end_time, ");
			searchSql.append("mpt4.command_type, mpt4.command_ename, mpt4.command_para, mrt4.result,mpt4.version ");
			searchSql.append("from mission_state_table t ");
			searchSql.append("left join mission_parameter_table4 mpt4 on t.mission_id = mpt4.mission_id ");
			searchSql.append("left join mission_result_table4 mrt4 on mrt4.mission_id = mpt4.mission_id ");
//			searchSql.append("left join node_table nt on nt.node_group_id = mpt4.node_group_id and nt.system_id = t.system_id ");
			searchSql.append("where (t.end_time>sysdate or t.end_time is null) ");
			searchSql.append("and t.mission_state =2 ");
			searchSql.append("and t.is_loop =0 ");		//非周期任务
//			searchSql.append("and mpt4.node_group_id in( "+groupsIdsSQL+") ");
			searchSql.append("and mpt4.mission_id in( "+missionSql4+") ");
			searchSql.append("and mrt4.result >= 40 ");
			searchSql.append("and mrt4.seq_id ="+uuid+" ");
			searchSql.append("order by t.create_time asc ");
			mapsList = dao.dbSelect(searchSql.toString(), fields);
			String split = "|";
			if(mapsList!=null && mapsList.size()>0){
				for(Map<String, String> map : mapsList){
					Task4 task4 = new Task4();
					JSONObject object = new JSONObject();
					task4.setTaskId(StringUtils.isNotEmpty(map.get("mission_id"))?Long.parseLong(map.get("mission_id")):null);
					task4.setTaskType(StringUtils.isNotEmpty(map.get("mission_type"))?Long.parseLong(map.get("mission_type")):null);
					task4.setCommandName(map.get("command_ename"));
					if(StringUtils.isNotEmpty(map.get("command_para"))){
						StringBuffer newStrs = new StringBuffer();
						String[] strs = map.get("command_para").split("\\|");
						for(String str : strs){
							if(DateUtil.isDate(str,Constants.COMMON_DATE_FORMAT)){
								newStrs.append(split+format.parse(str).getTime());
							}else{
								newStrs.append(split+str);
							}
						}
						newStrs = newStrs.length()>0?newStrs.delete(0, split.length()):newStrs;
						task4.setCommandParam(newStrs.toString());
					}
					task4.setStartTime(StringUtils.isEmpty(map.get("start_time"))?null:format.parse(map.get("start_time")).getTime());
					task4.setEndTime(StringUtils.isEmpty(map.get("end_time"))?null:format.parse(map.get("end_time")).getTime());
					task4.setCommandType(StringUtils.isNotEmpty(map.get("command_type"))?Long.parseLong(map.get("command_type")):null);
					task4.setState(StringUtils.isNotEmpty(map.get("result"))?Long.parseLong(map.get("result")):null);
					task4.setVersion(StringUtils.isNotEmpty(map.get("version"))?Long.parseLong(map.get("version")):null);
					object.put("typeInfo", task4.getTaskType());
					object.put("taskInfo", task4);
					infoArray.add(object);
				}
			}
			//-- Task4 For LoopMission
			mapsList.clear();
			fields.clear();
			fields.add("mission_id");
			fields.add("mission_type");
			fields.add("command_type");
			fields.add("command_ename");
			fields.add("command_para");
			fields.add("start_time");
			fields.add("end_time");
			fields.add("result");
			fields.add("version");
			fields.add("is_loop");
			fields.add("loop_delay");
			fields.add("mission_state");
			
			searchSql.delete(0, searchSql.length());
			searchSql.append("select t.mission_id,t.mission_type,to_char(t.start_time,'"+Constants.DB_DATE_FORMAT+"') start_time,to_char(t.end_time,'"+Constants.DB_DATE_FORMAT+"') end_time, ");
			searchSql.append("mpt4.command_type, mpt4.command_ename, mpt4.command_para, mrt4.result,mpt4.version,t.is_loop,t.loop_delay,t.mission_state ");
			searchSql.append("from mission_state_table t ");
			searchSql.append("left join mission_parameter_table4 mpt4 on t.mission_id = mpt4.mission_id ");
			searchSql.append("left join loopmission_state_table lmst on lmst.mission_id = t.mission_id ");
			searchSql.append("left join mission_result_table4 mrt4 on mrt4.mission_id = lmst.cur_mission_id ");
//			searchSql.append("left join node_table nt on nt.node_group_id = mpt4.node_group_id and nt.system_id = t.system_id ");
			searchSql.append("where 1=1 ");
			searchSql.append("and t.mission_state =2 ");
			searchSql.append("and lmst.cur_mission_id in ( select max(lmst.cur_mission_id) from loopmission_state_table lmst where lmst.mission_state in (1,2) group by lmst.mission_id)");
			searchSql.append("and t.is_loop =1 ");
//			searchSql.append("and mpt4.node_group_id in( "+groupsIdsSQL+") ");
			searchSql.append("and mpt4.mission_id in( "+missionSql4+") ");
//			searchSql.append("and nt.seq_id = "+uuid.longValue()+" ");
			searchSql.append("and mrt4.result >= 40 ");
			searchSql.append("and mrt4.seq_id ="+uuid+" ");
			searchSql.append("order by t.create_time asc ");
			mapsList = dao.dbSelect(searchSql.toString(), fields);
			split = "|";
			if(mapsList!=null && mapsList.size()>0){
				for(Map<String, String> map : mapsList){
					Task4 task4 = new Task4();
					JSONObject object = new JSONObject();
					task4.setTaskId(StringUtils.isNotEmpty(map.get("mission_id"))?Long.parseLong(map.get("mission_id")):null);
					task4.setTaskType(StringUtils.isNotEmpty(map.get("mission_type"))?Long.parseLong(map.get("mission_type")):null);
					task4.setCommandName(map.get("command_ename"));
					if(StringUtils.isNotEmpty(map.get("command_para"))){
						StringBuffer newStrs = new StringBuffer();
						String[] strs = map.get("command_para").split("\\|");
						for(String str : strs){
							if(DateUtil.isDate(str,Constants.COMMON_DATE_FORMAT)){
								newStrs.append(split+format.parse(str).getTime());
							}else{
								newStrs.append(split+str);
							}
						}
						newStrs = newStrs.length()>0?newStrs.delete(0, split.length()):newStrs;
						task4.setCommandParam(newStrs.toString());
					}
					task4.setStartTime(StringUtils.isEmpty(map.get("start_time"))?null:format.parse(map.get("start_time")).getTime());
					task4.setEndTime(StringUtils.isEmpty(map.get("end_time"))?null:format.parse(map.get("end_time")).getTime());
					task4.setCommandType(StringUtils.isNotEmpty(map.get("command_type"))?Long.parseLong(map.get("command_type")):null);
					task4.setState(StringUtils.isNotEmpty(map.get("result"))?Long.parseLong(map.get("result")):null);
					task4.setVersion(StringUtils.isNotEmpty(map.get("version"))?Long.parseLong(map.get("version")):null);
					task4.setIsLoop(StringUtils.isNotEmpty(map.get("is_loop"))?Long.parseLong(map.get("is_loop")):null);
					task4.setLoopDelay(StringUtils.isNotEmpty(map.get("loop_delay"))?Long.parseLong(map.get("loop_delay")):null);
					task4.setMissionState(StringUtils.isNotEmpty(map.get("mission_state"))?Long.parseLong(map.get("mission_state")):null);
					object.put("typeInfo", task4.getTaskType());
					object.put("taskInfo", task4);
					infoArray.add(object);
				}
			}
			
			//-- Task6
			mapsList.clear();
			fields.clear();
			fields.add("mission_id");
			fields.add("mission_type");
			fields.add("command_type");
			fields.add("command_ename");
			fields.add("command_para");
			fields.add("source_path");
			fields.add("target_path");
			fields.add("check_value");
			fields.add("start_time");
			fields.add("result");
			fields.add("version");
			fields.add("old_task_id");
			searchSql.delete(0, searchSql.length());
			searchSql.append("select t.mission_id,t.mission_type, ");
			searchSql.append("mpt6.old_task_id, ");
			searchSql.append("mpt6.command_type, mpt6.command_ename, mpt6.command_para,mpt6.source_path,mpt6.target_path,mpt6.check_value,to_char(mpt6.start_time,'"+Constants.DB_DATE_FORMAT+"') start_time,  mrt6.result,mpt6.version ");
			searchSql.append("from mission_state_table t ");
			searchSql.append("left join mission_parameter_table6 mpt6 on t.mission_id = mpt6.mission_id ");
			searchSql.append("left join mission_result_table6 mrt6 on mrt6.mission_id = mpt6.mission_id ");
//			searchSql.append("left join node_table nt on nt.node_group_id = mpt4.node_group_id and nt.system_id = t.system_id ");
			searchSql.append("where (t.end_time>sysdate or t.end_time is null) ");
			searchSql.append("and t.mission_state =2 ");
//			searchSql.append("and mpt6.node_group_id in( "+groupsIdsSQL+") ");
			searchSql.append("and mpt6.mission_id in( "+missionSql6+") ");
//			searchSql.append("and nt.seq_id = "+uuid.longValue()+" ");
			searchSql.append("and mrt6.result >= 40 ");
			searchSql.append("and mrt6.seq_id ="+uuid+" ");
			searchSql.append("order by t.create_time asc ");
			mapsList = dao.dbSelect(searchSql.toString(), fields);
			if(mapsList!=null && mapsList.size()>0){
				for(Map<String, String> map : mapsList){
					Task6 task6 = new Task6();
					JSONObject object = new JSONObject();
					task6.setTaskId(StringUtils.isNotEmpty(map.get("mission_id"))?Long.parseLong(map.get("mission_id")):null);
					task6.setTaskType(StringUtils.isNotEmpty(map.get("mission_type"))?Long.parseLong(map.get("mission_type")):null);
					task6.setCommandName(map.get("command_ename"));
					task6.setCommandType(StringUtils.isNotEmpty(map.get("command_type"))?Long.parseLong(map.get("command_type")):null);
					task6.setCommandParam(map.get("command_para"));
					task6.setFileName( SocketUtils.removeTimeTagFileName(map.get("source_path")));
					task6.setDestPath(map.get("target_path"));
					task6.setMd5Value(map.get("check_value"));
					task6.setUpgradeTime(StringUtils.isEmpty(map.get("start_time"))?null:format.parse(map.get("start_time")).getTime());
					task6.setOldTaskId(StringUtils.isNotEmpty(map.get("old_task_id"))?Long.parseLong(map.get("old_task_id")):null);
					task6.setState(StringUtils.isNotEmpty(map.get("result"))?Long.parseLong(map.get("result")):null);
					task6.setVersion(StringUtils.isNotEmpty(map.get("version"))?Long.parseLong(map.get("version")):null);
					object.put("typeInfo", task6.getTaskType());
					object.put("taskInfo", task6);
					infoArray.add(object);
				}
			}
			return infoArray;
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return null;
	}
	
	/**
	 * 根据任务ID 获取任务信息用于 MissionInfo1
	 * @time Oct 25, 2011-10:19:00 AM
	 * @param missionId 可为空，为空时，全校验，非空时 校验指定Id 返回
	 */
	public MissionStateTable getMessionById(Long missionId){
		//-- 查询可执行的任务
		StringBuffer searchSQL = new StringBuffer();
		if(missionId==null || missionId.longValue() == 0l){
			return null;
		}
		searchSQL.append("select mst.mission_id,");
		searchSQL.append("mst.mission_type,");
		searchSQL.append("mst.mission_state,");
		searchSQL.append("mst.system_id,");
		searchSQL.append("mst.group_id,");
		searchSQL.append("to_char(mst.start_time,'"+Constants.DB_DATE_FORMAT+"') start_time,");
		searchSQL.append("to_char(mst.end_time,'"+Constants.DB_DATE_FORMAT+"') end_time,");
		searchSQL.append("mst.is_loop,");
		searchSQL.append("mst.loop_delay ");
		searchSQL.append("from mission_state_table mst ");
		searchSQL.append("where 1=1 ");
//		searchSQL.append("and (mst.end_time>sysdate or mst.end_time is null) ");
//		searchSQL.append("and mst.mission_state in (1,2,3,4) ");
		searchSQL.append("and mst.mission_id = '"+missionId+"' ");
		searchSQL.append("order by mst.create_time asc ");
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("mission_id");
		fields.add("mission_type");
		fields.add("mission_state");
		fields.add("system_id");
		fields.add("group_id");
		fields.add("start_time");
		fields.add("end_time");
		fields.add("is_loop");
		fields.add("loop_delay");
		ArrayList<Map<String, String>> rs = null;
		try {
			rs = dao.dbSelect(searchSQL.toString(), fields);
			MissionStateTable mission = new MissionStateTable();
			if(rs!=null && rs.size()>0){
				Map<String, String> maps = rs.get(0);
					mission.setMissionId(StringUtils.isEmpty(maps.get("mission_id"))?null:Long.parseLong(maps.get("mission_id")));
					mission.setMissionType(StringUtils.isEmpty(maps.get("mission_type"))?null:Long.parseLong(maps.get("mission_type")) );
					mission.setMissionState(StringUtils.isEmpty(maps.get("mission_state"))?null:Long.parseLong(maps.get("mission_state")));
					mission.setSystemId(StringUtils.isEmpty(maps.get("system_id"))?null:Long.parseLong(maps.get("system_id")));
					mission.setGroupId(StringUtils.isEmpty(maps.get("group_id"))?null:Long.parseLong(maps.get("group_id")));
					mission.setStartTime(StringUtils.isEmpty(maps.get("start_time"))?null:format.parse(maps.get("start_time")));
					mission.setEndTime(StringUtils.isEmpty(maps.get("end_time"))?null:format.parse(maps.get("end_time")));
					mission.setLoopFlag(StringUtils.isEmpty(maps.get("is_loop"))?null:Long.parseLong(maps.get("is_loop")));
					mission.setLoopDelay(StringUtils.isEmpty(maps.get("loop_delay"))?null:Long.parseLong(maps.get("loop_delay")));
			}
			return mission;
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return null;
	}
	
	/**
	 * 校验并初始化周期任务轮次信息 <br>
	 * <p>设计说明：<br>
	 * 1、校验 缓存中是否存在 该周期任务信息，不存在 则添加<br>
	 * 2、校验 缓存中是否存在 该周期任务的轮次信息 不存在 则添加<br>
	 * 3、校验 缓存中 轮次信息是否 符合要求：<br>
	 * 	a、周期判定[startTime,endTime)<br>
	 * 	b、保证周期任务的轮次信息的连续性和非重复性(起始时间 至 结束时间 无遗漏 无交集) <br>
	 *	c、过期的轮次信息创建 其状态为 4(未能执行)<br>
	 * 	d、预置周期（轮次起始时间大于当前系统时间）数量 <br>
	 * 		为  Constants.COMMON_MISSION_LOOP_PRESET_NUMBER <br>
	 * 	e、新预置轮次信息的状态为 0<br>
	 * @time Feb 13, 2012-10:40:41 AM
	 * @param missionId
	 * @param startTime
	 * @param endTime
	 * @param missionCycle
	 */
	public void checkAndInitMissionCycle (MissionStateTable mission) throws Exception{
		
		/**参数有效性校验*/
		if (mission==null || mission.getMissionId() == null
				|| mission.getStartTime() == null 
				|| mission.getEndTime() == null
				|| mission.getLoopFlag() == null ) {
			return;
		}
		
		/**设计实现*/
		//- 校验 缓存中是否存在周期任务
		if(Common.getLoopMissionInfoMap().get(mission.getMissionId())==null){
			this.updateLoopMissionInfo(Common.getLoopMissionInfoMap(), mission.getMissionId());	//将周期任务保存到缓存中
			mission = Common.getLoopMissionInfoMap().get(mission.getMissionId());
		}
		
		/**参数有效性再次校验：出现过经过再次获取Mission仍然mission为null的情况*/
		if (mission==null || mission.getMissionId() == null
				|| mission.getStartTime() == null 
				|| mission.getEndTime() == null
				|| mission.getLoopFlag() == null ) {
			return;
		}
		
		//- 校验 缓存中是否存在周期任务的轮次信息
		this.updateLoopMissionRoundInfo(Common.getLoopMissionRoundInfoList(), mission.getMissionId());		//更新指定周期任务ID的轮次信息
		List<LoopMissionRoundInfo> roundInfoList = Common.getLoopMissionRoundInfoList().get(mission.getMissionId());
//		if(roundInfoList==null || roundInfoList.size()==0){
//			roundInfoList = Common.getLoopMissionRoundInfoList().get(mission.getMissionId());
//		}
		
		//- 校验 轮次信息是否符合要求
		SimpleDateFormat format = new SimpleDateFormat(Constants.COMMON_DATE_FORMAT);
		long timeStart = mission.getStartTime().getTime();		// 任务的周期起始时间点（毫秒）
		long timeEnd = mission.getEndTime().getTime();		// 任务的周期结束时间点（毫秒）
		long timeDelay = mission.getLoopDelay()*60*1000;		// 任务的周期值（毫秒）
		int preset = Constants.MISSION_LOOP_PRESET_NUMBER;		//preset预置数
		
		//- 新创建任务 时间起始点为当前系统时间
//		if(mission.getMissionState().longValue()==1l){
//			if(timeStart<System.currentTimeMillis()){
//				timeStart = System.currentTimeMillis();
//			}
//		}
		logger.debug("new Date() 和 system.currentTimeMillis()"+(new Date().getTime())+" VS  "+System.currentTimeMillis());
		
		/*
		 * 轮次的时间段前闭后开区间
		 * 预置周期为： 轮次时间 > 当前系统时间
		 * 调整后的timeStart 为roundInfoList最后一个对象的结束时间
		 * */
		
		//-- 第一步 获取已存在的轮次信息 调整周期的起始时间、结束时间和预置数
		if(roundInfoList!=null && roundInfoList.size()>0){	//继续校验，并检查
			LoopMissionRoundInfo roundInfo = null;
			for (Iterator<LoopMissionRoundInfo> roundInfoIte = roundInfoList.iterator(); roundInfoIte.hasNext();) {
				roundInfo = roundInfoIte.next();

				if(roundInfo.getStartTime().getTime() > System.currentTimeMillis()){	//预置轮次信息数量判断
					preset--;
				}
				timeStart = timeStart>roundInfo.getEndTime().getTime()?timeStart:roundInfo.getEndTime().getTime();
			}
		}
		
		//-- 第二步 补齐新轮次信息
		List<String[]> cycleList = new LinkedList<String[]>();		//新轮次信息集合
		a: while(preset > 0){
			long timePoint = timeStart+timeDelay;	//周期游标
			int cycleState = 0;
			if(timePoint > timeEnd){		//周期游标 末端调整
				break;
			}
			
			/**
			周期任务的周期判定：“前闭后开”区间，即：包含起始时间点，不包含结束时间点。
			当前周期与之后的周期状态均为0（预置），过期周期状态为4（未能执行）
			 * */
			if(timeStart > System.currentTimeMillis()){	//预置周期
				cycleState = 0;
				preset--;
			}else if(timePoint < System.currentTimeMillis()){	// 过期周期
				cycleState = 4;
			}else{	//当前周期[上一周期的timePoint,下一周期的timeStart)
				cycleState = 0;
			}
			cycleList.add(new String[]{mission.getMissionId()+"",cycleState+"", format.format(timeStart),format.format(timePoint)});
			timeStart = timePoint;
			if(timeEnd == timePoint){
				break a;
			}
		}
		
		//-- 第三步  保存 并 更新 轮次信息
		try {
			dao.setAutoCommit(false);
			
			if(cycleList.size()>0){
				String sql = "insert into loopmission_state_table (mission_id,mission_state,start_time,end_time) values (?,?,to_date(?,'"+Constants.DB_DATE_FORMAT+"'),to_date(?,'"+Constants.DB_DATE_FORMAT+"')) ";
				dao.dbUpdateByBatch(sql, cycleList);
			}
			
			//-- 更新缓存中的周期任务的 轮次信息
			if(cycleList.size()>0){
				this.updateLoopMissionRoundInfo(Common.getLoopMissionRoundInfoList(), mission.getMissionId());
			}
			
			//if(mission.getMissionState()== MissionConstants.MISSION_STATE_CREATE){
				//-- 修改任务状态为 mission_state = 2已开始执行
			//	dao.dbUpdate("update mission_state_table mst set mst.mission_state = ? , mst.AUTO_DESC=? where mst.mission_id= ?",MissionConstants.MISSION_STATE_RUNNING_FAIL,MissionConstants.ERROR_TASK_NO_USED_NODE,mission.getMissionId().longValue());
//				dao.dbUpdate("update mission_state_table mst set mst.mission_state = 2 where mst.mission_id="+mission.getMissionId().longValue());
			//}
			
			dao.commit();
		} catch (Exception e) {
			dao.rollback();
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
	}
	
	/**
	 * 针对任务已创建状态的任务，为其初始化任务结果集
	 * 查询任务状态，校验是否执行初始化
	 * 查询初始化结果的节点，保存入库
	 * @time Oct 25, 2011-11:00:08 AM
	 * @param missionId	任务Id
	 * @param systemId	系统Id
	 * @param nodeGroupId	节点组IDs 多个逗号隔开，不能超过1000
	 * @param nodeIpsId		节点IDs 多个节点逗号隔开，不能超过1000
	 * @param missionType	任务类型
	 */
	public void initMissionResults(Long missionId,String nodeGroupId,String nodeIpsId, int missionType) throws Exception{
		if(missionId==null || missionId.longValue()==0 || missionType==0){
			return;
		}
		try {
		dao.setAutoCommit(false);
		ArrayList<String> fields = new ArrayList<String>();
		StringBuffer searchSQL = new StringBuffer();
		searchSQL.append("select mst.mission_state from mission_state_table mst where mst.mission_id = "+missionId.longValue()+" and mst.mission_state<>3");
		fields.add("mission_state");
		ArrayList<Map<String, String>> rs = null;
		try {
			rs = dao.dbSelect(searchSQL.toString(), fields);
			if(rs!= null && rs.size()>0){
				if(rs.get(0)!=null && rs.get(0).get("mission_state")!=null && "2".equals(rs.get(0).get("mission_state").trim())){
					return;
				}
			}
		} catch (Exception e) {
			logger.error("",e);
		}
		searchSQL.delete(0,searchSQL.length());
		searchSQL.append("select distinct nt.seq_id ");
		searchSQL.append("from node_table nt ");
		searchSQL.append("where 1=1 ");
		searchSQL.append(" and nvl(nt.seq_id,-1)<> -1 ");
		searchSQL.append(" and nt.node_state = 0 ");
		if(StringUtils.isNotBlank(nodeIpsId)){
			searchSQL.append(" and nt.NODE_ID in("+nodeIpsId+") ");
		}else{
			if(StringUtils.isNotBlank(nodeGroupId)){
//				searchSQL.append(" and nt.node_group_id in( select nt.group_id from NODEGROUP_TABLE nt where nt.leaf_group = 1 start with nt.group_id in ("+nodeGroupId+") connect by prior  nt.group_id = nt.parent_group_id )");
				//@2018年4月26日15:57:27 适配mysql 数据库
				String startWithConnectBy = dao.startWithConnectBy("select nt.group_id from NODEGROUP_TABLE nt where nt.leaf_group = 1 ", " nt.group_id in ("+nodeGroupId+") ", "group_id", "parent_group_id");
				searchSQL.append(" and nt.node_group_id in( "+startWithConnectBy+")");
			}
		}
//		searchSQL.append(getIpnSelect());
		fields.clear();
		fields.add("seq_id");
		
		rs = dao.dbSelect(searchSQL.toString(), fields);
		//-- 循环插入结果信息
		if(rs!=null && rs.size()>0){
			String sql = " insert into mission_result_table"+missionType+" (mission_id,seq_id,result) values (?,?,?)";
			LinkedList<String []> params = new LinkedList<String[]>();
			for(Map<String, String> maps : rs){
				params.add(new String[]{missionId.longValue()+"",maps.get("seq_id")+"","3"});
			}
			//-- 修改任务状态为 mission_state = 2已开始执行
			dao.dbUpdate("update mission_state_table mst set mst.mission_state = 2 where mst.mission_id="+missionId.longValue());
			dao.dbUpdateByBatch(sql, params);
		}
		dao.commit();
		} catch (Exception e) {
			try {
				dao.rollback();
			} catch (Exception e1) {
				logger.error("",e1);
			}
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
	}
	/**
	 * 初始化任务信息（校验任务下发节点有效、非服务器和管理范围外Node 结果判定失败）
	 * 查询任务下发节点，并做校验和初始化操作
	 * 1、校验无有效下发节点（任务未能执行）
	 * 2、校验非服务器节点（初始化该节点失败的任务结果）
	 * 3、校验管理范围外节点（初始化该节点失败的任务结果）
	 * 4、插入任务结果并更新任务状态
	 * @time Oct 25, 2011-11:00:08 AM
	 * @param missionId	任务Id
	 * @param systemId	系统Id
	 * @param nodeGroupId	节点组IDs 多个逗号隔开，不能超过1000
	 * @param nodeIpsId		节点IDs 多个节点逗号隔开，不能超过1000
	 * @param missionType	任务类型
	 */
	public void initMissionResults2(Long missionId,String nodeGroupId,String nodeIpsId, int missionType) throws Exception{
		/* 参数校验 */
		if(missionId==null || missionId.longValue()==0 || missionType==0){
			return;
		}
		
		/* 任务初始化业务 */
		try {
		dao.setAutoCommit(false);
		ArrayList<String> msFields = new ArrayList<String>();
		StringBuffer msSQL = new StringBuffer();
		
		//即时判断任务状态是否为已创建状态
		msFields.add("mission_state");
		msSQL.append("select mst.mission_state from mission_state_table mst where mst.mission_id = "+missionId.longValue()+" and mst.mission_state = "+MissionConstants.MISSION_STATE_CREATE);
		ArrayList<Map<String, String>> missionSateMap = dao.dbSelect(msSQL.toString(), msFields);
		if(missionSateMap== null || missionSateMap.size() == 0){
			return;
		}
		
		ArrayList<String> nodeFields = new ArrayList<String>();
		StringBuffer nodeSQL = new StringBuffer();
		
		//查询任务下发节点
		nodeFields.add("seq_id");
		nodeFields.add("node_type");
		nodeSQL.append("select distinct nt.seq_id,nt.node_type ");
		nodeSQL.append("from node_table nt ");
		nodeSQL.append("where 1 = 1 ");
		nodeSQL.append(" and nvl(nt.seq_id,-1)<> -1 ");
		nodeSQL.append(" and nt.node_state = 0 ");
		if(StringUtils.isNotBlank(nodeIpsId)){
			nodeSQL.append(" and nt.NODE_ID in("+nodeIpsId+") ");
		}else{
			if(StringUtils.isNotBlank(nodeGroupId)){
//				nodeSQL.append(" and nt.node_group_id in( select nt.group_id from NODEGROUP_TABLE nt where nt.leaf_group = 1 start with nt.group_id in ("+nodeGroupId+") connect by prior  nt.group_id = nt.parent_group_id )");
				//@2018年4月26日15:57:27 适配mysql 数据库
				String startWithConnectBy = dao.startWithConnectBy("select nt.group_id from NODEGROUP_TABLE nt where nt.leaf_group = 1 ", " nt.group_id in ("+nodeGroupId+") ", "group_id", "parent_group_id");
				nodeSQL.append(" and nt.node_group_id in( "+startWithConnectBy+")");
			}
		}
		ArrayList<Map<String, String>> nodeMapList = dao.dbSelect(nodeSQL.toString(), nodeFields);
		
		// 任务下发节点
		if(nodeMapList != null && nodeMapList.size()>0){
			
			//拼写uuid串，用于校验管理范围外IP
			StringBuffer uuidStr = new StringBuffer("0");
			for(Map<String, String> map : nodeMapList){
				if(StringUtils.isNotEmpty(map.get("seq_id"))){
					uuidStr.append(","+map.get("seq_id"));
				}
			}
			
			//查询任务下发节点sql-管理范围外节点
			ArrayList<String> ipnSegmentFields = new ArrayList<String>();
			StringBuffer ipnSegmentSQL = new StringBuffer("select sis.start_ipn,sis.end_ipn from server_ip_segment sis left join server_table st on st.id = sis.server_id where st.server_state='0' and nvl(sis.segment_state,0) <>-1");
			ipnSegmentFields.add("start_ipn");
			ipnSegmentFields.add("end_ipn");
			ArrayList<Map<String, String>> omNodeMapList = dao.dbSelect(ipnSegmentSQL.toString(), ipnSegmentFields);
			StringBuffer omNodeSql = new StringBuffer("select distinct nt.seq_id from node_table nt where 1=1 ");
			
			if(omNodeMapList!=null && omNodeMapList.size()>0){
				for(Map<String, String> map : omNodeMapList){
					omNodeSql.append(" and (ipn < '"+map.get("start_ipn")+"' or ipn > '"+map.get("end_ipn")+"')");
				}
			}
			omNodeSql.append("and nt.seq_id in ("+uuidStr+")");
			ArrayList<String> omNodeFields = new ArrayList<String>();
			omNodeFields.add("seq_id");
			omNodeMapList = dao.dbSelect(omNodeSql.toString(), omNodeFields);

			//循环插入结果信息
			String sql = " insert into mission_result_table"+missionType+" (mission_id,seq_id,result,result_desc) values (?,?,?,?)";
			LinkedList<String []> params = new LinkedList<String[]>();
			node:for(Map<String, String> nodeMap : nodeMapList){
				if("0".equals(nodeMap.get("node_type"))){	//服务器节点
					if(omNodeMapList!= null && omNodeMapList.size()>0){
						omNode:for(Map<String, String> map : omNodeMapList){
							if(nodeMap.get("seq_id").equals(map.get("seq_id"))){//管理范围外节点失败结果
								params.add(new String[]{missionId.longValue()+"",nodeMap.get("seq_id")+"","1",MissionConstants.ERROR_RESULT_UN_MANAGEMENT_NODE});
								continue node;
							}
						}
					}
					
					//可下发服务器节点
					params.add(new String[]{missionId.longValue()+"",nodeMap.get("seq_id")+"","3",null});
				}else{	//非服务器
					params.add(new String[]{missionId.longValue()+"",nodeMap.get("seq_id")+"","1",MissionConstants.ERROR_RESULT_NOT_SERVER});
				}
			}
			
			//-- 修改任务状态为 mission_state = 2已开始执行
			dao.dbUpdate("update mission_state_table mst set mst.mission_state =? , mst.AUTO_DESC=? where mst.mission_id=?",MissionConstants.MISSION_STATE_RUNNING_OK,format.format(System.currentTimeMillis())+" "+MissionConstants.NOTICE_TASK_RUNNING,missionId.longValue());
			dao.dbUpdateByBatch(sql, params);
		}else{
			//无节点任务
			dao.dbUpdate("update mission_state_table mst set mst.mission_state = ? , mst.AUTO_DESC=? where mst.mission_id= ?",MissionConstants.MISSION_STATE_RUNNING_FAIL,format.format(System.currentTimeMillis())+" "+MissionConstants.ERROR_TASK_NO_USED_NODE,missionId.longValue());
		}
	
		dao.commit();
		} catch (Exception e) {
			dao.rollback();
			throw e;
		}finally{
			dao.clearConn();
		}
	}
	
	/**
	 * 初始化任务信息（校验任务下发节点有效、非服务器和管理范围外Node 结果判定失败）
	 * 查询任务下发节点，并做校验和初始化操作
	 * 1、校验无有效下发节点（任务未能执行）
	 * 2、校验非服务器节点（初始化该节点失败的任务结果）
	 * 3、校验管理范围外节点（初始化该节点失败的任务结果）
	 * 4、插入任务结果并更新任务状态
	 * @time Oct 25, 2011-11:00:08 AM
	 * @param missionId	任务Id
	 * @param systemId	系统Id
	 * @param nodeGroupId	节点组IDs 多个逗号隔开，不能超过1000
	 * @param nodeIpsId		节点IDs 多个节点逗号隔开，不能超过1000
	 * @param missionType	任务类型
	 */
	public void initLoopMissionResults2(Long curMissionId,String nodeGroupId,String nodeIpsId,int resultValue) throws Exception{
		/* 参数校验 */
		if(curMissionId==null || curMissionId.longValue()==0 ){
			return;
		}
		
		/* 任务初始化业务 */
		try {
		dao.setAutoCommit(false);
		ArrayList<String> msFields = new ArrayList<String>();
		StringBuffer msSQL = new StringBuffer();
		
		//即时判断任务状态是否为已创建状态
		msFields.add("mission_state");
		msSQL.append("select mst.mission_state from loopmission_state_table mst where mst.cur_mission_id = "+curMissionId.longValue()+" and (mst.mission_state <> "+MissionConstants.MISSION_STATE_FINISHING+" or mst.mission_state <>"+MissionConstants.MISSION_STATE_CANCEL_FINISHING+")");
		ArrayList<Map<String, String>> missionSateMap = dao.dbSelect(msSQL.toString(), msFields);
		if(missionSateMap== null || missionSateMap.size() == 0){
			return;
		}
		
		ArrayList<String> nodeFields = new ArrayList<String>();
		StringBuffer nodeSQL = new StringBuffer();
		
		//查询任务下发节点
		nodeFields.add("seq_id");
		nodeFields.add("node_type");
		nodeSQL.append("select distinct nt.seq_id,nt.node_type ");
		nodeSQL.append("from node_table nt ");
		nodeSQL.append("where 1 = 1 ");
		nodeSQL.append(" and nvl(nt.seq_id,-1)<> -1 ");
		nodeSQL.append(" and nt.node_state = 0 ");
		logger.info("curMissionId="+curMissionId+"nodeIps="+nodeIpsId);
		if(StringUtils.isNotBlank(nodeIpsId)){
			nodeSQL.append(" and nt.NODE_ID in("+nodeIpsId+") ");
		}else{
			if(StringUtils.isNotBlank(nodeGroupId)){
//				nodeSQL.append(" and nt.node_group_id in( select nt.group_id from NODEGROUP_TABLE nt where nt.leaf_group = 1 start with nt.group_id in ("+nodeGroupId+") connect by prior  nt.group_id = nt.parent_group_id )");
				//@2018年4月26日15:57:27 适配mysql 数据库
				String startWithConnectBy = dao.startWithConnectBy("select nt.group_id from NODEGROUP_TABLE nt where nt.leaf_group = 1 ", " nt.group_id in ("+nodeGroupId+") ", "group_id", "parent_group_id");
				nodeSQL.append(" and nt.node_group_id in( "+startWithConnectBy+")");
			}
		}
		ArrayList<Map<String, String>> nodeMapList = dao.dbSelect(nodeSQL.toString(), nodeFields);
		
		// 任务下发节点
		if(nodeMapList != null && nodeMapList.size()>0){
			
			//拼写uuid串，用于校验管理范围外IP
			StringBuffer uuidStr = new StringBuffer("0");
			for(Map<String, String> map : nodeMapList){
				if(StringUtils.isNotEmpty(map.get("seq_id"))){
					uuidStr.append(","+map.get("seq_id"));
				}
			}
			
			//查询任务下发节点sql-管理范围外节点
			ArrayList<String> ipnSegmentFields = new ArrayList<String>();
			StringBuffer ipnSegmentSQL = new StringBuffer("select sis.start_ipn,sis.end_ipn from server_ip_segment sis left join server_table st on st.id = sis.server_id where st.server_state='0' and nvl(sis.segment_state,0) <>-1");
			ipnSegmentFields.add("start_ipn");
			ipnSegmentFields.add("end_ipn");
			ArrayList<Map<String, String>> omNodeMapList = dao.dbSelect(ipnSegmentSQL.toString(), ipnSegmentFields);
			StringBuffer omNodeSql = new StringBuffer("select distinct nt.seq_id from node_table nt where 1=1 ");
			
			if(omNodeMapList!=null && omNodeMapList.size()>0){
				for(Map<String, String> map : omNodeMapList){
					omNodeSql.append(" and (ipn < '"+map.get("start_ipn")+"' or ipn > '"+map.get("end_ipn")+"')");
				}
			}
			omNodeSql.append("and nt.seq_id in ("+uuidStr+")");
			ArrayList<String> omNodeFields = new ArrayList<String>();
			omNodeFields.add("seq_id");
			omNodeMapList = dao.dbSelect(omNodeSql.toString(), omNodeFields);

			//循环插入结果信息
			String sql = " insert into mission_result_table4 (mission_id,seq_id,result,result_desc) values (?,?,?,?)";
			LinkedList<String []> params = new LinkedList<String[]>();
			
			//查询当前任务的执行节点中上一周期下发失败的节点-2013-9-27 hyx
			//过滤失败的思路有问题，应该过滤下发成功的，未知的默认下发失败，再次下发
			String assignSuccessSeqIds = "";
			if(resultValue==40) {
				assignSuccessSeqIds = getAssignSuccessSeqIdsByMiss(curMissionId);
				System.out.println("curMissId="+curMissionId+",OKSeqIds="+assignSuccessSeqIds);
				logger.info("curMissId="+curMissionId+",OKSeqIds="+assignSuccessSeqIds);
			}
			boolean hasAssignFailNode = false;//不一定是真下发失败，当未知时，默认下发失败
//			String assignFailSeqIds = "";
//			if(resultValue==40) {
//				assignFailSeqIds = getAssignFailSeqIdsByMiss(curMissionId);//当前任务当前周期的当前节点之前的状态
//				System.out.println("curMissId="+curMissionId+",failSeqIds="+assignFailSeqIds);
//				logger.info("curMissId="+curMissionId+",failSeqIds="+assignFailSeqIds);
//			}
			
			//由于其他地方导致的缓存中的轮次信息的state和数据库中的不一致，对于已经有结果的，还要初始化，所以此处验证一下，如果已经有结果了，则不做插入操作
			ArrayList<String> hasRltFields = new ArrayList<String>();
			hasRltFields.add("result");
			hasRltFields.add("result_detail");
			ArrayList<Map<String, String>> hasRltList = dao.dbSelect("select mrt4.result,mrt4.result_detail from mission_result_table4 mrt4 where mrt4.mission_id="+curMissionId,hasRltFields);
			
			if(hasRltList!=null && hasRltList.size()==0) {//此处只能防止之前插入过此次不允许重复插入，不能防止此次插入重复的记录（curMissId+seqId），也不需要，因为表中设置了联合主键
				node:for(Map<String, String> nodeMap : nodeMapList){
					String seqIdTmp = nodeMap.get("seq_id")+"";
					if("0".equals(nodeMap.get("node_type"))){	//服务器节点
						if(omNodeMapList!= null && omNodeMapList.size()>0){
							omNode:for(Map<String, String> map : omNodeMapList){
								if(seqIdTmp.equals(map.get("seq_id"))){//管理范围外节点失败结果
									params.add(new String[]{curMissionId.longValue()+"",seqIdTmp,"1",MissionConstants.ERROR_RESULT_UN_MANAGEMENT_NODE});
									continue node;
								}
							}
						}
						
						//可下发服务器节点
						if(resultValue==40) {//周期任务再次初始化任务结果时，对于下发失败的，要初始化为下发中状态：3
							//对于当前任务的执行节点中下发失败的节点，并将任务结果初始化为3，然后进行下发
							System.out.println("所有的的seq"+seqIdTmp);
							logger.info("所有的的seq"+seqIdTmp);
							if(!assignSuccessSeqIds.contains(","+seqIdTmp+",")) {		
								System.out.println("下发失败的seq"+seqIdTmp);
								logger.info("下发失败的seq"+seqIdTmp);
								hasAssignFailNode = true;
								params.add(new String[]{curMissionId.longValue()+"",seqIdTmp,"3",null});
							}else {
								params.add(new String[]{curMissionId.longValue()+"",seqIdTmp,resultValue+"",null});
							}
						}else {
							params.add(new String[]{curMissionId.longValue()+"",seqIdTmp,resultValue+"",null});
						}
					}else{	//非服务器
						params.add(new String[]{curMissionId.longValue()+"",seqIdTmp,"1",MissionConstants.ERROR_RESULT_NOT_SERVER});
					}
				}
			}
			
			//当之前周期有下发失败的节点时，本周期继续进行下发：,2,（其实是将需要下发的任务id加入到对应的list）
			if(hasAssignFailNode) {
				MissionStateTable mission = getMissionInfoByCurMissionId(curMissionId);
				String[] missIds = new String[1];
				if(mission!=null && mission.getMissionId()!=null) {
					missIds[0] = mission.getMissionId()+"";
					Common.addAssignFailMissionIds(mission.getMissionId()+"");
				}
			}			
			
			//-- 修改周期任务状态为 mission_state 开始执行2 或6 
			if(resultValue==3){
				dao.dbUpdate("update loopmission_state_table mst set mst.mission_state =? where mst.cur_mission_id=?",MissionConstants.MISSION_STATE_RUNNING_OK,curMissionId.longValue());
			}else if(resultValue==5){
				dao.dbUpdate("update loopmission_state_table mst set mst.mission_state =? where mst.cur_mission_id=?",MissionConstants.MISSION_STATE_CANCEL_RUNNING_OK,curMissionId.longValue());
				
			}
			dao.dbUpdateByBatch(sql, params);
		}else{
			
			//无节点任务 将周期置为无效
			dao.dbUpdate("update mission_state_table mst set mst.AUTO_DESC=? where mst.mission_id in (select lmst.mission_id from loopmission_state_table lmst where lmst.cur_mission_id=? )"
					, format.format(new Date())+" " +MissionConstants.ERROR_TASK_RUND_NO_USED_NODE
					,curMissionId.longValue());
			dao.dbUpdate("update loopmission_state_table mst set mst.mission_state = ? where mst.cur_mission_id= ?",MissionConstants.MISSION_STATE_RUNNING_FAIL,curMissionId.longValue());
		}
	
		dao.commit();
		} catch (Exception e) {
			dao.rollback();
			throw e;
		}finally{
			dao.clearConn();
		}
	}
	
	/**
	 * 初始化所有节点都不通的周期任务的结果：过期的插入下发失败的结果
	 *     1.查询未过期的周期，插入结果3
	 *     2.查询过期的周期，且未插入结果的，插入1,41
	 */
	public void initLoopMissionForAssignFail(Long curMissionId,String nodeGroupId,String nodeIpsId,int resultVal,Integer resultDetail) throws Exception{
		/* 参数校验 */
		if(curMissionId==null || curMissionId.longValue()==0 ){
			return;
		}
		String rltDetailStr = resultDetail==null?"":resultDetail+"";
		
		/* 任务初始化业务 */
		try {
			dao.setAutoCommit(false);
			ArrayList<String> msFields = new ArrayList<String>();
			StringBuffer msSQL = new StringBuffer();
			
			//即时判断任务状态是否为已创建状态
			msFields.add("mission_state");
			msSQL.append("select mst.mission_state from loopmission_state_table mst where mst.cur_mission_id = "+curMissionId.longValue()+" and (mst.mission_state <> "+MissionConstants.MISSION_STATE_FINISHING+" or mst.mission_state <>"+MissionConstants.MISSION_STATE_CANCEL_FINISHING+")");
			ArrayList<Map<String, String>> missionSateMap = dao.dbSelect(msSQL.toString(), msFields);
			if(missionSateMap== null || missionSateMap.size() == 0){
				return;
			}
			
			//查询需要插入结果的节点
			ArrayList<String> nodeFields = new ArrayList<String>();
			StringBuffer nodeSQL = new StringBuffer();			
			//查询任务下发节点
			nodeFields.add("seq_id");
			nodeFields.add("node_type");
			nodeSQL.append("select distinct nt.seq_id,nt.node_type ");
			nodeSQL.append("from node_table nt ");
			nodeSQL.append("where 1 = 1 ");
			nodeSQL.append(" and nvl(nt.seq_id,-1)<> -1 ");
			nodeSQL.append(" and nt.node_state = 0 ");
			if(StringUtils.isNotBlank(nodeIpsId)){
				nodeSQL.append(" and nt.NODE_ID in("+nodeIpsId+") ");
			}else{
				if(StringUtils.isNotBlank(nodeGroupId)){
//					nodeSQL.append(" and nt.node_group_id in( select nt.group_id from NODEGROUP_TABLE nt where nt.leaf_group = 1 start with nt.group_id in ("+nodeGroupId+") connect by prior  nt.group_id = nt.parent_group_id )");
					//@2018年4月26日15:57:27 适配mysql 数据库
					String startWithConnectBy = dao.startWithConnectBy("select nt.group_id from NODEGROUP_TABLE nt where nt.leaf_group = 1 ", " nt.group_id in ("+nodeGroupId+") ", "group_id", "parent_group_id");
					nodeSQL.append(" and nt.node_group_id in( "+startWithConnectBy+")");
				}
			}
			ArrayList<Map<String, String>> nodeMapList = dao.dbSelect(nodeSQL.toString(), nodeFields);
			
			// 任务下发节点
			if(nodeMapList != null && nodeMapList.size()>0){
				
				//拼写uuid串，用于校验管理范围外IP
				StringBuffer uuidStr = new StringBuffer("0");
				for(Map<String, String> map : nodeMapList){
					if(StringUtils.isNotEmpty(map.get("seq_id"))){
						uuidStr.append(","+map.get("seq_id"));
					}
				}
				
				//查询任务下发节点sql-管理范围外节点
				ArrayList<String> ipnSegmentFields = new ArrayList<String>();
				StringBuffer ipnSegmentSQL = new StringBuffer("select sis.start_ipn,sis.end_ipn from server_ip_segment sis left join server_table st on st.id = sis.server_id where st.server_state='0' and nvl(sis.segment_state,0) <>-1");
				ipnSegmentFields.add("start_ipn");
				ipnSegmentFields.add("end_ipn");
				ArrayList<Map<String, String>> omNodeMapList = dao.dbSelect(ipnSegmentSQL.toString(), ipnSegmentFields);
				StringBuffer omNodeSql = new StringBuffer("select distinct nt.seq_id from node_table nt where 1=1 ");
				
				if(omNodeMapList!=null && omNodeMapList.size()>0){
					for(Map<String, String> map : omNodeMapList){
						omNodeSql.append(" and (ipn < '"+map.get("start_ipn")+"' or ipn > '"+map.get("end_ipn")+"')");
					}
				}
				omNodeSql.append("and nt.seq_id in ("+uuidStr+")");
				ArrayList<String> omNodeFields = new ArrayList<String>();
				omNodeFields.add("seq_id");
				omNodeMapList = dao.dbSelect(omNodeSql.toString(), omNodeFields);
				
				//循环插入结果信息
				String sql = " insert into mission_result_table4 (mission_id,seq_id,result,result_detail,result_desc) values (?,?,?,?,?)";
				LinkedList<String []> params = new LinkedList<String[]>();
				
				//由于其他地方导致的缓存中的轮次信息的state和数据库中的不一致，对于已经有结果的，还要初始化，所以此处验证一下，如果已经有结果了，则不做插入操作
				ArrayList<String> hasRltFields = new ArrayList<String>();
				hasRltFields.add("result");
				hasRltFields.add("result_detail");
				ArrayList<Map<String, String>> hasRltList = dao.dbSelect("select mrt4.result,mrt4.result_detail from mission_result_table4 mrt4 where mrt4.mission_id="+curMissionId,hasRltFields);
				
				if(hasRltList!=null && hasRltList.size()==0) {						
					node:for(Map<String, String> nodeMap : nodeMapList){
						String seqIdTmp = nodeMap.get("seq_id")+"";
						if("0".equals(nodeMap.get("node_type"))){	//服务器节点
							if(omNodeMapList!= null && omNodeMapList.size()>0){
								omNode:for(Map<String, String> map : omNodeMapList){
									if(seqIdTmp.equals(map.get("seq_id"))){//管理范围外节点失败结果
										params.add(new String[]{curMissionId.longValue()+"",seqIdTmp,resultVal+"",rltDetailStr,MissionConstants.ERROR_RESULT_UN_MANAGEMENT_NODE});
										continue node;
									}
								}
							}
							
							
							params.add(new String[]{curMissionId.longValue()+"",seqIdTmp,resultVal+"",rltDetailStr,null});
						}else{	//非服务器
							params.add(new String[]{curMissionId.longValue()+"",seqIdTmp,resultVal+"",rltDetailStr,MissionConstants.ERROR_RESULT_NOT_SERVER});
						}
					}
				}
				
				//-- 修改周期任务状态为 mission_state 开始执行2 或6 
				if(resultVal==3){
					dao.dbUpdate("update loopmission_state_table mst set mst.mission_state =? where mst.cur_mission_id=?",MissionConstants.MISSION_STATE_RUNNING_OK,curMissionId.longValue());
				}else if(resultVal==5){
					dao.dbUpdate("update loopmission_state_table mst set mst.mission_state =? where mst.cur_mission_id=?",MissionConstants.MISSION_STATE_CANCEL_RUNNING_OK,curMissionId.longValue());
					
				}
				dao.dbUpdateByBatch(sql, params);
			}
//			else{//此处不会执行到，既然之前周期确定为节点都不通，表明有执行节点				
//				//无节点任务 将周期置为无效
//				dao.dbUpdate("update mission_state_table mst set mst.AUTO_DESC=? where mst.mission_id in (select lmst.mission_id from loopmission_state_table lmst where lmst.cur_mission_id=? )"
//						, format.format(new Date())+" " +MissionConstants.ERROR_TASK_RUND_NO_USED_NODE
//						,curMissionId.longValue());
//				dao.dbUpdate("update loopmission_state_table mst set mst.mission_state = ? where mst.cur_mission_id= ?",MissionConstants.MISSION_STATE_RUNNING_FAIL,curMissionId.longValue());
//			}
//			
			dao.commit();
		} catch (Exception e) {
			dao.rollback();
			throw e;
		}finally{
			dao.clearConn();
		}
	}
	
	//查询当前任务的执行节点中上一周期下发失败的节点
	private String getAssignFailSeqIdsByMiss(Long curMissionId) {
		StringBuffer assignFailSeqIds = new StringBuffer(",");
		try
		{
			if(curMissionId!=null) {
				ArrayList<String> nodeFields = new ArrayList<String>();
				StringBuffer nodeSQL = new StringBuffer();
				
				//查询任务下发节点---此sql有问题，只查完成的，如果之前没有完成的周期，那就没有下发失败的节点，其实是不知道是否下发成功，应该默认下发失败才对，NC会过滤的
				nodeFields.add("seq_id");
				nodeSQL.append(" select mrt4.seq_id from mission_result_table4 mrt4 ");//3：超找此周期中，下发失败的：result=1 and resultDetail=41
				nodeSQL.append(" where mrt4.mission_id =( ");
				nodeSQL.append("       select max(lst.cur_mission_id)  ");//2：(有可能查到的为null，只有一个周期的，或者之前都是未能执行的，此为第一个周期)查找主任务中当前周期之前的，且执行完成的一个周期的任务id（会不会有的周期任务的结果还没过来，导致查找的不对，条件为：小于当前周期的最大的周期，且不为4未能执行的）
				nodeSQL.append("       from loopmission_state_table lst  ");
				nodeSQL.append("       where lst.mission_id = ( ");
				nodeSQL.append("             select lstTmp.mission_id ");//1：超找当前周期对应的主任务id
				nodeSQL.append("             from loopmission_state_table lstTmp  ");
				nodeSQL.append("             where lstTmp.cur_mission_id="+curMissionId+")");
				//下面sql语句不能加state=2，因为为2时，可能结果为3 or 40 此时不知道是否下发成功，应该默认下发失败，再次下发才对，重复下发，NC会过滤，不会重复执行，所以只能要state=3完成的，我们才能准确判断
				nodeSQL.append("             and (lst.mission_state =3 ) and lst.cur_mission_id<"+curMissionId);//lst.mission_state =3，未能执行的在结果表不会有结果，所以第一个条件！=4可以不加，不行，那就看之前是否有执行完成的？
				nodeSQL.append(" ) and mrt4.result=1 and mrt4.result_detail=41");
				ArrayList<Map<String, String>> nodeMapList = dao.dbSelect(nodeSQL.toString(), nodeFields);
				if(nodeMapList != null && nodeMapList.size()>0){					
					for(Map<String, String> map : nodeMapList){
						if(StringUtils.isNotEmpty(map.get("seq_id"))){
							assignFailSeqIds.append(map.get("seq_id")+",");
						}
					}
				}
			}
			
		} catch (Exception e)
		{
			logger.error("The node that failed to query the current task during the previous cycle is curMissionId="+curMissionId+" abnormal", e);
		}
		
		return assignFailSeqIds.toString();
	}
	
	
	//查询当前任务的执行节点中上一周期下发失败的节点
	private String getAssignSuccessSeqIdsByMiss(Long curMissionId) {
		StringBuffer assignFailSeqIds = new StringBuffer(",");
		try
		{
			if(curMissionId!=null) {
				ArrayList<String> nodeFields = new ArrayList<String>();
				StringBuffer nodeSQL = new StringBuffer();
				
				//查询任务下发节点
				nodeFields.add("seq_id");
				nodeSQL.append(" select distinct mrt4.seq_id from mission_result_table4 mrt4 ");
				nodeSQL.append(" where mrt4.mission_id in( ");
				nodeSQL.append("       select lst.cur_mission_id  ");//查找当前周期之前所有周期的任务id
				nodeSQL.append("       from loopmission_state_table lst  ");
				nodeSQL.append("       where lst.mission_id = ( ");
				nodeSQL.append("             select lstTmp.mission_id ");
				nodeSQL.append("             from loopmission_state_table lstTmp  ");
				nodeSQL.append("             where lstTmp.cur_mission_id="+curMissionId+")");
				nodeSQL.append("             and lst.cur_mission_id<"+curMissionId);
				nodeSQL.append(" ) and  mrt4.result in (0,40,50,60,70,80)  ");//查一定 下发成功 的节点,对于result=1，result_detail！=41的，也可能是下发失败（周期任务超时时将3修改为1，不过这种情况影响不大）
//				nodeSQL.append(" ) and ( mrt4.result in (0,40,50,60,70,80) or ");//查一定 下发成功 的节点
//				nodeSQL.append("         (mrt4.result=1 and (mrt4.result_detail is null or mrt4.result_detail !=41))");
//				nodeSQL.append("        )");
				ArrayList<Map<String, String>> nodeMapList = dao.dbSelect(nodeSQL.toString(), nodeFields);
				if(nodeMapList != null && nodeMapList.size()>0){					
					for(Map<String, String> map : nodeMapList){
						if(StringUtils.isNotEmpty(map.get("seq_id"))){
							assignFailSeqIds.append(map.get("seq_id")+",");
						}
					}
				}
			}
			
		} catch (Exception e)
		{
			logger.error("The node that succeeds in the last cycle of the execution node for the current task is querying,curMissionId="+curMissionId+" abnormal", e);
		}
		
		return assignFailSeqIds.toString();
	}
	
	/**
	 * 统计周期任务中，执行节点全都不通的情况:
	 *   1.最近的一个周期：1-41 或者 3（多次下发也没关系，NC会自动过滤，不会多次执行）
	 *   2.更新loop表的state：2 or 4
	 *   
	 */
	public List<String> checkLoopMissAssignFail() {
		List<String> assignFailMissIds = new ArrayList<String>();
		try
		{
			ArrayList<String> missFields = new ArrayList<String>();
			StringBuffer missSQL = new StringBuffer();
			
			//查询任务下发节点
			missFields.add("mission_id");
			missFields.add("cur_mission_id");
			missFields.add("nodeNum");
			missFields.add("assignFailNum");
			missFields.add("node_groups_id");
			missFields.add("node_ips_id");
			
			Date sysdateD = new Date();
			String sysdate = format.format(sysdateD);//为了统一时间，都去DC的时间
			
			//查找所有节点都不通的周期任务相关的信息
			missSQL.append(" select tmp.mission_id,tmp.maxCurMissId cur_mission_id,tmp.nodeNum,tmp.assignFailNum,mpt4.node_groups_id,mpt4.node_ips_id ");
			missSQL.append(" from (  ");
			missSQL.append("       select tmp1.mission_id,tmp1.maxCurMissId,count(*) nodeNum, ");
			missSQL.append("              sum(case when mrt4.result=1 and mrt4.result_detail=41 then 1 else 0 end) assignFailNum        ");
			missSQL.append("       from  ");
			missSQL.append("       (  ");
			missSQL.append("           select mst.mission_id,max(lst.cur_mission_id) maxCurMissId ");
			missSQL.append("           from mission_state_table mst  ");
			missSQL.append("           left join loopmission_state_table lst on lst.mission_id=mst.mission_id  ");
			missSQL.append("           left join mission_result_table4 mrt4 on mrt4.mission_id=lst.cur_mission_id  ");
			missSQL.append("           where mst.mission_type=4 and mst.is_loop=1 and mst.end_time>to_date('"+sysdate+"','yyyy-MM-dd HH24:mi:ss') ");//对于过期的，loop表的state为未能执行
			missSQL.append("                 and mst.mission_state=2 ");//总任务状态为执行中
			missSQL.append("                 and lst.mission_state in (3,2)  ");//中间有未能执行的也没关系，只要执行完成的最新的一个周期是都不通，就认为都不通。如果加上2的状态，则下发中的周期就不会认为是网络都不通的情况，这样就不会再去下发了，所以还是要加2的状态的
			missSQL.append("           group by mst.mission_id ");
			missSQL.append("        )tmp1 ");
			missSQL.append("        left join mission_result_table4 mrt4 on mrt4.mission_id=tmp1.maxCurMissId ");
			missSQL.append("        group by tmp1.mission_id,tmp1.maxCurMissId ");
			missSQL.append(" )tmp");
			missSQL.append(" left join mission_parameter_table4 mpt4 on mpt4.mission_id = tmp.mission_id ");
			missSQL.append(" left join loopmission_state_table lst2 on lst2.cur_mission_id=tmp.maxCurMissId ");
			missSQL.append(" where tmp.nodeNum=assignFailNum  and tmp.mission_id is not null and tmp.maxCurMissId is not null ");
			
			ArrayList<Map<String, String>> missMapList = dao.dbSelect(missSQL.toString(), missFields);
			//有记录就说明存在全部通的周期任务
			if(missMapList != null && missMapList.size()>0){	
				String initRltCurMissIdSql = " select  case when lst.end_time>to_date('"+sysdate+"','yyyy-MM-dd HH24:mi:ss')  and lst.start_time<=to_date('"+sysdate+"','yyyy-MM-dd HH24:mi:ss')  then lst.cur_mission_id  end toAssign ," +//下发失败后，再次下发时，要在周期时间内，不在周期时间内，不进行下发
													 " case when lst.end_time<=to_date('"+sysdate+"','yyyy-MM-dd HH24:mi:ss')  then lst.cur_mission_id end assignFail  " +
											 " from loopmission_state_table lst " +
											 " left join mission_state_table mst on mst.mission_id=lst.mission_id " +
											 " left join  mission_result_table4 mrt4 on lst.cur_mission_id=mrt4.mission_id " +
											 " where lst.mission_id=? and lst.cur_mission_id>? and mrt4.result is null and mst.mission_state in (2,6)"+//总任务状态为已完成的就不初始化结果了
											 "       and (lst.end_time<=to_date('"+sysdate+"','yyyy-MM-dd HH24:mi:ss')  or (lst.start_time<=to_date('"+sysdate+"','yyyy-MM-dd HH24:mi:ss')  and lst.end_time>to_date('"+sysdate+"','yyyy-MM-dd HH24:mi:ss') ))" +//下发失败后，再次下发时，要在周期时间内，不在周期时间内，不进行下发
											 " order by toAssign asc";
				ArrayList<String> curMissFields = new ArrayList<String>();
				curMissFields.add("toAssign");
				curMissFields.add("assignFail");
				
				for(Map<String, String> map : missMapList){
					if(StringUtils.isNotEmpty(map.get("mission_id"))){
						assignFailMissIds.add(map.get("mission_id"));
						//初始化任务结果：下发中
						Long missId = Long.parseLong(map.get("mission_id"));
						Long curMissId = Long.parseLong(map.get("cur_mission_id"));
						
						MissionStateTable mission = this.getMessionById(missId);
						
						String nodeGroupIds = map.get("node_groups_id");
						String nodeIds = map.get("node_ips_id");
						
						//如果已经有结果了，就不要再进行插入结果,过了时间的周期直接默认插入下发失败的结果：因为是全不通，所以要所有节点都插入下发中的结果
						ArrayList<Map<String, String>> missCurMissMapList = dao.dbSelect(initRltCurMissIdSql, curMissFields, missId,curMissId);
						boolean assignOneFlag = true;
						if(missCurMissMapList!=null && missCurMissMapList.size()>0) {
							for(Map<String, String> mapTmp : missCurMissMapList){
								LoopMissionRoundInfo roundInfo = null;
								if(StringUtils.isNotBlank(mapTmp.get("toAssign")) && assignOneFlag) {//初始化下发结果:只初始化最近的未过期的一个周期，可能周期未执行完毕
									//未过期的，下发
									Long toAssignCurMissId = Long.parseLong(mapTmp.get("toAssign"));
									//-- 轮次校验和初始化
									checkAndInitMissionCycle(mission);
									
									//-- 获取当前周期轮次
									List<LoopMissionRoundInfo> roundInfoList = Common.getLoopMissionRoundInfoList().get(missId);
									if(roundInfoList !=null && roundInfoList.size()>0){
										//-- 获取当前周期轮次
										for (Iterator<LoopMissionRoundInfo> roundIte = roundInfoList.iterator(); roundIte.hasNext();) {
											roundInfo = roundIte.next();
											if(roundInfo.getEndTime().compareTo(sysdateD)==1 ){//大于
												break;
											}
										}
										logger.info("当前轮次的id"+roundInfo.getCurMissionId()+",主id"+missId);
									}
									
									//-- 预置状态的轮次，初始化当前轮次的结果数据
									if(roundInfo!=null && roundInfo.getMissionState()!=null && roundInfo.getMissionState().longValue()==0l || roundInfo.getMissionState().longValue()==1l){	//0 预置状态，未初始化当前轮次的任务结果信息
										initLoopMissionForAssignFail(toAssignCurMissId,nodeGroupIds,nodeIds,3,null);//初始化无需下发的结果信息 3开始执行 40已下发,修改loop表的状态为执行中2
										roundInfo.setMissionState(2l);	//更新缓存中的任务轮次信息状态
									}
									
									assignOneFlag = false;//只将符合条件（无结果，周期结束时间未过）的最小的一个周期的执行结果修改为下发中3
									continue;
								}
								if(StringUtils.isNotBlank(mapTmp.get("assignFail"))) {//过期的：都初始化为4
									Long assignFailCurMissId = Long.parseLong(mapTmp.get("assignFail"));
									
									//-- 轮次校验和初始化
									checkAndInitMissionCycle(mission);
									
									//-- 获取当前周期轮次
									List<LoopMissionRoundInfo> roundInfoList = Common.getLoopMissionRoundInfoList().get(missId);
									if(roundInfoList !=null && roundInfoList.size()>0){
										//-- 获取当前周期轮次
										for (Iterator<LoopMissionRoundInfo> roundIte = roundInfoList.iterator(); roundIte.hasNext();) {
											roundInfo = roundIte.next();
											if(roundInfo.getEndTime().compareTo(sysdateD)==1 ){//大于
												break;
											}
										}
									}
									
									//过期的，插入结果
									if(roundInfo!=null) {
										updateLoopMissionState(assignFailCurMissId, 4);//修改loop表的状态为未能执行4，不需要插入结果了就
										roundInfo.setMissionState(4l);
									}
									continue;
								}
							}
						}
					}
				}
			}
			
		} catch (Exception e)
		{
			logger.error("In the statistical periodic task, the execution nodes are all blocked", e);
		}
		
		return assignFailMissIds;
	}
	
	/**
	 * 针对任务已创建状态的任务，为其初始化结果集
	 * 最大精确到组的任务结果记录插入
	 * @time Oct 25, 2011-11:00:08 AM
	 * @param curMissionId	任务Id
	 * @param systemId	系统Id
	 */
	public void initLoopMissionResults(Long curMissionId,String groupsId,String nodeIpsId,int resultValue) throws Exception{
		if(curMissionId==null || curMissionId.longValue()==0){
			return;
		}
		ArrayList<String> fields = new ArrayList<String>();
		StringBuffer searchSQL = new StringBuffer();
		searchSQL.append("select mst.mission_state from loopmission_state_table mst where mst.cur_mission_id = "+curMissionId.longValue()+" and mst.mission_state<>3");
		fields.add("mission_state");
		ArrayList<Map<String, String>> rs = null;
		try {
			rs = dao.dbSelect(searchSQL.toString(), fields);
			if(rs!= null && rs.size()>0){
				if(rs.get(0)!=null && StringUtils.isNotEmpty(rs.get(0).get("mission_state")) && ("2".equals(rs.get(0).get("mission_state").trim()) || "6".equals(rs.get(0).get("mission_state").trim()))){
					return;
				}
			}
		} catch (Exception e) {
			logger.error("",e);
		}
		searchSQL.delete(0,searchSQL.length());
		searchSQL.append("select distinct nt.seq_id ");
		searchSQL.append("from node_table nt ");
		searchSQL.append("where 1=1 ");
		searchSQL.append(" and nvl(nt.seq_id,-1)<> -1 ");
		searchSQL.append(" and nt.node_state = 0 ");
		if(StringUtils.isNotBlank(nodeIpsId)){
			searchSQL.append(" and nt.NODE_ID in("+nodeIpsId+") ");
		}else{
			if(StringUtils.isNotBlank(groupsId)){
//				searchSQL.append(" and nt.node_group_id in( select nt.group_id from NODEGROUP_TABLE nt where nt.leaf_group = 1 start with nt.group_id in ("+groupsId+") connect by prior  nt.group_id = nt.parent_group_id )");
				//@2018年4月26日15:57:27 适配mysql 数据库
				String startWithConnectBy = dao.startWithConnectBy("select nt.group_id from NODEGROUP_TABLE nt where nt.leaf_group = 1 ", " nt.group_id in ("+groupsId+") ", "group_id", "parent_group_id");
				searchSQL.append(" and nt.node_group_id in( "+startWithConnectBy+")");
			}
		}
//		searchSQL.append(getIpnSelect());
		fields.clear();
		fields.add("seq_id");
		try {
			rs = dao.dbSelect(searchSQL.toString(), fields);
			//-- 循环插入结果信息
			dao.setAutoCommit(false);
			if(rs!=null && rs.size()>0){
				String sql = " insert into mission_result_table4 (mission_id,seq_id,result) values (?,?,?)";
				LinkedList<String []> params = new LinkedList<String[]>();
				for(Map<String, String> maps : rs){
					params.add(new String[]{curMissionId.longValue()+"",maps.get("seq_id")+"",resultValue+""});
				}
				//-- 修改任务状态为 mission_state = 1 以创建 BUG loop state =5 的情况
				dao.dbUpdate("update loopmission_state_table mst set mst.mission_state = 1 where mst.cur_mission_id="+curMissionId.longValue());
				dao.dbUpdateByBatch(sql, params);
			}
			dao.commit();
		} catch (Exception e) {
			try {
				dao.rollback();
			} catch (Exception e1) {
				logger.error("",e1);
			}
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
	}
	public Task1 getTask1ById(Long missionId){
		if(missionId == null || missionId.longValue() == 0){
			return null;
		}
		Task1 task1 = new Task1();
		StringBuffer searchSQL = new StringBuffer();
		searchSQL.append("select mpt1.node_groups_id,mpt1.command_para,mpt1.NODE_IPS_ID ");
		searchSQL.append("from mission_parameter_table1 mpt1 ");
		searchSQL.append("where mpt1.mission_Id='"+missionId.longValue()+"' ");
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("node_groups_id");
		fields.add("NODE_IPS_ID");
		fields.add("command_para");
		ArrayList<Map<String, String>> rs = null;
		try {
			rs = dao.dbSelect(searchSQL.toString(), fields);
			//-- 整理到对象集合
			if(rs!=null && rs.size()>0){
				Map<String, String> maps = rs.get(0);
				task1.setTaskParam(StringUtils.isEmpty(maps.get("command_para"))?null: maps.get("command_para"));
				task1.setNodeGroupsId(StringUtils.isEmpty(maps.get("node_groups_id"))?null: maps.get("node_groups_id"));
				task1.setNodeIpsId(StringUtils.isEmpty(maps.get("NODE_IPS_ID"))?null: maps.get("NODE_IPS_ID"));
			}			
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return task1;
	}
	public String getHostIpByMissionId(Long mId){
		String hostIp = null;
		StringBuffer searchSQL = new StringBuffer();
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("system_ip");
		ArrayList<Map<String, String>> rs = null;
		try {
			rs = dao.dbSelect("select st.system_ip from system_table st,mission_state_table mst where mst.system_id = st.system_id and  mst.mission_id='"+mId.longValue()+"'", fields);
			if(rs!=null && rs.size()>0){
				Map<String, String> map = (Map<String, String>) rs.get(0);
				hostIp = StringUtils.isEmpty(map.get("system_ip"))?null:StringUtils.trim(map.get("system_ip"));
			}
		} catch (Exception e) {
			logger.error("MissionId is："+mId+" ServerIp acquisition failure",e);
		}
		if(StringUtils.isEmpty(hostIp)){
			logger.error("missionId is："+mId+" ServerIp is empty");
		}
		return hostIp;
	}
	public String getHostIpBySystemId(Long systemId){
		String hostIp = null;
		StringBuffer searchSQL = new StringBuffer();
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("system_ip");
		ArrayList<Map<String, String>> rs = null;
		try {
			rs = dao.dbSelect("select st.system_ip from system_table st where st.system_id='"+systemId.longValue()+"'", fields);
			if(rs!=null && rs.size()>0){
				Map<String, String> map = (Map<String, String>) rs.get(0);
				hostIp = StringUtils.isEmpty(map.get("system_ip"))?null:StringUtils.trim(map.get("system_ip"));
			}
		} catch (Exception e) {
			logger.error("SystemId 为："+systemId+" ServerIp acquisition failure",e);
		}
		if(StringUtils.isEmpty(hostIp)){
			logger.error("SystemId 为："+systemId+" ServerIp is empty");
		}
		return hostIp;
	}
	public List<FileComment> getMissionFileInformations(Long missionId){
		List<FileComment> pushFileList = new LinkedList<FileComment>();
		StringBuffer searchSQL = new StringBuffer();
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("file_name");
		fields.add("md5_value");
		ArrayList<Map<String, String>> rs = null;
		try {
			rs = dao.dbSelect("select mfi.file_name,mfi.md5_value from mission_file_information mfi where mfi.mission_id='"+missionId.longValue()+"' order by mfi.id asc", fields);
			if(rs!=null && rs.size()>0){
				for (Iterator iterator = rs.iterator(); iterator.hasNext();) {
					Map<String, String> map = (Map<String, String>) iterator.next();
					
//					String[] strings = new String[]{map.get("file_name"),map.get("md5_value")};
					pushFileList.add(new FileComment(map.get("file_name"),0,0,map.get("md5_value")));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return pushFileList;
	}
	
	public List<FileComment> getMissionFileInformations2(Long missionId){
		List<FileComment> pushFileList = new LinkedList<FileComment>();
		StringBuffer searchSQL = new StringBuffer();
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("file_name");
		fields.add("md5_value");
		ArrayList<Map<String, String>> rs = null;
		try {
			rs = dao.dbSelect("select mfi.file_name,mfi.md5_value from mission_file_information mfi where mfi.mission_id='"+missionId.longValue()+"' order by mfi.id asc", fields);
			if(rs!=null && rs.size()>0){
				for (Iterator iterator = rs.iterator(); iterator.hasNext();) {
					Map<String, String> map = (Map<String, String>) iterator.next();
					
//					String[] strings = new String[]{map.get("file_name"),map.get("md5_value")};
					pushFileList.add(new FileComment(map.get("file_name"),0,0,map.get("md5_value")));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return pushFileList;
	}
	public boolean checkFileIntegrity(String fileSrc,String md5Val){
		File file = new File(fileSrc);
		try {
			//不存在 Return false
			if(!file.exists()){
				return false;
			}
			
			//比较MD5值
			String md5Val0 = MD5Util.getFileMD5String(file);
			if(!md5Val0.equals(md5Val)){
				file.delete();
				return false;
			}else
				return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
	public Task4 getTask4ById(Long missionId){
		if(missionId == null || missionId.longValue() == 0){
			return null;
		}
		Task4 task4 = new Task4();
		StringBuffer searchSQL = new StringBuffer();
		searchSQL.append("select mpt4.command_Type, ");
		searchSQL.append("mpt4.command_ename, ");
		searchSQL.append("mpt4.command_para, ");
		searchSQL.append("mpt4.node_groups_id, ");
		searchSQL.append("mpt4.NODE_IPS_ID, ");
		searchSQL.append("mpt4.max_return, ");
		searchSQL.append("mpt4.version ");
		searchSQL.append("from mission_parameter_table4 mpt4 ");
		searchSQL.append("where mpt4.mission_Id='"+missionId.longValue()+"' ");
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("command_Type");
		fields.add("command_ename");
		fields.add("command_para");
		fields.add("node_groups_id");
		fields.add("NODE_IPS_ID");
		fields.add("version");
		ArrayList<Map<String, String>> rs = null;
//		MissionResult result = new MissionResult();
		try {
			rs = dao.dbSelect(searchSQL.toString(), fields);
			String split = ";";
			//-- 整理到对象集合
			if(rs!=null && rs.size()>0){
				Map<String, String> maps = rs.get(0);
				task4.setCommandName(maps.get("command_ename"));
				task4.setCommandType(StringUtils.isEmpty(maps.get("command_Type"))?null:Long.parseLong(maps.get("command_Type")));
				task4.setVersion(StringUtils.isEmpty(maps.get("version"))?null:Long.parseLong(maps.get("version")));
				task4.setNodeGroupsId(StringUtils.isEmpty(maps.get("node_groups_id"))?null:maps.get("node_groups_id"));
				task4.setNodeIpsId(StringUtils.isEmpty(maps.get("NODE_IPS_ID"))?null:maps.get("NODE_IPS_ID"));
				if(StringUtils.isNotEmpty(maps.get("command_para"))){
					StringBuffer newStrs = new StringBuffer();
					String[] strs = maps.get("command_para").split(";");
					for(String str : strs){
						if(DateUtil.isDate(str,Constants.COMMON_DATE_FORMAT)){
							newStrs.append(split+format.parse(str).getTime());
						}else{
							newStrs.append(split+str);
						}
					}
					newStrs = newStrs.length()>0?newStrs.delete(0, split.length()):newStrs;
					task4.setCommandParam(newStrs.toString());
				}
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return task4;
	}
	public Task6 getTask6ById(Long missionId){
		if(missionId == null || missionId.longValue() == 0){
			return null;
		}
		Task6 task6 = new Task6();
		StringBuffer searchSQL = new StringBuffer();
		searchSQL.append("select mpt6.command_Type, ");
		searchSQL.append("mpt6.command_ename, ");
		searchSQL.append("mpt6.command_para, ");
		searchSQL.append("mpt6.node_groups_id, ");
		searchSQL.append("mpt6.NODE_IPS_ID, ");
		searchSQL.append("mpt6.source_path, ");
		searchSQL.append("mpt6.target_path, ");
		searchSQL.append("mpt6.check_value, ");
		searchSQL.append("mpt6.old_task_id, ");
		searchSQL.append("to_char(mpt6.start_time,'"+Constants.DB_DATE_FORMAT+"') start_time, ");
		searchSQL.append("mpt6.version ");
		searchSQL.append("from mission_parameter_table6 mpt6 ");
		searchSQL.append("where mpt6.mission_Id='"+missionId.longValue()+"' ");
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("command_Type");
		fields.add("command_ename");
		fields.add("command_para");
		fields.add("source_path");
		fields.add("target_path");
		fields.add("check_value");
		fields.add("start_time");
		fields.add("node_groups_id");
		fields.add("NODE_IPS_ID");
		fields.add("old_task_id");
		fields.add("version");
		ArrayList<Map<String, String>> rs = null;
//		MissionResult result = new MissionResult();
		try {
			rs = dao.dbSelect(searchSQL.toString(), fields);
//			String split = ";";
			//-- 整理到对象集合
			if(rs!=null && rs.size()>0){
				Map<String, String> maps = rs.get(0);
				task6.setCommandName(maps.get("command_ename"));
				task6.setCommandType(StringUtils.isEmpty(maps.get("command_Type"))?null:Long.parseLong(maps.get("command_Type")));
				task6.setCommandParam(maps.get("command_para"));
				task6.setVersion(StringUtils.isEmpty(maps.get("version"))?null:Long.parseLong(maps.get("version")));
				task6.setNodeGroupsId(StringUtils.isEmpty(maps.get("node_groups_id"))?null:maps.get("node_groups_id"));
				task6.setNodeIpsId(StringUtils.isEmpty(maps.get("NODE_IPS_ID"))?null:maps.get("NODE_IPS_ID"));
				task6.setOldTaskId(StringUtils.isEmpty(maps.get("old_task_id"))?null:Long.parseLong(maps.get("old_task_id")));
				task6.setFileName(maps.get("source_path"));
				task6.setDestPath(maps.get("target_path"));
				task6.setMd5Value(maps.get("check_value"));
				task6.setUpgradeTime(StringUtils.isEmpty(maps.get("start_time"))?null:format.parse(maps.get("start_time")).getTime());
//				if(StringUtils.isNotEmpty(maps.get("command_para"))){
//					StringBuffer newStrs = new StringBuffer();
//					String[] strs = maps.get("command_para").split(";");
//					for(String str : strs){
//						if(DateUtil.isDate(str,Constants.COMMON_DATE_FORMAT)){
//							newStrs.append(split+format.parse(str).getTime());
//						}else{
//							newStrs.append(split+str);
//						}
//					}
//					newStrs = newStrs.length()>0?newStrs.delete(0, split.length()):newStrs;
//				}
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return task6;
	}

	/**
	 * @time Oct 25, 2011-11:00:08 AM
	 * 文件推送任务 执行结果查询
	 * 文件推送结果 result 的值有
	 *  3 任务信息下发中
	 * 40 任务信息下发成功（信息有NMSAgent端提供）
	 * 41 任务信息下发失败（信息有DataController端提供）
	 * @param missionId	任务Id
	 * @param missionState	任务的状态
	 * 
	 */
	public ArrayList<MissionResult> getMissionResultsForTask(long missionId,int missionType){
		if(missionType==0 || missionId == 0l){
			return null;
		}
		ArrayList<MissionResult> mrList = new ArrayList<MissionResult>();
		StringBuffer searchSQL = new StringBuffer();
		searchSQL.append("select mrt.mission_id, ");
		searchSQL.append("nt.node_ip, ");
		searchSQL.append("mrt.seq_id, ");
		searchSQL.append("nvl(mrt.result,3) result ");
		searchSQL.append("from mission_result_table"+missionType+" mrt ");
		searchSQL.append("left join (select distinct node_ip,ipn,seq_id from node_table n ) nt on nt.seq_id=mrt.seq_id ");
		searchSQL.append("where mrt.mission_id = "+missionId+" ");
		searchSQL.append("and nvl(mrt.result,3) =3 ");	
		searchSQL.append(getIpnSelect());
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("mission_id");
		fields.add("node_ip");
		fields.add("result");
		fields.add("seq_id");
		ArrayList<Map<String, String>> rs = null;
		try {
			rs = dao.dbSelect(searchSQL.toString(), fields);
			//-- 整理到对象集合
			if(rs!=null && rs.size()>0){
				for(Map<String, String> maps : rs){
					MissionResult result = new MissionResult();
					result.setMissionId(Long.parseLong(maps.get("mission_id")));
					result.setNodeIp(maps.get("node_ip"));
					result.setUuid(maps.get("seq_id")==null ? null:Long.parseLong(maps.get("seq_id")));
					result.setResult(maps.get("result")==null ? null:Long.parseLong(maps.get("result")));
					mrList.add(result);
				}
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return mrList;
	}
	
	/**
	 * @time Oct 25, 2011-11:00:08 AM
	 * 文件推送任务 执行结果查询
	 * 文件推送结果 result 的值有
	 *  3 任务信息下发中
	 * 40 任务信息下发成功（信息有NMSAgent端提供）
	 * 41 任务信息下发失败（信息有DataController端提供）
	 * @param missionId	任务Id
	 * @param missionState	任务的状态
	 * 
	 */
	public ArrayList<MissionResult> getMissionResultsForLoopTask(long missionId,int missionType,Integer resultVal){
		if(missionType==0 || missionId == 0l){
			return null;
		}
		
		ArrayList<MissionResult> mrList = new ArrayList<MissionResult>();
		StringBuffer searchSQL = new StringBuffer();
		searchSQL.append("select mrt.mission_id, ");
		searchSQL.append("nt.node_ip, ");
		searchSQL.append("mrt.seq_id, ");
		searchSQL.append("nvl(mrt.result,3) result ");
		searchSQL.append("from mission_result_table"+missionType+" mrt ");
		searchSQL.append("left join loopmission_state_table lmst on lmst.cur_mission_id = mrt.mission_id ");
		searchSQL.append("left join (select distinct node_ip,ipn,seq_id from node_table n) nt on nt.seq_id=mrt.seq_id ");
		searchSQL.append("where lmst.mission_id = "+missionId+" ");
		
		if(resultVal != null){
			searchSQL.append("and nvl(mrt.result,3) ="+resultVal.intValue());
		}
		searchSQL.append(getIpnSelect());
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("mission_id");
		fields.add("node_ip");
		fields.add("result");
		fields.add("seq_id");
		ArrayList<Map<String, String>> rs = null;
		try {
			logger.debug(searchSQL.toString());
			rs = dao.dbSelect(searchSQL.toString(), fields);
			//-- 整理到对象集合
			if(rs!=null && rs.size()>0){
				for(Map<String, String> maps : rs){
					MissionResult result = new MissionResult();
					result.setMissionId(Long.parseLong(maps.get("mission_id")));
					result.setNodeIp(maps.get("node_ip"));
					result.setUuid(maps.get("seq_id")==null ? null:Long.parseLong(maps.get("seq_id")));
					result.setResult(maps.get("result")==null ? null:Long.parseLong(maps.get("result")));
					mrList.add(result);
				}
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return mrList;
	}
	
	//获取
	public ArrayList<MissionResult> getMissionResultsForLoopTaskByCurMissId(long curMissionId,Integer resultVal){
		int missionType = 4;
		if(curMissionId == 0l || resultVal==null){
			return null;
		}
		
		ArrayList<MissionResult> mrList = new ArrayList<MissionResult>();
		StringBuffer searchSQL = new StringBuffer();
		searchSQL.append("select mrt.mission_id, ");
		searchSQL.append("nt.node_ip, ");
		searchSQL.append("mrt.seq_id, ");
		searchSQL.append("mrt.result result ");
		searchSQL.append("from mission_result_table"+missionType+" mrt ");
//		searchSQL.append("left join loopmission_state_table lmst on lmst.cur_mission_id = mrt.mission_id ");
		searchSQL.append("left join (select distinct node_ip,ipn,seq_id from node_table n) nt on nt.seq_id=mrt.seq_id ");
		searchSQL.append("where mrt.mission_id = "+curMissionId+" ");
		
		if(resultVal != null){
			searchSQL.append("and mrt.result ="+resultVal.intValue());
		}
		searchSQL.append(getIpnSelect());
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("mission_id");
		fields.add("node_ip");
		fields.add("result");
		fields.add("seq_id");
		ArrayList<Map<String, String>> rs = null;
		try {
			logger.debug(searchSQL.toString());
			rs = dao.dbSelect(searchSQL.toString(), fields);
			//-- 整理到对象集合
			if(rs!=null && rs.size()>0){
				for(Map<String, String> maps : rs){
					MissionResult result = new MissionResult();
					result.setMissionId(Long.parseLong(maps.get("mission_id")));
					result.setNodeIp(maps.get("node_ip"));
					result.setUuid(maps.get("seq_id")==null ? null:Long.parseLong(maps.get("seq_id")));
					result.setResult(maps.get("result")==null ? null:Long.parseLong(maps.get("result")));
					mrList.add(result);
				}
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return mrList;
	}
	/**
	 * 批量更新任务结果方法业务流程
	 * 	1、检查数据完整性：任务ID、任务类型、SeqID、任务结果 均不能为空
	 * 	2、数据规整
	 * 		周期任务结果处理流程：（判定 loopFlag 为1或-1）
	 * 		2.1、获取 获取任务轮次信息；
	 * 		2.2、规整数据
	 * 非周期任务结果处理流程：
	 * 
	 * @time Nov 16, 2011-2:00:46 PM
	 * @param mr2List
	 */
	public void updateMissionResult2ByBatch(int missiontype,List<MissionResult2> mr2List) throws Exception {
		List<String[]> params = new ArrayList<String[]>();
		
		//-try{}finally{} 用于清理数据库连接
		try {
			
			//-任务结果List 非空判断
			if(mr2List!= null && mr2List.size()>0){
				
				//- 声明 本次业务操作的各对象变量
				EmailService emailService = new EmailService(dao);	//邮件功能
				String sql = getUpdateSQL(missiontype);		//获取更新sql
				int count = 0;		//计数器
				StringBuffer cancelMissionStore = new StringBuffer(",");	//撤销任务ID暂存
				
				List<MissionStateTable> loopMissionIdofInsertRltList = new ArrayList<MissionStateTable>();//记录有结果录入的周期任务的总id，并进行轮次检查和更新（因为如果没轮次了再检测，可能任务的总状态就被统计为已完成了，之后的结果也就不会被统计上了）
				
				//- 遍历任务结果集
				Iterator<MissionResult2> mrIte = mr2List.iterator();
				while (mrIte.hasNext()) {
				     
					/* 任务结果： 完整性校验、数据规整、保存 等操作 */
					MissionResult2 mr = (MissionResult2) mrIte.next();
					
					//- 完整性校验：
					if(mr == null){		//无效跳过
						continue;
					}
					
					if(mr.getMissionId() ==null 
							|| mr.getMissionType() == null 
							|| mr.getUuid() ==null
//							|| mr.getResult() == null //结果为空时，触发器会采用之前的结果，回传文件的结果信息result为null，所以之前的回传文件都为空
							){		//无效跳过
						continue;
					}
					
					
					//- 数据规整：周期任务判断及处理
					//- 任务类型4 周期任务结果处理 标识判断，loopFlag: 1周期任务标识  -1:Agent无法判断任务类型，先尝试按周期任务处理
					
					Long resultsMissionId = mr.getMissionId();
					if(mr.getMissionType().longValue() == 4l
							&& mr.getLoopFlag()!= null 
							&& (mr.getLoopFlag().longValue()==1l || mr.getLoopFlag().longValue()==-1l)){
						
						//-- 获取任务
						MissionStateTable mission = Common.getLoopMissionInfoMap().get(mr.getMissionId());//总任务id
						
						loopMissionIdofInsertRltList.add(mission);
						
						if(mission==null){
							mission = getMessionById(mr.getMissionId());
							Common.getLoopMissionInfoMap().put(mr.getMissionId(),mission);
						}
						
						LoopMissionRoundInfo roundInfo = this.getRoundInfoFromCommonList(mr);
						
						if(roundInfo == null){
							
							//-- 检查并预置轮次信息(执行撤销时不再运行)
							if(mission.getMissionState()!=6l && mission.getMissionState()!=7l){
								checkAndInitMissionCycle(mission);		//检查预置轮次数
							}else{
								this.updateLoopMissionRoundInfo(Common.getLoopMissionRoundInfoList(), mission.getMissionId());		//更新指定周期任务ID的轮次信息
							}
							
							//-- 再次获取 缓存中的信息 否则 查询数据库（比较旧的轮次信息情况）
							roundInfo = this.getRoundInfoFromCommonList(mr);
							if(roundInfo ==null){
								
								roundInfo = this.getRoundInfoFromDB(mr);
								//-- 该任务的轮次信息不存在  通过loopFlag 判断是否继续执行保存
								/* loopFlag 为1 周期任务结果，则抛弃，为-1 未知情况，继续非周期任务信息结果的处理 */
								if(roundInfo == null){
									if(mr.getLoopFlag().longValue()==1l ){	//无效的 周期任务数据 抛弃
										logger.warn("Unable to find cycle information of the cycle task result information 【"+(JSONObject.fromObject(mr).toString())+"】");
										continue;
									}else{	//Agent无法判断任务类型 可能为一次性执行的任务
//									logger.info("对应的 roundInfo is null"+(JSONObject.fromObject(mr).toString()));
									}
								}else{
									List<LoopMissionRoundInfo> rList = Common.getLoopMissionRoundInfoList().get(mr.getMissionId());
									if(rList == null){
										rList = new LinkedList<LoopMissionRoundInfo>();
										Common.getLoopMissionRoundInfoList().put(mr.getMissionId(),rList);
									}
									rList.add(0, roundInfo);
								}
							}
							
						}
						
						//-- 当前轮次校验
						if(roundInfo!=null && roundInfo.getMissionState().longValue() == 0l){	//结果未被初始化，周期内仅执行一次
//							MissionStateTable mission = Common.getLoopMissionInfoMap().get(mr.getMissionId());
							initLoopMissionResults2(roundInfo.getCurMissionId(), mission.getNodeGroupsId(),mission.getNodeIpsId(),40);//初始化无需下发的结果信息 3开始执行 40已下发
							updateLoopMissionState(roundInfo.getCurMissionId(), 2);
							roundInfo.setMissionState(2l);
//							checkAndInitMissionCycle(mission);		//检查预置轮次数
						}else 
						if(roundInfo!=null && roundInfo.getMissionState().longValue() == 1l){	//结果已经初始化，周期内仅执行一次
//							MissionStateTable mission = Common.getLoopMissionInfoMap().get(mr.getMissionId());
							updateLoopMissionState(roundInfo.getCurMissionId(), 2);
							roundInfo.setMissionState(2l);
							
//							checkAndInitMissionCycle(mission);		//检查预置轮次数
						}
						
						/**无法获取轮次信息的数据跳过
						 * */
						if(roundInfo!=null){	//轮次周期 状态为“已创建”，这变更状态并初始化下一轮次
							resultsMissionId = roundInfo.getCurMissionId().longValue();
						}
						
						logger.debug("MissionResult2 missionId 变更 :>"+(mr.getMissionId()+" ---> "+roundInfo.getCurMissionId().longValue()));
					
						if(mission.getMissionState().longValue()==6){
							
							//-- 检查是否已发出通知
							if(roundInfo!=null){
								if(cancelMissionStore.indexOf(","+mr.getUuid()+":"+mr.getMissionId()+",")==-1){
									cancelMissionStore.append(mr.getUuid()+":"+mr.getMissionId()+",");
									if(mr.getResult()==null || (mr.getResult().longValue() != 6l && mr.getResult().longValue() != 7l )){
										MissionResult result = new MissionResult();
										result.setUuid(mr.getUuid());
										Common.sendMissionInfo(mission,new NMSClientTask4Cancel(Common.getNodeIpByUUID(mr.getUuid()),Constants.SSL_CLIENT_PORT,mission.getMissionId()),mr.getUuid(), 1,roundInfo.getStartTime().getTime(),roundInfo.getEndTime().getTime());
									}
								}
							}
						}
					}
					
					
					//-- 任务结果保存
					String [] strs = null;
					if(mr.getMissionType()!= null && mr.getMissionType().longValue()==4l){
						strs = new String[6];
						strs[0] = mr.getResult()==null?null:mr.getResult()+"";
						strs[1] = (StringUtils.isEmpty(mr.getDescription()) || "null".equalsIgnoreCase(mr.getDescription()))?"":(mr.getDescription()+"\n");
						strs[2] = mr.getFileInfo();
						strs[3] = mr.getResultDetail()==null?null:mr.getResultDetail()+"";
						strs[4] = resultsMissionId.longValue()+"";
						strs[5] = mr.getUuid()+"";
						if(StringUtils.isNotEmpty(strs[2])){
							logger.debug("准备入库(含回传文件) ："+Arrays.toString(strs));
						}
					}else{
						strs = new String[4];
						strs[0] = mr.getResult()==null?"":mr.getResult()+"";
						strs[1] = (StringUtils.isEmpty(mr.getDescription()) || "null".equalsIgnoreCase(mr.getDescription()))?"":(mr.getDescription()+"\n");
						strs[2] = mr.getMissionId()+"";
						strs[3] = mr.getUuid()+"";
						
					}
					logger.debug("准备入库 ："+Arrays.toString(strs));
					params.add(strs);
					count++;
					
					//2013-6-24  hyx  注释以下代码某个节点的执行结果失败不发送邮件，任务最终完成后发一封邮件即可（包括统计信息，失败和成功节点数）
					//-- 任务失败结果告警
                   /*
                    int  result = mr.getResult()==null?-1:mr.getResult().intValue();
					if(result == 1){	//需要告警
						emailService.sendEmailForMissionBySeqId(mr.getMissionId(),missiontype, mr.getUuid(), createEmailInfoForFailResult(mr));
				    }
				    */	
					if(count == Constants.DB_EXECUTE_BATCH){
						dao.dbUpdateByBatch(sql, params);
						count = 0;
						params.clear();
					}
				}
				
				if(loopMissionIdofInsertRltList!=null && loopMissionIdofInsertRltList.size()>0) {//说明有周期任务的结果入库，就需要检测周期任务的轮次
					for(MissionStateTable missTmp:loopMissionIdofInsertRltList) {
						//-- 检查并预置轮次信息(执行撤销时不再运行)
						if(missTmp!=null) {
							if(missTmp.getMissionState()!=null 
									&& missTmp.getMissionState()!=6l && missTmp.getMissionState()!=7l){
								checkAndInitMissionCycle(missTmp);		//检查预置轮次数
							}else{
								this.updateLoopMissionRoundInfo(Common.getLoopMissionRoundInfoList(), missTmp.getMissionId());//更新指定周期任务ID的轮次信息(从数据库到缓存)
							}
						}
						
					}
				}
				
				if (count > 0) {
					dao.dbUpdateByBatch(sql, params);
					count = 0;
					params.clear();
				}
			}
			logger.info("任务结果批量入库保存完成");
//		} catch (Exception e) {
//			logger.error("批量更新异常 \n"+"",e);
		}finally{
			dao.clearConn();
		}
	}
	
	public static void main(String []args){
		CommonDao dao;
		try {
			
			BoneCPPool.initPool();			
			dao = new CommonDao();
			UpgradeService service = new UpgradeService(dao);
			service.updateLoopMissionInfo(Common.getLoopMissionInfoMap(), null);
			Map<Long , MissionStateTable> loopMissionInfoMap = new HashMap<Long, MissionStateTable>();
			loopMissionInfoMap = Common.getLoopMissionInfoMap();
			System.out.println(Common.getLoopMissionInfoMap().size());
//			service.updateLoopMissionComplete();
//			service.getMissionForAgentStart(89l);
//			service.checkTimeoutLoopMisssionAndAddResult();//测试：超时周期任务的检查
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
////		service.checkAndUpdateMissionComplete() ;
////		service.checkAndUpdateLoopMissionComplete();
////		service.updateCommonMissionComplete();//任务状态：成功（31）、部分成功（32）、全部失败（30）
//		
//	    List<MissionResult2> mr2List = new ArrayList<MissionResult2>();
//		mr2List.add(new MissionResult2(1274523l));
//		mr2List.add(new MissionResult2(1274523l));		
//		mr2List.add(new MissionResult2(1274538l));		
//		mr2List.add(new MissionResult2(1274582l));		
//		mr2List.add(new MissionResult2(1274538l));		
//		
//		service.updateCommonMissionStateDesc(1, mr2List);
//		service.updateCommonMissionStateDesc(1, null);
//		service.updateCommonMissionStateDesc(4, null);
//		service.updateCommonMissionStateDesc(6, null);
//		service.updateLoopMissionStateDesc(mr2List);
		
//		service.getMissionForAgentStart(66l);
//		service.updateLoopMissionInfo(Common.getLoopMissionInfoMap(), null);
//		service.updateLoopMissionRoundInfo(Common.getLoopMissionRoundInfoList(), null);
//		service.checkAndInitMissionCycle(Common.getLoopMissionInfoMap().get(1187604l));
		
	}
	
	public LoopMissionRoundInfo getRoundInfoFromCommonListByID(Long missionId,Long curMissionId){
		List<LoopMissionRoundInfo> roundList = Common.getLoopMissionRoundInfoList().get(missionId);
		if(roundList!= null && roundList.size()>0){
			for (Iterator roundIte = roundList.iterator(); roundIte.hasNext();) {
				LoopMissionRoundInfo roundInfo = (LoopMissionRoundInfo) roundIte.next();
				if(curMissionId!=null && curMissionId.longValue() == roundInfo.getCurMissionId().longValue()){
					return roundInfo;
				}
			}
		}
		 return null;
	}
	
	public LoopMissionRoundInfo getRoundInfoFromCommonList(MissionResult2 mr){
		List<LoopMissionRoundInfo> roundList = Common.getLoopMissionRoundInfoList().get(mr.getMissionId());
		if(roundList!= null && roundList.size()>0){

//			pl("mr.getMissionId()"+mr.getMissionId());
//			pl("mr.getMissionType()"+mr.getMissionType());
//			pl("mr.getLoopFlag()"+mr.getLoopFlag());
//			pl("mr.getResult()"+mr.getResult());
//			pl("mr.getUuid()"+mr.getUuid());
//			pl("mr.getStartTime()"+mr.getStartTime());
//			pl("mr.getEndTime()"+mr.getEndTime());
//			pl("mr.getDescription()"+mr.getDescription());
//			pl("mr.getFileInfo()"+mr.getFileInfo());
//			pl("mr.getText()"+mr.getText());
			if(mr.getResult()!= null &&(mr.getResult()==6 || mr.getResult()==7)){
				return roundList.get(roundList.size()-1);
			}else{
				for (Iterator roundIte = roundList.iterator(); roundIte.hasNext();) {
					LoopMissionRoundInfo roundInfo = (LoopMissionRoundInfo) roundIte.next();
					if(mr.getStartTime()!=null && roundInfo.getStartTime().getTime()<= mr.getStartTime() && roundInfo.getEndTime().getTime()> mr.getStartTime()){
						return roundInfo;
					}
				}
			}
		}
		 return null;
	}
public LoopMissionRoundInfo getRoundInfoFromDBByID(Long curMissionId){
		
		LoopMissionRoundInfo roundInfo = null;
		StringBuffer searchSQL = new StringBuffer();
		searchSQL.append("select lmst.cur_mission_id, ");
		searchSQL.append("lmst.mission_id, ");
		searchSQL.append("lmst.mission_state, ");
		searchSQL.append("to_char(lmst.start_time,'"+Constants.DB_DATE_FORMAT+"') start_time,");
		searchSQL.append("to_char(lmst.end_time,'"+Constants.DB_DATE_FORMAT+"') end_time ");
		searchSQL.append("from loopmission_state_table lmst ");
		searchSQL.append("where 1=1 ");
		searchSQL.append("and lmst.cur_mission_id = ? ");
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("cur_mission_id");
		fields.add("mission_id");
		fields.add("mission_state");
		fields.add("start_time");
		fields.add("end_time");
		String [] params = new String[]{curMissionId.longValue()+""};
		
		ArrayList<Map<String, String>> rs = null;
		try {
			rs = dao.dbSelect(searchSQL.toString(), fields, params);
			if(rs!=null && rs.size()>0){
				for(Map<String, String> maps : rs){
					roundInfo = new LoopMissionRoundInfo();
					roundInfo.setMissionId(StringUtils.isEmpty(maps.get("mission_id"))?null:Long.parseLong(maps.get("mission_id")));
					roundInfo.setCurMissionId(StringUtils.isEmpty(maps.get("cur_mission_id"))?null:Long.parseLong(maps.get("cur_mission_id")));
					roundInfo.setMissionState(StringUtils.isEmpty(maps.get("mission_state"))?null:Long.parseLong(maps.get("mission_state")));
					roundInfo.setStartTime(StringUtils.isEmpty(maps.get("start_time"))?null:format.parse(maps.get("start_time")));
					roundInfo.setEndTime(StringUtils.isEmpty(maps.get("end_time"))?null:format.parse(maps.get("end_time")));
				}
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return roundInfo;
	}
	public LoopMissionRoundInfo getRoundInfoFromDB(MissionResult2 mr){
		
		LoopMissionRoundInfo roundInfo = null;
		StringBuffer searchSQL = new StringBuffer();
		searchSQL.append("select lmst.cur_mission_id, ");
		searchSQL.append("lmst.mission_id, ");
		searchSQL.append("lmst.mission_state, ");
		searchSQL.append("to_char(lmst.start_time,'"+Constants.DB_DATE_FORMAT+"') start_time,");
		searchSQL.append("to_char(lmst.end_time,'"+Constants.DB_DATE_FORMAT+"') end_time ");
		searchSQL.append("from loopmission_state_table lmst ");
		searchSQL.append("where lmst.mission_id=? ");
		searchSQL.append("and lmst.start_time<=to_date(?,'"+Constants.DB_DATE_FORMAT+"') ");
//		searchSQL.append("and lmst.end_time>=to_date(?,'"+Constants.DB_DATE_FORMAT+"') ");
		/**
		 * 去掉sql语句中的等号的原因：
		 *     NC根据整个任务的开始和结束时间执行时，有可能会比DC多一个周期（最后一个周期不满设定的间隔时间），因为DC将最后一个不满间隔的周期抛弃了，而NC却执行了，
		 *     所以此时如果NC的最后一个周期结果被收集过来，首先判断缓存中是否有此轮次（NC.startTime>=轮次.startTime && NC.startTime<轮次.endTime）,
		 *     结果没有，就会通过此sql从数据库中查找，但是此时的 NC.startTime和轮次.endTime比较时就加了等号，且比较的是日期格式的（只比到了秒）（如果比较的是long格式，NC.startTime肯定会大于最后一个周期的endTime，可能不会出现等于的情况），
		 *     所以NC最后一个周期的结果就入到了上一个周期里
		 */
		searchSQL.append("and lmst.end_time>to_date(?,'"+Constants.DB_DATE_FORMAT+"') ");
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("cur_mission_id");
		fields.add("mission_id");
		fields.add("mission_state");
		fields.add("start_time");
		fields.add("end_time");
//		pl(mr.getMissionId());
//		pl(mr.getUuid());
//		pl(mr.getResult());
//		pl(mr.getLoopFlag());
//		pl(mr.getStartTime());
//		pl(mr.getEndTime());
//		pl(mr.getFileInfo());
//		pl(mr.getDescription());
		try {
			logger.info("getRoundInfoFromDB方法：mr.getStartTime()="+mr.getStartTime());
			String startTime = new SimpleDateFormat(Constants.COMMON_DATE_FORMAT).format(mr.getStartTime());
			String [] params = new String[]{mr.getMissionId()+"",startTime,startTime};
			
			ArrayList<Map<String, String>> rs = null;
			rs = dao.dbSelect(searchSQL.toString(), fields, params);
			if(rs!=null && rs.size()>0){
				for(Map<String, String> maps : rs){
					roundInfo = new LoopMissionRoundInfo();
					roundInfo.setMissionId(StringUtils.isEmpty(maps.get("mission_id"))?null:Long.parseLong(maps.get("mission_id")));
					roundInfo.setCurMissionId(StringUtils.isEmpty(maps.get("cur_mission_id"))?null:Long.parseLong(maps.get("cur_mission_id")));
					roundInfo.setMissionState(StringUtils.isEmpty(maps.get("mission_state"))?null:Long.parseLong(maps.get("mission_state")));
					roundInfo.setStartTime(StringUtils.isEmpty(maps.get("start_time"))?null:format.parse(maps.get("start_time")));
					roundInfo.setEndTime(StringUtils.isEmpty(maps.get("end_time"))?null:format.parse(maps.get("end_time")));
				}
			}
		} catch (Exception e) {
			logger.error("Get the result corresponding to wheel information abnormal task type from DB："+mr==null?"":mr.getMissionType(),e);
		}finally{
			dao.clearConn();
		}
		return roundInfo;
	}
	/**
	 * 根据MissionID 更新指定的 周期任务信息
	 * @time Feb 10, 2012-2:23:35 PM
	 * @param missionInfoMap
	 * @param missionId
	 * @return
	 */
	public Map<Long, MissionStateTable> updateLoopMissionInfo(Map<Long, MissionStateTable> missionInfoMap,Long missionId) {
		//-- 查询可执行的任务
		StringBuffer searchSQL = new StringBuffer();
		searchSQL.append("select mst.mission_id,");
		searchSQL.append("mst.mission_type,");
		searchSQL.append("mst.mission_state,");
		searchSQL.append("mst.system_id,");
		searchSQL.append("mst.group_id,");
		searchSQL.append("mpt4.node_groups_id,");
		searchSQL.append("mpt4.node_ips_id,");//2015-11-23 hyx 增加任务的节点信息（由于之前只查询了节点组的信息，所以在结果入库的时候，以缓存中的周期任务信息的节点组和节点作为参数调用initLoopMissionResults2方法，导致将节点组内所有的节点都进行了初始化（如果新建任务的时候只选择了某些节点，此处就出现问题了），而其他地方（如任务新建的时候）调用initLoopMissionResults2的时候，是直接已参数表的节点和节点为参数，所以不会出现问题）
		searchSQL.append("to_char(mst.start_time,'"+Constants.DB_DATE_FORMAT+"') start_time,");
		searchSQL.append("to_char(mst.end_time,'"+Constants.DB_DATE_FORMAT+"') end_time,");
		searchSQL.append("mst.is_loop,");
		searchSQL.append("mst.loop_delay ");
		searchSQL.append("from mission_state_table mst ");
		searchSQL.append("left join mission_parameter_table4 mpt4 on mst.mission_id = mpt4.mission_id ");
		searchSQL.append("where mst.end_time>sysdate ");
		searchSQL.append("and mst.mission_state in (1,2,5,6) ");
		searchSQL.append("and mst.is_loop = 1 ");
		if(missionId!= null && missionId.longValue()!=0){
			searchSQL.append("and mst.mission_id = '"+missionId.longValue()+"' ");
		}
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("mission_id");
		fields.add("mission_type");
		fields.add("mission_state");
		fields.add("system_id");
		fields.add("group_id");
		fields.add("node_groups_id");
		fields.add("node_ips_id");
		fields.add("start_time");
		fields.add("end_time");
		fields.add("is_loop");
		fields.add("loop_delay");
		ArrayList<Map<String, String>> rs = null;
		ArrayList<MissionStateTable> mstList = new ArrayList<MissionStateTable>();
		try {
			rs = dao.dbSelect(searchSQL.toString(), fields);
			if(rs!=null && rs.size()>0){
				for(Map<String, String> maps : rs){
					MissionStateTable mission = new MissionStateTable();
					mission.setMissionId(StringUtils.isEmpty(maps.get("mission_id"))?null:Long.parseLong(maps.get("mission_id")));
					mission.setMissionType(StringUtils.isEmpty(maps.get("mission_type"))?null:Long.parseLong(maps.get("mission_type")) );
					mission.setMissionState(StringUtils.isEmpty(maps.get("mission_state"))?null:Long.parseLong(maps.get("mission_state")));
					mission.setSystemId(StringUtils.isEmpty(maps.get("system_id"))?null:Long.parseLong(maps.get("system_id")));
					mission.setGroupId(StringUtils.isEmpty(maps.get("group_id"))?null:Long.parseLong(maps.get("group_id")));
					mission.setNodeGroupsId(StringUtils.isEmpty(maps.get("node_groups_id"))?null:maps.get("node_groups_id"));
					mission.setNodeIpsId(StringUtils.isEmpty(maps.get("node_ips_id"))?null:maps.get("node_ips_id"));
					mission.setStartTime(StringUtils.isEmpty(maps.get("start_time"))?null:format.parse(maps.get("start_time")));
					mission.setEndTime(StringUtils.isEmpty(maps.get("end_time"))?null:format.parse(maps.get("end_time")));
					mission.setLoopFlag(StringUtils.isEmpty(maps.get("is_loop"))?null:Long.parseLong(maps.get("is_loop")));
					mission.setLoopDelay(StringUtils.isEmpty(maps.get("loop_delay"))?null:Long.parseLong(maps.get("loop_delay")));
					missionInfoMap.put(mission.getMissionId(), mission);
				}
			}
			return missionInfoMap;
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return missionInfoMap;
	}
	
	//根据curMissionId查找主任务信息
	public MissionStateTable getMissionInfoByCurMissionId(Long curMissionId) {
		MissionStateTable mission = null;
		if(curMissionId!=null) {			
			//-- 查询可执行的任务
			StringBuffer searchSQL = new StringBuffer();
			searchSQL.append("select mst.mission_id,");
			searchSQL.append("mst.mission_type,");
			searchSQL.append("mst.mission_state,");
			searchSQL.append("mst.system_id,");
			searchSQL.append("mst.group_id,");
			searchSQL.append("mpt4.node_groups_id,");
			searchSQL.append("to_char(mst.start_time,'"+Constants.DB_DATE_FORMAT+"') start_time,");
			searchSQL.append("to_char(mst.end_time,'"+Constants.DB_DATE_FORMAT+"') end_time,");
			searchSQL.append("mst.is_loop,");
			searchSQL.append("mst.loop_delay ");
			searchSQL.append("from mission_state_table mst ");
			searchSQL.append("left join mission_parameter_table4 mpt4 on mst.mission_id = mpt4.mission_id ");
			searchSQL.append("left join loopmission_state_table lst on lst.mission_id = mst.mission_id ");
			searchSQL.append("where mst.end_time>sysdate ");
			searchSQL.append("and mst.mission_state in (1,2,5,6) ");
			searchSQL.append("and mst.is_loop = 1 ");
			searchSQL.append("and lst.cur_mission_id = "+curMissionId.longValue());
			
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("mission_id");
			fields.add("mission_type");
			fields.add("mission_state");
			fields.add("system_id");
			fields.add("group_id");
			fields.add("node_groups_id");
			fields.add("start_time");
			fields.add("end_time");
			fields.add("is_loop");
			fields.add("loop_delay");
			ArrayList<Map<String, String>> rs = null;
			try {
				rs = dao.dbSelect(searchSQL.toString(), fields);
				if(rs!=null && rs.size()>0){
					mission = new MissionStateTable();
					Map<String, String> maps = rs.get(0);
					mission.setMissionId(StringUtils.isEmpty(maps.get("mission_id"))?null:Long.parseLong(maps.get("mission_id")));
					mission.setMissionType(StringUtils.isEmpty(maps.get("mission_type"))?null:Long.parseLong(maps.get("mission_type")) );
					mission.setMissionState(StringUtils.isEmpty(maps.get("mission_state"))?null:Long.parseLong(maps.get("mission_state")));
					mission.setSystemId(StringUtils.isEmpty(maps.get("system_id"))?null:Long.parseLong(maps.get("system_id")));
					mission.setGroupId(StringUtils.isEmpty(maps.get("group_id"))?null:Long.parseLong(maps.get("group_id")));
					mission.setNodeGroupsId(StringUtils.isEmpty(maps.get("node_groups_id"))?null:maps.get("node_groups_id"));
					mission.setStartTime(StringUtils.isEmpty(maps.get("start_time"))?null:format.parse(maps.get("start_time")));
					mission.setEndTime(StringUtils.isEmpty(maps.get("end_time"))?null:format.parse(maps.get("end_time")));
					mission.setLoopFlag(StringUtils.isEmpty(maps.get("is_loop"))?null:Long.parseLong(maps.get("is_loop")));
					mission.setLoopDelay(StringUtils.isEmpty(maps.get("loop_delay"))?null:Long.parseLong(maps.get("loop_delay")));
				}
			} catch (Exception e) {
				logger.error("",e);
			}finally{
				dao.clearConn();
			}
		}
		return mission;
	}
	/**
	 * 根据MissionID 更新指定的周期任务的轮次List 到 集合Map<Long, List<LoopMissionRoundInfo>> loopMissionRoundMap 中
	 * @time Feb 10, 2012-2:23:58 PM
	 * @param missionInfoMap
	 * @param missionId
	 * @return
	 */
	public void updateLoopMissionRoundInfo(Map<Long, List<LoopMissionRoundInfo>> loopMissionRoundMap,Long missionId) {
		
		List<Long>	mIdsList = new LinkedList<Long>();

		
		if(missionId != null ){
			//将missionId 加入周期任务队列已查询 周期数据
			mIdsList.add(missionId);	
			
		}else{
			
			//missionId为空时  进行非指定查询
			String midsSql = "select mst.mission_id from  mission_state_table mst where mst.is_loop = 1 and mst.mission_state in(1,2,5,6) and mst.end_time > to_date('"+format.format(new Date())+"','yyyy-MM-dd HH24:mi:ss') "; 
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("mission_id");
			try {
				
				//将missionId们存入周期任务队列
				ArrayList<Map<String, String>> rs = dao.dbSelect(midsSql, fields);
				if(rs != null){
					for (Iterator midsIte = rs.iterator(); midsIte.hasNext();) {
						Map<String, String> midMap = (Map<String, String>) midsIte.next();
						mIdsList.add(StringUtils.isEmpty(midMap.get("mission_id"))?0:Long.parseLong(midMap.get("mission_id")));
					}
				}
				
			} catch (Exception e) {
				logger.error("",e);
			}
		}
		
		//终止无效操作
		if(mIdsList.size()== 0){
			return;
		}
		
		//循环查询周期数据
		for (Iterator midsIte = mIdsList.iterator(); midsIte.hasNext();) {
			
			Long mid = (Long) midsIte.next();
			
			//-- 跳过无效操作
			if(mid.longValue() == 0){
				continue;
			}
			//-- 查询可执行的任务 将数据存入缓存集合
			StringBuffer searchSQL = new StringBuffer();
			if(Constants.IS_MYSQL){
				searchSQL.append("select * from( ");
				searchSQL.append("select lmst.cur_mission_id, ");
				searchSQL.append("lmst.mission_id, ");
				searchSQL.append("lmst.mission_state, ");
				searchSQL.append("to_char(lmst.start_time,'"+Constants.DB_DATE_FORMAT+"') start_time,");
				searchSQL.append("to_char(lmst.end_time,'"+Constants.DB_DATE_FORMAT+"') end_time ");
				searchSQL.append("from loopmission_state_table lmst ");
				searchSQL.append("left join mission_state_table mst on mst.mission_id = lmst.mission_id ");
				searchSQL.append("where 1=1 ");
//				searchSQL.append("and rownum <=20 ");
				searchSQL.append("and mst.mission_id = ?");
				searchSQL.append("order by lmst.cur_mission_id desc");
				searchSQL.append(" limit 20");
				searchSQL.append(") ttt order by cur_mission_id asc");
			}else{
				searchSQL.append("select * from( ");
				searchSQL.append("select lmst.cur_mission_id, ");
				searchSQL.append("lmst.mission_id, ");
				searchSQL.append("lmst.mission_state, ");
				searchSQL.append("to_char(lmst.start_time,'"+Constants.DB_DATE_FORMAT+"') start_time,");
				searchSQL.append("to_char(lmst.end_time,'"+Constants.DB_DATE_FORMAT+"') end_time ");
				searchSQL.append("from loopmission_state_table lmst ");
				searchSQL.append("left join mission_state_table mst on mst.mission_id = lmst.mission_id ");
				searchSQL.append("where 1=1 ");
				searchSQL.append("and rownum <=20 ");
				searchSQL.append("and mst.mission_id = ?");
				searchSQL.append("order by lmst.cur_mission_id desc");
				searchSQL.append(") ttt order by cur_mission_id asc");
			}
			
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("cur_mission_id");
			fields.add("mission_id");
			fields.add("mission_state");
			fields.add("start_time");
			fields.add("end_time");
			ArrayList<Map<String, String>> rs = null;
			try {
				rs = dao.dbSelect(searchSQL.toString(), fields,new String[]{mid.longValue()+""});
				if(rs!=null && rs.size()>0){
					for(Map<String, String> maps : rs){
						LoopMissionRoundInfo roundInfo = new LoopMissionRoundInfo();
						roundInfo.setMissionId(StringUtils.isEmpty(maps.get("mission_id"))?null:Long.parseLong(maps.get("mission_id")));
						roundInfo.setCurMissionId(StringUtils.isEmpty(maps.get("cur_mission_id"))?null:Long.parseLong(maps.get("cur_mission_id")));
						roundInfo.setMissionState(StringUtils.isEmpty(maps.get("mission_state"))?null:Long.parseLong(maps.get("mission_state")));
						roundInfo.setStartTime(StringUtils.isEmpty(maps.get("start_time"))?null:format.parse(maps.get("start_time")));
						roundInfo.setEndTime(StringUtils.isEmpty(maps.get("end_time"))?null:format.parse(maps.get("end_time")));
						
						if(loopMissionRoundMap.get(roundInfo.getMissionId()) == null){
							List<LoopMissionRoundInfo> list = new LinkedList<LoopMissionRoundInfo>();
							loopMissionRoundMap.put(roundInfo.getMissionId(), list);
						}
						loopMissionRoundMap.get(roundInfo.getMissionId()).add(roundInfo);
						if(loopMissionRoundMap.get(roundInfo.getMissionId()).size() > 20){
							loopMissionRoundMap.get(roundInfo.getMissionId()).remove(0);
						}
					}
				}
			} catch (Exception e) {
				logger.error("",e);
			}finally{
				dao.clearConn();
			}
		}
	}
	public String createEmailContextForMission(Long missionId) {
		StringBuffer context = new StringBuffer();
		//通过missionID 获取任务信息 名称 创建日期等
		String selectSql = "select mst.mission_name,to_char(mst.create_time,'"+Constants.DB_DATE_FORMAT+"') create_time,mst.mission_state from mission_state_table mst where mst.mission_id = '"+missionId+"' ";
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("mission_name");
		fields.add("create_time");
		fields.add("mission_state");
		try {
			ArrayList<Map<String, String>> mapsList = this.dao.dbSelect(selectSql, fields);
			if(mapsList !=null && mapsList.size()>0){
				Map<String, String> maps = mapsList.get(0);
//				String state = "已创建";
//				String state = "Created";
				String state = "i18n_server.UpgradeService.created_n81i";
				if("2".equals(maps.get("mission_state"))){
//					state = "正在执行";
//					state = "Executing";
					state = "i18n_server.UpgradeService.exec_n81i";
				}else if("3".equals(maps.get("mission_state"))){
//					state = "已完成";
//					state = "Completed";
					state = "i18n_server.UpgradeService.finish_n81i";
				}
//				context.append("任务名称："+maps.get("mission_name")+"\n");
//				context.append("Task Name："+maps.get("mission_name")+"\n");
				context.append("i18n_server.UpgradeService.missionName_n81i："+maps.get("mission_name")+"\n");
//				context.append("创建时间："+maps.get("create_time")+"\n");
//				context.append("Created Time："+maps.get("create_time")+"\n");
				context.append("i18n_server.UpgradeService.createTime_n81i："+maps.get("create_time")+"\n");
//				context.append("任务状态："+state);
//				context.append("Task Status："+state);
				context.append("i18n_server.UpgradeService.missionState_n81i："+state);
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			dao.clearConn();
		}
		return context.toString();
	}

	private EmailInfo createEmailInfoForFailResult(MissionResult2 mr){
		StringBuffer context = new StringBuffer();
		String ip = Common.getNodeIpByUUID(mr.getUuid());
		EmailInfo emailInfo = new EmailInfo();
		emailInfo.setActionIp(ip);
		emailInfo.setActionType(EmailTypeConstants.TYPE_TASK_NODE_RESULT_ERROR);
		emailInfo.setSendFlag(EmailTypeConstants.FLAG_SEND_ALLREADY);
		emailInfo.setContent(mr.getDescription());
		emailInfo.setActionDate(format.format(new Date(mr.getStartTime()==null?System.currentTimeMillis():mr.getStartTime())));
		emailInfo.setSendLevel(EmailTypeConstants.URGENT_LATER);
		//通过missionID 获取任务信息 名称 创建日期等
		String selectSql = "select mst.mission_name,to_char(mst.create_time,'"+Constants.DB_DATE_FORMAT+"') create_time from mission_state_table mst where mst.mission_id = '"+mr.getMissionId()+"' ";
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("mission_name");
//		fields.add("create_time");
		try {
			ArrayList<Map<String, String>> mapsList = this.dao.dbSelect(selectSql, fields);
			if(mapsList !=null && mapsList.size()>0){
				Map<String, String> maps = mapsList.get(0);
				emailInfo.setActionDesc(maps.get("mission_name"));
			}
			
		} catch (Exception e) {
			logger.error("", e);
		}finally{
			dao.clearConn();
		}
		return emailInfo;
	}
	/*private String createEmailContextForFailResult(MissionResult2 mr){
		StringBuffer context = new StringBuffer();
		String ip = Common.getNodeIpByUUID(mr.getUuid());
		//通过missionID 获取任务信息 名称 创建日期等
		String selectSql = "select mst.mission_name,to_char(mst.create_time,'"+Constants.DB_DATE_FORMAT+"') create_time from mission_state_table mst where mst.mission_id = '"+mr.getMissionId()+"' ";
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("mission_name");
		fields.add("create_time");
		try {
			ArrayList<Map<String, String>> mapsList = this.dao.dbSelect(selectSql, fields);
			if(mapsList !=null && mapsList.size()>0){
				Map<String, String> maps = mapsList.get(0);
				maps.get("");
				context.append("任务名称："+maps.get("mission_name")+"\n");
				context.append("创建时间："+maps.get("create_time")+"\n");
				context.append("结果描述："+ip+" "+mr.getDescription());
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			dao.clearConn();
		}
		return context.toString();
	}*/
	/**
	 * 变更任务状态
	 * @time Jan 11, 2012-1:39:27 PM
	 * @param missionId
	 * @param missionState
	 */
	public void updateMissionState(Long missionId,int missionState,String autoDesc) throws Exception{
		if(missionId==null || missionId.longValue()==0){
			return ;
		}
		String [] params = null;
		StringBuffer sql = new StringBuffer("update mission_state_table mst set ");
		sql.append(" mst.mission_state = ? ");
		pl(autoDesc);
		if(StringUtils.isEmpty(autoDesc)){
			params =new String[]{missionState+"",missionId.longValue()+""};
		}else{
			sql.append(" , mst.AUTO_DESC = ? ");
			params =new String[]{missionState+"",autoDesc,missionId.longValue()+""};
		}
		sql.append(" where mst.mission_id =? ");
		try {
			dao.dbUpdate(sql.toString(), params);
		} catch (Exception e) {
			throw e;
		}finally{
			dao.clearConn();
		}
	}
	/**
	 * 删除预置周期信息
	 * @time Jan 11, 2012-1:39:27 PM
	 * @param missionId
	 * @param missionState
	 */
	public void deleteLoopMissionPreset(Long missionId,Long curMissionId) {
		if(missionId==null || missionId.longValue()==0){
			return ;
		}
		
		String sql = "delete from loopmission_state_table  where mission_state=0 and mission_id ="+missionId.longValue()+" and start_time>=sysdate";
		if(curMissionId!=null){
			sql = "delete from loopmission_state_table  where mission_id ="+missionId.longValue()+" and cur_mission_id>"+curMissionId.longValue();
		}
		
		try {
			dao.dbUpdate(sql);
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
	}
	/**
	 * 变更周期任务结果的状态
	 * @time Jan 11, 2012-1:39:27 PM
	 * @param missionId
	 * @param missionState
	 */
	public void updateMissionResultsResult(long roundMissionId,int missionType,int result) {
		if(roundMissionId==0 || missionType==0){
			return ;
		}
		String sql = "update mission_result_table"+missionType+" mst set mst.result="+result+" where mst.mission_id ="+roundMissionId;
		try {
			dao.dbUpdate(sql);
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
	}
	/**
	 * 变更任务状态
	 * @time Jan 11, 2012-1:39:27 PM
	 * @param missionId
	 * @param missionState
	 */
	public void updateLoopMissionState(Long missionId,int missionState) {
		if(missionId==null || missionId.longValue()==0){
			return ;
		}
		String sql = "update loopmission_state_table mst set mst.mission_state ='"+missionState+"' where mst.cur_mission_id ="+missionId.longValue();
		try {
			dao.dbUpdate(sql);
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
	}
	public String getUpdateSQL(int missionType) {
//		"+(mr2.getResult()==null?1:mr2.getResult())+"
//		String desc = StringUtils.isEmpty(mr2.getDescription())?"":mr2.getDescription();
//		"+mr2.getMissionId().longValue()+"
//		"+mr2.getUuid().longValue()+"
//		StringBuffer sql = new StringBuffer(" mrt set mrt.result =? ,mrt.result_desc = substr(mrt.result_desc||?,decode(sign(vsize(mrt.result_desc||?)-1024),-1,0,0,0,1,vsize(mrt.result_desc||?)+1-1024),1024) ");
		StringBuffer sql = new StringBuffer("update mission_result_table"+missionType+" mrt set mrt.result =? ,mrt.result_desc = ?");
		switch (missionType) {
		case 1:
//			sql.insert(0, "update mission_result_table1");
			break;
		case 2:
//			sql.insert(0, "update mission_result_table2");
			break;
		case 3:
//			sql.insert(0, "update mission_result_table3");
			break;
		case 4:
			sql.append(",mrt.file_info = ? ,mrt.result_detail=?");
			break;
		case 5:
//			sql.insert(0, "update mission_result_table5");
			break;
		case 6:
//			sql.insert(0, "update mission_result_table6");
			break;
		default:
			break;
		}
		sql.append(" where mrt.mission_id =? and mrt.seq_id =? ");
		return sql.toString();
	}
//	public void updateMissionResult2ByBatch(List<MissionResult2> mr2List) {
//		List<String> updateSqlList = new ArrayList<String>();
//		try {
//			if(mr2List!= null && mr2List.size()>0){
//				Iterator<MissionResult2> mrIte = mr2List.iterator();
//				int count = 0;
//				while (mrIte.hasNext()) {
//					MissionResult2 mr = (MissionResult2) mrIte.next();
//					String sql = getUpdateSql(mr);
//					System.out.println("sql> "+sql);
//					updateSqlList.add(sql);
//					count++;
//					if(count == Constants.DB_EXECUTE_BATCH){
//						dao.dbUpdateByBatch(updateSqlList);
//						count = 0;
//						updateSqlList.clear();
//					}
//				}
//				if (count > 0) {
//					dao.dbUpdateByBatch(updateSqlList);
//					count = 0;
//					updateSqlList.clear();
//				}
//			}
//		} catch (Exception e) {
//			logger.error("批量更新异常 \n"+"",e);
//		}finally{
//			dao.clearConn();
//		}
//	}
	
	/**
	 * 非定时任务 检查任务完成状态操作方法
	 * @time Nov 17, 2011-4:47:55 PM
	 */
	/*public void checkAndUpdateMissionComplete() {//此处total是共执行的，还是所有应执行的节点数，再加个字段？描述是在DC端就入库？还是web端再统计？
		StringBuffer selectSql = new StringBuffer();
		selectSql.append("select t.mission_id from (");
		selectSql.append("(select mrt.mission_id,sum(decode(mrt.result,0,1,0) ) ok,sum(decode(mrt.result,1,1,-1,1,0) ) fail,count(mrt.seq_id) total from mission_result_table1 mrt group by mrt.mission_id) union all ");
//		selectSql.append("(select mrt.mission_id,sum(decode(mrt.result,0,1,0) ) ok,sum(decode(mrt.result,1,1,-1,1,0) ) fail,count(mrt.seq_id) total from mission_result_table2 mrt group by mrt.mission_id) union all ");
//		selectSql.append("(select mrt.mission_id,sum(decode(mrt.result,0,1,0) ) ok,sum(decode(mrt.result,1,1,-1,1,0) ) fail,count(mrt.seq_id) total from mission_result_table3 mrt group by mrt.mission_id) union all ");
		selectSql.append("(select mrt.mission_id,sum(decode(mrt.result,0,1,0) ) ok,sum(decode(mrt.result,1,1,-1,1,0) ) fail,count(mrt.seq_id) total from mission_result_table4 mrt group by mrt.mission_id) union all ");
//		selectSql.append("(select mrt.mission_id,sum(decode(mrt.result,0,1,0) ) ok,sum(decode(mrt.result,1,1,-1,1,0) ) fail,count(mrt.seq_id) total from mission_result_table5 mrt group by mrt.mission_id) union all ");
		selectSql.append("(select mrt.mission_id,sum(decode(mrt.result,0,1,0) ) ok,sum(decode(mrt.result,1,1,-1,1,0) ) fail,count(mrt.seq_id) total from mission_result_table6 mrt group by mrt.mission_id)");
		selectSql.append(") t ");
		selectSql.append("left join mission_state_table mst on mst.mission_id = t.mission_id ");
		selectSql.append("where t.ok + t.fail = t.total ");
		selectSql.append("and nvl(t.mission_id,-1) <> -1 ");
		selectSql.append("and mst.is_loop = 0 ");
		selectSql.append("and mst.mission_state <3 ");
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("mission_id");
		try {
//			StringBuffer missionIds = new StringBuffer(); 
			List<Map<String, String>> mapList = dao.dbSelect(selectSql.toString(), fields);
			if(mapList != null && mapList.size()>0){//
				for(Map<String, String> map : mapList){
//					missionIds.append(","+map.get("mission_id"));
					if(StringUtils.isNotEmpty(map.get("mission_id"))){
//						createEmailContextForMission(Long.parseLong(map.get("mission_id")));
						dao.dbUpdate("update mission_state_table mst set mst.mission_state = 3 where mst.mission_id = ?",map.get("mission_id"));
					}
				}
//				missionIds = missionIds.deleteCharAt(0);
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
	}*/
	
	/**
	 * 非周期任务：录入任务结果后，若任务已完成，则更新任务状态为成功、部分成功、全部失败中的一个（原来只有一个完成状态，做此修改便于更清晰的描述任务完成的状态）
	 *          完成（3）：t.ok + t.fail = t.total 
	 *           成功（31）：t.ok + t.fail = t.total  and  t.ok = t.total 
	 *           部分成功（32）：t.ok + t.fail = t.total  and   t.ok>0  and t.fail>0
	 *           全部失败（30）：t.ok + t.fail = t.total  and  t.fail = t.total
	 * @time 2013-1-28 9:30:55 AM
	 * @author hyx
	 */
	public void updateCommonMissionComplete() {//此处total是共执行的，还是所有应执行的节点数，再加个字段？描述是在DC端就入库？还是web端再统计？
		StringBuffer selectSql = new StringBuffer();
		selectSql.append("select t.mission_id,t.ok,t.fail,t.total from (");
		selectSql.append("(select mrt.mission_id,sum(decode(mrt.result,0,1,0) ) ok,sum(decode(mrt.result,1,1,-1,1,0) ) fail,count(mrt.seq_id) total from mission_result_table1 mrt group by mrt.mission_id) union all ");
		selectSql.append("(select mrt.mission_id,sum(decode(mrt.result,0,1,0) ) ok,sum(decode(mrt.result,1,1,-1,1,0) ) fail,count(mrt.seq_id) total from mission_result_table4 mrt group by mrt.mission_id) union all ");
		selectSql.append("(select mrt.mission_id,sum(decode(mrt.result,0,1,0) ) ok,sum(decode(mrt.result,1,1,-1,1,0) ) fail,count(mrt.seq_id) total from mission_result_table6 mrt group by mrt.mission_id)");
		selectSql.append(") t ");
		selectSql.append("left join mission_state_table mst on mst.mission_id = t.mission_id ");
		selectSql.append("where t.ok + t.fail = t.total ");
		selectSql.append("and nvl(t.mission_id,-1) <> -1 ");//不取任务id为null的？
		selectSql.append("and mst.is_loop = 0 ");//非周期任务
		selectSql.append("and mst.mission_state in(1,2) ");//如果之前已经更新为完成（=3）的任务，不再更新，只更新一次（非周期任务的状态：1创建,2执行中,4未能执行（未能执行的不能更新为完成））
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("mission_id");
		fields.add("ok");
		fields.add("fail");
		fields.add("total");
		try {
			List<Map<String, String>> mapList = dao.dbSelect(selectSql.toString(), fields);
			
			if(mapList != null && mapList.size()>0){//
				EmailService emailService = new EmailService(dao);
				for(Map<String, String> map : mapList){
					if(StringUtils.isNotEmpty(map.get("mission_id"))){
						Long ok = StringUtils.isEmpty(map.get("ok"))?null:Long.parseLong(map.get("ok"));
						Long fail = StringUtils.isEmpty(map.get("fail"))?null:Long.parseLong(map.get("fail"));
						Long total = StringUtils.isEmpty(map.get("total"))?null:Long.parseLong(map.get("total"));
						//完成的任务才需要更新状态，但是对于新录入的任务，我会更改其mission_state_table里的mission_state_desc
						if(ok!=null && ok.equals(total) ) {//成功
//							dao.dbUpdate("update mission_state_table mst set mst.mission_state = 30 ,AUTO_DESC=? where mst.mission_id = ?",format.format(System.currentTimeMillis())+" 任务执行完成:共"+total+"个执行节点，成功"+ok+"个，失败"+fail+"个",map.get("mission_id"));
							dao.dbUpdate("update mission_state_table mst set mst.mission_state = 30 ,AUTO_DESC=? where mst.mission_id = ?",format.format(System.currentTimeMillis())+" i18n_sserver.UpgradeService.sql.complate_n81i "+total+" i18n_sserver.UpgradeService.sql.executeNode_n81i "+ok+" i18n_sserver.UpgradeService.sql.failed_n81i "+fail,map.get("mission_id"));
							
						}else if(fail!=null && fail.equals(total)) {//全部失败
//							dao.dbUpdate("update mission_state_table mst set mst.mission_state = 31 ,AUTO_DESC=? where mst.mission_id = ?",format.format(System.currentTimeMillis())+" 任务执行完成:共"+total+"个执行节点，成功"+ok+"个，失败"+fail+"个",map.get("mission_id"));
							dao.dbUpdate("update mission_state_table mst set mst.mission_state = 31 ,AUTO_DESC=? where mst.mission_id = ?",format.format(System.currentTimeMillis())+" i18n_sserver.UpgradeService.sql.complate_n81i "+total+" i18n_sserver.UpgradeService.sql.executeNode_n81i "+ok+" i18n_sserver.UpgradeService.sql.failed_n81i "+fail,map.get("mission_id"));
							
						}else if(fail!=null && fail.longValue()>0 && ok!=null && ok.longValue()>0) {//部分成功
//							dao.dbUpdate("update mission_state_table mst set mst.mission_state = 32 ,AUTO_DESC=? where mst.mission_id = ?",format.format(System.currentTimeMillis())+" 任务执行完成:共"+total+"个执行节点，成功"+ok+"个，失败"+fail+"个",map.get("mission_id"));
							dao.dbUpdate("update mission_state_table mst set mst.mission_state = 32 ,AUTO_DESC=? where mst.mission_id = ?",format.format(System.currentTimeMillis())+" i18n_sserver.UpgradeService.sql.complate_n81i "+total+" i18n_sserver.UpgradeService.sql.executeNode_n81i "+ok+" i18n_sserver.UpgradeService.sql.failed_n81i "+fail,map.get("mission_id"));
							
						}
						// 发送邮件
//						emailService.sendEmailForMission(Long.parseLong(map.get("mission_id")), "任务执行通知", "任务执行结束:共"+total+"个执行节点，成功"+ok+"个，失败"+fail+"个");
//						emailService.sendEmailForMission(Long.parseLong(map.get("mission_id")), "Task execution notification", "End of task execution:A total of"+total+"execution nodes,successful"+ok+"failed"+fail);
						emailService.sendEmailForMission(Long.parseLong(map.get("mission_id")), "i18n_server.UpgradeService.missionExec_n81i", "i18n_server.UpgradeService.missionEnd_n81i:i18n_server.UpgradeService.sql.total_n81i "+total+" i18n_server.UpgradeService.sql.executeNode2_n81i,i18n_server.UpgradeService.sql.success_n81i "+ok+" i18n_sserver.UpgradeService.sql.failed_n81i "+fail);
					}
				}
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
	}
	
	//更新mission_state_table表里的mission_state_desc字段（只对新录入结果的任务更新，没录入任务结果的任务不需要更新）
	public void updateCommonMissionStateDesc(int missiontype,List<MissionResult2> mr2List) {
		if(mr2List!=null && mr2List.size()>0) {
			//获得更新结果的任务id的字符串
			String missionIds = getMissionIdLinkStr(mr2List);
			
			if(!"".equals(missionIds)) {
				updateCommonMissionStateDesc(missiontype,missionIds);
				
			}
		}
	}
	
	/**
	 * 更新mission_state_table表里的mission_state_desc字段（只对新录入结果的任务更新，没录入任务结果的任务不需要更新）
	 * 	  根据任务id更新任务的状态-非周期任务
	 * 
	 */
	public void updateCommonMissionStateDesc(int missiontype,String missionIds) {
		if(StringUtils.isNotBlank(missionIds)) {
			StringBuffer selectSql = new StringBuffer();
			selectSql.append(" select t.mission_id,t.ok,t.fail,t.total ");
			selectSql.append(" from (");
			selectSql.append("       select mrt.mission_id,");
			selectSql.append("              sum(decode(mrt.result,0,1,0) ) ok, ");
			selectSql.append("              sum(decode(mrt.result,1,1,-1,1,0) ) fail, ");
			selectSql.append("              count(mrt.seq_id) total ");
			selectSql.append("       from mission_result_table"+missiontype+" mrt  ");
			selectSql.append("       group by mrt.mission_id  ");
			selectSql.append(" ) t ");
			selectSql.append(" left join mission_state_table mst on mst.mission_id = t.mission_id ");
			selectSql.append(" where mst.is_loop = 0");//非周期任务:0,周期任务：1
			selectSql.append("       and  t.mission_id is not null ");//不取任务id为null的？其实不需要，因为非周期任务的任务id理论上不会为null？
			selectSql.append(" and mst.mission_id in("+missionIds+") ");//只更新 新录入了结果的任务的任务状态描述
			
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("mission_id");
			fields.add("ok");
			fields.add("fail");
			fields.add("total");
			try {
				List<Map<String, String>> mapList = dao.dbSelect(selectSql.toString(), fields);
				if(mapList != null && mapList.size()>0){//
					List<String> sqls = new ArrayList<String>();
					for(Map<String, String> map : mapList){
						if(StringUtils.isNotEmpty(map.get("mission_id"))){
							Long ok = StringUtils.isEmpty(map.get("ok"))?null:Long.parseLong(map.get("ok"));
							Long fail = StringUtils.isEmpty(map.get("fail"))?null:Long.parseLong(map.get("fail"));
							Long total = StringUtils.isEmpty(map.get("total"))?null:Long.parseLong(map.get("total"));
							//完成的任务才需要更新状态，但是对于新录入的任务，我会更改其mission_state_table里的mission_state_desc
//							sqls.add("update mission_state_table mst set mst.mission_state_desc = '共"+total+"个执行节点，</br>"+(total-ok-fail)+"个未执行，</br>"+(ok+fail)+"个已执行【成功"+ok+"个，失败"+fail+"个】' where mst.mission_id = "+map.get("mission_id"));
							sqls.add("update mission_state_table mst set mst.mission_state_desc = 'i18n_server.UpgradeService.sql.total_n81i "+total+" i18n_server.UpgradeService.sql.executeNode2_n81i，</br>"+(total-ok-fail)+" i18n_server.UpgradeService.sql.unexecute_n81i，</br>"+(ok+fail)+" i18n_server.UpgradeService.sql.execute_n81i【i18n_server.UpgradeService.sql.success_n81i "+ok+" i18n_sserver.UpgradeService.sql.failed_n81i "+fail+"】' where mst.mission_id = "+map.get("mission_id"));
						}
					}
					
					dao.dbUpdateByBatch(sqls);
				}
			} catch (Exception e) {
				logger.error("",e);
			}finally{
				dao.clearConn();
			}
		}
	}
	
	private String getMissionIdLinkStr(List<MissionResult2> mr2List) {
		String missionIds = "";
		for(MissionResult2 missRlt2:mr2List) {
			String misId = missRlt2.getMissionId()==null ? "" : missRlt2.getMissionId().toString();
			if(!"".equals(misId)&&!(","+missionIds).contains(","+misId+",")) {
				missionIds = missionIds + misId + ",";
			}
		}
		if(missionIds.endsWith(",")) {
			missionIds = missionIds.substring(0,missionIds.length()-1);
		}
		return missionIds;
	}
	
	//更新loopmission_state_table表里的mission_state_desc字段（只对新录入结果的任务更新，没录入任务结果的任务不需要更新）
	public void updateLoopMissionStateDesc(List<MissionResult2> mr2List) {
		if(mr2List!=null && mr2List.size()>0) {	
			//获得更新结果的任务id的字符串
			String missionIds = getMissionIdLinkStr(mr2List);
			
			if(!"".equals(missionIds)) {		
				updateLoopMissionStateDesc(missionIds);
			}	
		}
	}
	
	//根据任务id更新任务的状态描述-周期任务
	public void updateLoopMissionStateDesc(String  missionIds) {			
		if(StringUtils.isNotBlank(missionIds)) {				
//			StringBuffer selectSql = new StringBuffer();
//			selectSql.append(" select sumT.missionId ,sumT.ok, sumT.fail, sumT.total ");
//			selectSql.append(" from (");
//			selectSql.append("        select row_number() over(partition by lmst.mission_id order by lmst.cur_mission_id desc) cn, ");
//			selectSql.append("               lmst.cur_mission_id ,");
//			selectSql.append("               lmst.mission_id missionId,mst.mission_state, ");
//			selectSql.append("               t.ok, t.fail, t.total ");
//			selectSql.append("        from ( ");
//			selectSql.append("                 select mrt.mission_id, ");
//			selectSql.append("                        sum(decode(mrt.result, 0, 1, 0)) ok, ");//只统计正常执行的周期任务执行情况，对于撤销的不管
//			selectSql.append("                        sum(decode(mrt.result, 1, 1, -1, 1, 0)) fail, ");//只统计正常执行的周期任务执行情况，对于撤销的不管
//			selectSql.append("                        count(mrt.seq_id) total ");
//			selectSql.append("                 from mission_result_table4 mrt ");
//			selectSql.append("                 group by mrt.mission_id ");
//			selectSql.append("              ) t ");
//			selectSql.append("        left join loopmission_state_table lmst on lmst.cur_mission_id = t.mission_id ");
//			selectSql.append("        left join mission_state_table mst on mst.mission_id = lmst.mission_id ");
//			selectSql.append("        where lmst.cur_mission_id is not null and mst.is_loop=1 and mst.mission_state =2 ");//mission_state=2表示只修改正常执行的，对于撤销的，不予修改
//			selectSql.append("              and mst.mission_id in("+missionIds+") ");//只修改有结果录入的
//			selectSql.append(" ) sumT ");//只修改有结果录入的
//			selectSql.append(" where sumT.cn=1 ");//只修改有结果录入的
			String selectSql = "select lmst.mission_id missionId, t.ok, t.fail, t.total\n" +
					"  from (select mrt.mission_id,\n" + 
					"               nvl(sum(decode(mrt.result, 0, 1, 0)), 0) ok,\n" + 
					"               nvl(sum(decode(mrt.result, 1, 1, -1, 1, 0)), 0) fail,\n" + 
					"               count(mrt.seq_id) total\n" + 
					"          from mission_result_table4 mrt\n" + 
					"         group by mrt.mission_id) t\n" + 
					"  left join (select max(lst.cur_mission_id) cur_mission_id, lst.mission_id\n" + 
					"               from  mission_result_table4 mrt4\n" + 
					"               left join  loopmission_state_table lst on mrt4.mission_id = lst.cur_mission_id\n" + 
					"              group by lst.mission_id) lmst\n" + 
					"    on lmst.cur_mission_id = t.mission_id\n" + 
					"  left join mission_state_table mst\n" + 
					"    on mst.mission_id = lmst.mission_id\n" + 
					" where lmst.cur_mission_id is not null and mst.is_loop=1 " + 
					" and mst.mission_state =2 and mst.mission_id in ("+missionIds+")";//mission_state=2表示只修改正常执行的，对于撤销的，不予修改
			
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("missionId");
			fields.add("ok");
			fields.add("fail");
			fields.add("total");
			try {
				List<Map<String, String>> mapList = dao.dbSelect(selectSql.toString(), fields);
				if(mapList != null && mapList.size()>0){//
					List<String> sqls = new ArrayList<String>();
					for(Map<String, String> map : mapList){
						if(StringUtils.isNotEmpty(map.get("missionId"))){
							Long ok = StringUtils.isEmpty(map.get("ok"))?null:Long.parseLong(map.get("ok"));
							Long fail = StringUtils.isEmpty(map.get("fail"))?null:Long.parseLong(map.get("fail"));
							Long total = StringUtils.isEmpty(map.get("total"))?null:Long.parseLong(map.get("total"));
							//完成的任务才需要更新状态，但是对于新录入的任务，我会更改其mission_state_table里的mission_state_desc
//							sqls.add("update mission_state_table mst set mst.mission_state_desc = '最新周期共"+total+"个执行节点，</br>"+(total-ok-fail)+"个未执行，</br>"+(ok+fail)+"个已执行【成功"+ok+"个，失败"+fail+"个】' where mst.mission_id = "+map.get("missionId"));
							sqls.add("update mission_state_table mst set mst.mission_state_desc = 'i18n_server.UpgradeService.sql.cycle_n81i "+total+" i18n_server.UpgradeService.sql.executeNode2_n81i，</br>"+(total-ok-fail)+" i18n_server.UpgradeService.sql.unexecute_n81i，</br>"+(ok+fail)+" i18n_server.UpgradeService.sql.execute_n81i【i18n_server.UpgradeService.sql.success_n81i "+ok+" i18n_sserver.UpgradeService.sql.failed_n81i "+fail+" 】' where mst.mission_id = "+map.get("missionId"));
						}
					}
					
					dao.dbUpdateByBatch(sqls);
				}
			} catch (Exception e) {
				logger.error("",e);
			}finally{
				dao.clearConn();
			}
		}
	}
	
	/**
	 * 周期任务：
	 *    更新loopmission_state_table表：
	 *       1.查询正常执行的单次周期任务的完成（2->3）+撤销任务的撤销完成(6->7)
	 *       2.更新表loopmission_state_table中的状态（2->3，6->7）
	 *    更新mission_state_table表：
	 *    	 1.查询正常执行的任务周期全部完成为任务完成（2->3）
	 *    	 2.查询撤销任务周的撤销完成为整个任务撤销完成（6->7）
	 * 任务完成判定标准（20130322）：撤销任务为撤销周期完成即整个任务完成
	 * 						  正常周期任务为所有正常均完成则整个任务完成
	 * @time Nov 17, 2011-4:47:55 PM  
	 * @author hyx
	 */
	public void updateLoopMissionComplete() {
		//-- 周期任务 的检查SQL
		//完成的（正常执行的+撤销的，为了获得完成的任务id，无论是正常执行完成的，还是撤销完成的）
		StringBuffer loopSQL = new StringBuffer();
		loopSQL.append(" select lmst.cur_mission_id mission_id ,lmst.mission_state");
		loopSQL.append(" from (");
		loopSQL.append("        select mrt.mission_id,");//0，1，-1和6,7不会同时出现的
		loopSQL.append("               sum(case when mrt.result = 0 then 1 else 0 end) ok,");//正常执行成功的
		loopSQL.append("               sum(case when mrt.result in (1,-1) then 1 else 0 end) fail,");//正常执行失败的
		loopSQL.append("               sum(case when mrt.result = 7 then 1 else 0 end) cxOk,");//撤销成功的
		loopSQL.append("               sum(case when mrt.result = 6 then 1 else 0 end) cxFail,");//撤销失败的
		loopSQL.append("               count(mrt.seq_id) total ");//总数
		loopSQL.append("        from mission_result_table4 mrt ");
		loopSQL.append("        group by mrt.mission_id ");
		loopSQL.append("       ) t ");
		loopSQL.append(" left join  loopmission_state_table lmst on lmst.cur_mission_id = t.mission_id ");
		loopSQL.append(" where lmst.cur_mission_id is not null ");
		loopSQL.append("       and (t.ok + t.fail = t.total or t.cxOk+t.cxFail=t.total )");
		loopSQL.append("       and lmst.mission_state not in (3,7)  ");//3:周期任务的单次任务完成，7：周期任务的单次任务完成撤销

		ArrayList<String> fields = new ArrayList<String>();
		fields.add("mission_id");
		fields.add("mission_state");
		try {
			List<Map<String, String>> mapList = dao.dbSelect(loopSQL.toString(), fields);
			
			//- 变更周期任务信息状态 loopmission_state_table
			if(mapList != null && mapList.size()>0){
				StringBuffer missionIds = new StringBuffer("0");	//正常周期任务结果入库完成轮次IDS	
				StringBuffer cancelMissionIds = new StringBuffer("0");//撤销周期任务结果入库完成轮次IDS	
				for(Map<String, String> map : mapList){
					if(StringUtils.isNotEmpty(map.get("mission_state")) && map.get("mission_state").equals("6")){	//撤销周期
						cancelMissionIds.append(","+map.get("mission_id"));
					}else{	//非撤销周期
						missionIds.append(","+map.get("mission_id"));
					}
				}
				
				//存在撤销周期的轮次任务
				if(cancelMissionIds.length()>1){
					//将该周期轮次状态置为撤销完成，将该任务状态置为撤销完成
					dao.dbUpdate("update loopmission_state_table mst set mst.mission_state = 7 where mst.mission_state = 6 and mst.cur_mission_id in ("+cancelMissionIds.toString()+")");
//					dao.dbUpdate("update mission_state_table mst set mst.mission_state = 7 , mst.auto_desc='"+format.format(System.currentTimeMillis())+" 任务撤销完成' where mst.mission_state = 6 and mst.mission_id in ( select lmst.mission_id from loopmission_state_table lmst where lmst.cur_mission_id in("+cancelMissionIds.toString()+")) ");
					dao.dbUpdate("update mission_state_table mst set mst.mission_state = 7 , mst.auto_desc='"+format.format(System.currentTimeMillis())+" i18n_server.UpgradeService.sql.revoke_n81i' where mst.mission_state = 6 and mst.mission_id in ( select lmst.mission_id from loopmission_state_table lmst where lmst.cur_mission_id in("+cancelMissionIds.toString()+")) ");
				}
				
				//存在正常周期的轮次任务
				if(missionIds.length()>1){
					dao.dbUpdate("update loopmission_state_table mst set mst.mission_state = 3 where mst.mission_state = 2 and mst.cur_mission_id in ("+missionIds.toString()+")");
				}
			}
			//- 变更周期任务信息状态 mission_state_table
			StringBuffer missionSql = new StringBuffer();
			missionSql.append(" select mst.mission_id,mst.mission_state");
			missionSql.append(" from (");
			missionSql.append("         select lmst.mission_id, ");
			missionSql.append("                sum(decode(lmst.mission_state, 3, 1, 7, 1, 0)) ok,");//正常执行完成的周期，撤销完成的周期
			missionSql.append("                sum(decode(lmst.mission_state, 4, 1, 0)) fail,");//未能执行的周期
			missionSql.append("                count(lmst.cur_mission_id) total");
			missionSql.append("         from loopmission_state_table lmst");
			missionSql.append("         group by lmst.mission_id");
			missionSql.append("       ) t");
			missionSql.append(" left join mission_state_table mst on mst.mission_id = t.mission_id");
			missionSql.append(" where t.ok + t.fail = t.total");
			missionSql.append("       and nvl(mst.mission_id, -1) <> -1");
			missionSql.append("       and mst.is_loop = 1");
			missionSql.append("       and mst.mission_state not in (3, 7, 4)");
			
			StringBuffer missionIds0 = new StringBuffer("0");
			List<Map<String, String>> mapList0 = dao.dbSelect(missionSql.toString(), fields);
			//- 变更周期任务信息状态 mission_state_table
			if(mapList0 != null && mapList0.size()>0){
				EmailService emailService = new EmailService(dao);
				for(Map<String, String> map : mapList0){
					missionIds0.append(","+map.get("mission_id"));
					if(StringUtils.isNotEmpty(map.get("mission_id"))){
						// 发送邮件
//						emailService.sendEmailForMission(Long.parseLong(map.get("mission_id")), "任务执行通知", "任务执行结束");
						emailService.sendEmailForMission(Long.parseLong(map.get("mission_id")), "i18n_server.UpgradeService.missionExec_n81i", "i18n_server.UpgradeService.missionEnd_n81i");
					}
				}
				//将撤销任务或撤销超时任务置为撤销完成状态
//				dao.dbUpdate("update mission_state_table mst set mst.mission_state = 7,mst.auto_desc='"+format.format(System.currentTimeMillis())+" 任务撤销完成' where mst.mission_state = 6 and (mst.mission_id in ("+missionIds0.toString()+") or mst.end_time <= sysdate)");
//				dao.dbUpdate("update mission_state_table mst set mst.mission_state = 7,mst.auto_desc='"+format.format(System.currentTimeMillis())+" 任务撤销完成' where mst.mission_state = 6 and mst.mission_id in ("+missionIds0.toString()+") ");
				dao.dbUpdate("update mission_state_table mst set mst.mission_state = 7,mst.auto_desc='"+format.format(System.currentTimeMillis())+" i18n_server.UpgradeService.sql.revoke_n81i' where mst.mission_state = 6 and mst.mission_id in ("+missionIds0.toString()+") ");
				//只针对完成的周期任务，不包括撤销任务（完成的状况可能是：全部完成（mission_state为3的=total），部分未能执行（fail>0））
//				dao.dbUpdate("update mission_state_table mst set mst.mission_state = 3,mst.auto_desc='"+format.format(System.currentTimeMillis())+" 任务执行完成' where mst.mission_state = 2 and (mst.mission_id in ("+missionIds0.toString()+") or mst.end_time <= sysdate)");
//				dao.dbUpdate("update mission_state_table mst set mst.mission_state = 3,mst.auto_desc='"+format.format(System.currentTimeMillis())+" 任务执行完成' where mst.mission_state = 2 and mst.mission_id in ("+missionIds0.toString()+")  ");
				dao.dbUpdate("update mission_state_table mst set mst.mission_state = 3,mst.auto_desc='"+format.format(System.currentTimeMillis())+" i18n_server.UpgradeService.sql.revoke_n81i' where mst.mission_state = 2 and mst.mission_id in ("+missionIds0.toString()+")  ");
				//--将超时的任务检查，单独提出-checkTimeoutLoopMisssionAndAddResult()方法
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
	}
	
	//对于超时周期任务的清理：周期未初始化结果：loop表的state=0 or 1，将loop表的state修改为4未能执行
	public void updateTimeoutLoopMissionState(String timeoutMissIds) {
		if(StringUtils.isNotBlank(timeoutMissIds)) {
			StringBuffer loopSQL = new StringBuffer();
			loopSQL.append(" select lmst.mission_id,lmst.cur_mission_id , lmst.mission_state");
			loopSQL.append(" from loopmission_state_table lmst ");
			loopSQL.append(" where lmst.mission_id in ("+timeoutMissIds+") and lmst.mission_state in (0,1) and lmst.end_time<=to_date('"+format.format(new Date())+"','yyyy-MM-dd HH24:mi:ss') ");
			
			ArrayList<String> fields = new ArrayList<String>();
			fields.add("mission_id");
			fields.add("cur_mission_id");
			fields.add("mission_state");
			try {
				List<Map<String, String>> mapList = dao.dbSelect(loopSQL.toString(), fields);
				
				//- 变更周期任务信息状态 loopmission_state_table
				if(mapList != null && mapList.size()>0){
					StringBuffer missionIds = new StringBuffer("0");	
					StringBuffer cancelMissionIds = new StringBuffer("0");	
					for(Map<String, String> map : mapList){
						if(StringUtils.isNotEmpty(map.get("mission_state")) && map.get("mission_state").equals("6")){	//撤销周期
							cancelMissionIds.append(","+map.get("cur_mission_id"));
						}else{	//非撤销周期
							missionIds.append(","+map.get("cur_mission_id"));
						}
					}
					
					//存在撤销周期的轮次任务
					if(cancelMissionIds.length()>1){
						//将该周期轮次状态置为撤销完成，将该任务状态置为撤销完成
						dao.dbUpdate("update loopmission_state_table mst set mst.mission_state = 7 where mst.mission_state = 6 and mst.cur_mission_id in ("+cancelMissionIds.toString()+")");
//						dao.dbUpdate("update mission_state_table mst set mst.mission_state = 7 , mst.auto_desc='"+format.format(System.currentTimeMillis())+" 任务撤销完成' where mst.mission_state = 6 and mst.mission_id in ( select lmst.mission_id from loopmission_state_table lmst where lmst.cur_mission_id in("+cancelMissionIds.toString()+")) ");
						dao.dbUpdate("update mission_state_table mst set mst.mission_state = 7 , mst.auto_desc='"+format.format(System.currentTimeMillis())+" i18n_server.UpgradeService.sql.revoke_n81i' where mst.mission_state = 6 and mst.mission_id in ( select lmst.mission_id from loopmission_state_table lmst where lmst.cur_mission_id in("+cancelMissionIds.toString()+")) ");
					}
					
					//存在正常周期的轮次任务
					if(missionIds.length()>1){
						dao.dbUpdate("update loopmission_state_table mst set mst.mission_state = 4 where mst.cur_mission_id in ("+missionIds.toString()+")");
					}
				}
				
				//- 变更周期任务信息状态 mission_state_table
				StringBuffer missionSql = new StringBuffer();
				missionSql.append(" select mst.mission_id,mst.mission_state");
				missionSql.append(" from (");
				missionSql.append("         select lmst.mission_id, ");
				missionSql.append("                sum(decode(lmst.mission_state, 3, 1, 7, 1, 0)) ok,");//正常执行完成的周期，撤销完成的周期
				missionSql.append("                sum(decode(lmst.mission_state, 4, 1, 0)) fail,");//未能执行的周期
				missionSql.append("                count(lmst.cur_mission_id) total");
				missionSql.append("         from loopmission_state_table lmst");
				missionSql.append("         group by lmst.mission_id");
				missionSql.append("       ) t");
				missionSql.append(" left join mission_state_table mst on mst.mission_id = t.mission_id");
				missionSql.append(" where t.ok + t.fail = t.total");
				missionSql.append("       and nvl(mst.mission_id, -1) <> -1");
				missionSql.append("       and mst.is_loop = 1");
				missionSql.append("       and mst.mission_state not in (3, 7, 4)");
				
				ArrayList<String> missFields = new ArrayList<String>();
				missFields.add("mission_id");
				missFields.add("mission_state");
				
				StringBuffer missionIds0 = new StringBuffer("0");
				List<Map<String, String>> mapList0 = dao.dbSelect(missionSql.toString(), missFields);
				//- 变更周期任务信息状态 mission_state_table
				if(mapList0 != null && mapList0.size()>0){
					EmailService emailService = new EmailService(dao);
					for(Map<String, String> map : mapList0){
						missionIds0.append(","+map.get("mission_id"));
						if(StringUtils.isNotEmpty(map.get("mission_id"))){
							// 发送邮件
//							emailService.sendEmailForMission(Long.parseLong(map.get("mission_id")), "任务执行通知", "任务执行结束");
							emailService.sendEmailForMission(Long.parseLong(map.get("mission_id")), "i18n_server.UpgradeService.missionExec_n81i", "i18n_server.UpgradeService.missionExec_n81i");
						}
					}
					//将撤销任务或撤销超时任务置为撤销完成状态
//					dao.dbUpdate("update mission_state_table mst set mst.mission_state = 7,mst.auto_desc='"+format.format(System.currentTimeMillis())+" 任务撤销完成' where mst.mission_state = 6 and mst.mission_id in ("+missionIds0.toString()+") ");
					dao.dbUpdate("update mission_state_table mst set mst.mission_state = 7,mst.auto_desc='"+format.format(System.currentTimeMillis())+" i18n_server.UpgradeService.sql.revoke_n81i' where mst.mission_state = 6 and mst.mission_id in ("+missionIds0.toString()+") ");
					//只针对完成的周期任务，不包括撤销任务（完成的状况可能是：全部完成（mission_state为3的=total），部分未能执行（fail>0））
//					dao.dbUpdate("update mission_state_table mst set mst.mission_state = 3,mst.auto_desc='"+format.format(System.currentTimeMillis())+" 任务执行完成' where mst.mission_state = 2 and mst.mission_id in ("+missionIds0.toString()+")  ");
					dao.dbUpdate("update mission_state_table mst set mst.mission_state = 3,mst.auto_desc='"+format.format(System.currentTimeMillis())+" i18n_server.UpgradeService.sql.executed_n81i' where mst.mission_state = 2 and mst.mission_id in ("+missionIds0.toString()+")  ");
					//--将超时的任务检查，单独提出-checkTimeoutLoopMisssionAndAddResult()方法
				}
			} catch (Exception e) {
				logger.error("",e);
			}finally{
				dao.clearConn();
			}
		}
	}
	
	 /**
	  * 2013-3-13 hyx
	  * 检查周期任务中超时的任务，并将结果（state状态修改）存入缓存，等待下一次录入结果线程执行时，更改任务的状态及描述
		 * 针对过期未完成的【周期】任务进行清理（非周期任务不需要清理，因为没有结束时间endTime，所以不会超时）：
		 *     1.会不会重复添加过期任务呢？-不会，因为此处将结果加入缓存后，会先执行上面的结果录入，和任务状态的改变，再执行过期任务清理时，之前的过期任务的状态已修改为3或者7，不会被统计
		 *     2.清理时，将超时的任务（mission_state_table表中state=2或者6的，且endTime小于当前时间的）的结果存入缓存(Common.addResultToResultList)
		 *     3.对于过期的周期任务：
		 *        除了修改周期结果的状态（3->1），
		 *        还需要修改loopmission_state_table表的状态(2->3或者6->7,对于状态为0的不需要修改，因为界面不会显示？更新状态时也不会统计)，
		 *        及mission_state_table的状态(2->3或者6->7，对于1的情况，在初始化任务时，已经做过超时检查了，初始化后任务的状态变为2了就，所以此处不用对1的做超时检查)，
		 *        注：将过期周期任务结果存入缓存后，上面进行统计时，就会根据结果的状态，统计loop表的状态，及mission_state_table表的状态，所以步骤3的3个修改，我们只需要做第一步，将结果存入缓存
		 *     
		 *     程序逻辑：
		 *        如果获得超时的任务：--所谓的超时，是指表mission_state_table的endTime小于当前时间
		 *          （1）从mission_state_table表查询：周期任务（isLoop=1 and missType=4），state=2或者6的，且endTime小于当前时间的任务ids
		 *          （2）根据（1）生成的任务ids，查询结果表里的信息（只查找result=3或者5的），再生成MissionResult2类（使result=1）
		 *          （3）将生成的MissionResult2存入缓存
		 */
	public void checkTimeoutLoopMisssionAndAddResult() {
		//第一步-- 超时周期任务 检查SQL
		Date sysdateD = new Date();
		String sysdate = format.format(sysdateD);//为了统一时间，都去DC的时间
		
		StringBuffer missionTimeoutCheckSQL = new StringBuffer();
		missionTimeoutCheckSQL.append(" select mst.mission_id, mst.mission_state");
		missionTimeoutCheckSQL.append(" from mission_state_table mst");
		missionTimeoutCheckSQL.append(" where mst.is_loop=1");
		missionTimeoutCheckSQL.append("       and mst.mission_type=4");
		missionTimeoutCheckSQL.append("       and mst.mission_state in(2,6)");
		missionTimeoutCheckSQL.append("       and mst.end_time<to_date('"+sysdate+"','yyyy-MM-dd HH24:mi:ss') ");
		
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("mission_id");
		fields.add("mission_state");
		try {
			StringBuffer timeoutMissIds = new StringBuffer("0");
			List<Map<String, String>> timeoutMissMapList = dao.dbSelect(missionTimeoutCheckSQL.toString(), fields);
			if(timeoutMissMapList != null && timeoutMissMapList.size()>0){
				//第二步
				for(Map<String, String> map : timeoutMissMapList){		
					timeoutMissIds.append(","+map.get("mission_id"));
				}
				System.out.println(timeoutMissIds.toString());
				
				//对于超时周期任务的清理：任务结果为下发中的部分
				List<MissionResult2> mrList = getAllMissRltsForLoopTask(timeoutMissIds.toString());					
				//第三步
				for( MissionResult2 mr :  mrList){
//					MissionResult2 result2 = new MissionResult2();
//					//- 任务Id long
//					result2.setMissionId(mr.getMissionId());
//					//-- 任务类型 long
//					result2.setMissionType(4l);
//					//- UUID long
//					result2.setUuid(mr.getUuid());
//					//- 周期标识 long
//					result2.setLoopFlag(1l);
//					//- 开始执行时间 long
//					result2.setStartTime(null);
//					//- 结束时间 long
//					result2.setEndTime(null);
//					//- 配置截取文本 string
//					result2.setText(null);
					//- 结果状态 long
					mr.setResult(1l);
					//- 结果描述 string
					mr.setDescription(MissionConstants.ERROR_RESULT_EXEC_TIMEOUT);
					
					Common.addResultToResultList(mr);//超时未执行的任务
				}
			
				//对于超时周期任务的清理：周期未初始化结果：loop表的state=0 or 1，将loop表的state修改为4未能执行
				updateTimeoutLoopMissionState(timeoutMissIds.toString());
			}
		} catch (Exception e) {
			logger.error("Check the timeout task in the cycle task and store the result of the timeout task into the cache exception",e);
		}finally{
			dao.clearConn();
		}
	}
	
	//清理指定任务id的周期任务:修改结果表和loop表时会先判断是否超时
	public void clearTimeoutLoopMisssion(Long missionId) {
		try {
			if(missionId!=null) {				
				//对于超时周期任务的清理：任务结果为下发中的部分
				List<MissionResult2> mrList = getAllMissRltsForLoopTask(missionId.toString());					
				//第三步
				for( MissionResult2 mr :  mrList){
					//- 结果状态 long
					mr.setResult(1l);
					//- 结果描述 string
					mr.setDescription(MissionConstants.ERROR_RESULT_EXEC_TIMEOUT);					
					Common.addResultToResultList(mr);//超时未执行的任务
				}				
				//对于超时周期任务的清理：周期未初始化结果：loop表的state=0 or 1，将loop表的state修改为4未能执行
				updateTimeoutLoopMissionState(missionId.toString());
			}
		} catch (Exception e) {
			logger.error("Clear the specified cycle task and store the result of timeout task into cache exception",e);
		}finally{
			dao.clearConn();
		}
	}
	
	
	private ArrayList<MissionResult2> getAllMissRltsForLoopTask(String missionIds){
		if(StringUtils.isBlank(missionIds) || "0".equals(missionIds)){
			return null;
		}
		
		ArrayList<MissionResult2> mrList = new ArrayList<MissionResult2>();
		StringBuffer searchSQL = new StringBuffer();
		searchSQL.append("select lmst.mission_id, ");
		searchSQL.append("       to_char(lmst.START_TIME,'"+Constants.DB_DATE_FORMAT+"') START_TIME, ");
		searchSQL.append("       to_char(lmst.END_TIME,'"+Constants.DB_DATE_FORMAT+"') END_TIME, ");
		searchSQL.append("       nt.node_ip, ");
		searchSQL.append("       mrt.seq_id, ");
		searchSQL.append("       nvl(mrt.result,3) result ");
		searchSQL.append("from mission_result_table4  mrt ");
		searchSQL.append("left join loopmission_state_table lmst on lmst.cur_mission_id = mrt.mission_id ");
		searchSQL.append("left join (select distinct node_ip,ipn,seq_id from node_table n) nt on nt.seq_id=mrt.seq_id ");
		searchSQL.append("where lmst.mission_id in("+missionIds+") ");
		searchSQL.append("      and nvl(mrt.result,3) in(3,5)");
		searchSQL.append("      and lmst.end_time<=to_date('"+format.format(new Date())+"','yyyy-MM-dd HH24:mi:ss') ");
		
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("mission_id");
		fields.add("START_TIME");
		fields.add("END_TIME");
		fields.add("node_ip");
		fields.add("result");
		fields.add("seq_id");
		ArrayList<Map<String, String>> rs = null;
		try {
			logger.debug(searchSQL.toString());
			rs = dao.dbSelect(searchSQL.toString(), fields);
			//-- 整理到对象集合
			if(rs!=null && rs.size()>0){
				for(Map<String, String> maps : rs){
					MissionResult2 result = new MissionResult2();
					result.setMissionId(Long.parseLong(maps.get("mission_id")));
//					result.setNodeIp(maps.get("node_ip"));
					result.setUuid(maps.get("seq_id")==null ? null:Long.parseLong(maps.get("seq_id")));
					result.setResult(maps.get("result")==null ? null:Long.parseLong(maps.get("result")));
					
					result.setEndTime(maps.get("END_TIME")==null ? null:format.parse(maps.get("END_TIME")).getTime());
					result.setStartTime(maps.get("START_TIME")==null ? null:format.parse(maps.get("START_TIME")).getTime());
//					result.setEndTime(maps.get("result")==null ? null:Long.parseLong(maps.get("result")));
					result.setMissionType(4l);
					result.setLoopFlag(1l);
					mrList.add(result);
				}
			}
		} catch (Exception e) {
			logger.error("",e);
		}finally{
			dao.clearConn();
		}
		return mrList;
	}

	
	/**
	 * 将周期任务的部分结果设置为空
	 * @time Nov 17, 2011-4:47:55 PM
	 */
//	public void checkAndUpdateLoopMissionComplete() {
//		//-- 周期任务 的检查SQL
//		StringBuffer loopSQL = new StringBuffer();
//		
////		SimpleDateFormat format = new SimpleDateFormat();
//		loopSQL.append("select lmst.cur_mission_id mission_id from (");
//		loopSQL.append("(select mrt.mission_id,sum(case when mrt.result = 0 then 1 else 0 end) ok,sum(case when mrt.result in (1,-1) then 1 else 0 end) fail,count(mrt.seq_id) total from mission_result_table4 mrt group by mrt.mission_id ) ");
//		loopSQL.append("union all " +
//		"(select mrt.mission_id,sum(case when mrt.result='7' then 1 else 0 end) ok,sum(case when mrt.result='0' then 1 else 0 end) fail,count(mrt.seq_id) total from mission_result_table4 mrt group by mrt.mission_id ) ");
//		loopSQL.append(") t ");
//		loopSQL.append("left join loopmission_state_table lmst on lmst.cur_mission_id = t.mission_id ");
//		loopSQL.append("where t.ok + t.fail = t.total ");
//		loopSQL.append("and nvl(t.mission_id,-1) <> -1 ");
//		loopSQL.append("and lmst.mission_state not in (3,7) ");
//		
//		ArrayList<String> fields = new ArrayList<String>();
//		fields.add("mission_id");
//		try {
//			StringBuffer missionIds = new StringBuffer("0"); 
//			List<Map<String, String>> mapList = dao.dbSelect(loopSQL.toString(), fields);
//			//- 变更周期任务信息状态 loopmission_state_table
//			if(mapList != null && mapList.size()>0){
//				for(Map<String, String> map : mapList){
//					missionIds.append(","+map.get("mission_id"));
////					if(StringUtils.isNotEmpty(map.get("mission_id"))){
////						createEmailContextForMission(Long.parseLong(map.get("mission_id")));
////					}
//				}
////				missionIds = missionIds.deleteCharAt(0);
//				dao.dbUpdate("update loopmission_state_table mst set mst.mission_state = 3 where mst.mission_state = 2 and mst.cur_mission_id in ("+missionIds.toString()+")");
//				dao.dbUpdate("update loopmission_state_table mst set mst.mission_state = 7 where mst.mission_state = 6 and mst.cur_mission_id in ("+missionIds.toString()+")");
//			}
//			//- 变更周期任务信息状态 mission_state_table
//			if(mapList != null && mapList.size()>0){
//				StringBuffer missionSql = new StringBuffer();
//				missionSql.append("select mst.mission_id from (");
//				missionSql.append("select lmst.mission_id,sum(decode(mrt.result,3,1,7,1,0) ) ok,sum(decode(mrt.result,4,1,0) ) fail,count(lmst.cur_mission_id) total from loopmission_state_table lmst group by lmst.mission_id ");
//				missionSql.append(") t ");
//				missionSql.append("left join mission_state_table mst on mst.mission_id = t.mission_id ");
//				missionSql.append("where t.ok + t.fail = t.total ");
//				missionSql.append("and nvl(t.mission_id,-1) <> -1 ");
//				missionSql.append("and mst.is_loop = 1 ");
//				missionSql.append("and lmst.mission_state not in(3,7,4) ");
//				
//				StringBuffer missionIds0 = new StringBuffer("0"); 
//				List<Map<String, String>> mapList0 = dao.dbSelect(loopSQL.toString(), fields);
//				//- 变更周期任务信息状态 loopmission_state_table
//				if(mapList != null && mapList.size()>0){
//					for(Map<String, String> map : mapList0){
//						missionIds0.append(","+map.get("mission_id"));
//						if(StringUtils.isNotEmpty(map.get("mission_id"))){
//							createEmailContextForMission(Long.parseLong(map.get("mission_id")));
//						}
//					}
//					dao.dbUpdate("update mission_state_table mst set mst.mission_state = 7,mst.auto_desc='"+format.format(System.currentTimeMillis())+" 任务撤销完成' where mst.mission_state = 6 and mst.mission_id in ("+missionIds.toString()+") ");
//					dao.dbUpdate("update mission_state_table mst set mst.mission_state = 3,mst.auto_desc='"+format.format(System.currentTimeMillis())+" 任务执行完成' where mst.mission_state = 2 and mst.mission_id in ("+missionIds.toString()+") and mst.end_time <= sysdate");
//					dao.dbUpdate("update mission_state_table mst set mst.mission_state = 4,mst.auto_desc='"+format.format(System.currentTimeMillis())+" 当前系统时间 大于 结束时间，无法执行' where mst.mission_state = 1 and mst.end_time <= sysdate");
//				}
//			}
//		} catch (Exception e) {
//			logger.error("",e);
//		}finally{
//			dao.clearConn();
//		}
//	}
	/**
	 * 获取任务结果更新Sql
	 * @time Nov 16, 2011-1:32:07 PM
	 * @param mr
	 * @return
	 */
//	public String getUpdateSql(MissionResult2 mr2) {
//		StringBuffer sql = new StringBuffer("update mission_result_table");
//		sql.append(mr2.getMissionType()+" mrt set ");
//		sql.append("mrt.result ='"+(mr2.getResult()==null?1:mr2.getResult())+"' ");
//		String desc = StringUtils.isEmpty(mr2.getDescription())?"":mr2.getDescription();
//		sql.append(",mrt.result_desc = substr(mrt.result_desc||'?',decode(sign(vsize(mrt.result_desc||'"+desc+"')-1024),-1,0,0,0,1,vsize(mrt.result_desc||'"+desc+"')+1-1024),1024) ");
//		sql.append("where mrt.mission_id ='"+mr2.getMissionId().longValue()+"' ");
//		sql.append("and mrt.seq_id ='"+mr2.getUuid().longValue()+"' ");
//		return sql.toString();
//	}
	
}