package com.nms.server.thread.mission;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

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

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.MissionConstants;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.EmailService;
import com.nms.server.service.UpgradeService;
import com.nms.server.thread.socket.NMSWebBPDownload;
import com.socket.utils.FileComment;

/**
 * 任务加载管理线程
 *  每两分钟执行一次，或接收激活
 *  可加载 指定任务 或 者所有符合条件的任务
 *  @date Nov 9, 2011 3:28:45 PM
 *	@author ZhangGang
 *
 */
public class LoadNewMissionThread implements Runnable{
	/* 线程基本属性 */
	private Logger logger = Logger.getLogger(LoadNewMissionThread.class);
	volatile boolean stop = false;	//线程中断标示
	
	/* 业务操作属性 */
	private CommonDao dao = null;			//数据库链接
	private UpgradeService service = null;	//
	private EmailService emailService = null;	//
	private Long missionId = null;
	
	SimpleDateFormat format = new SimpleDateFormat(Constants.COMMON_DATE_FORMAT);
	
	public LoadNewMissionThread(Long missionId){
		this.missionId = missionId;
	}
	
	@Override
	public void run(){
		if(missionId!=null){
//			Thread.currentThread().setName("新任务载入线程 Id:>"+missionId);
			Thread.currentThread().setName("The New Task Is Loaded With Thread Id:>"+missionId);
		}else{
//			Thread.currentThread().setName("新任务载入线程");
			Thread.currentThread().setName("The New Task Load Thead");
		}
		
		try {
			/* 任务加载错开并发时间 等待 0-20秒 */
			int waitTime = (int)(Math.random()*20000);
			Thread.sleep(waitTime);
			logger.debug("任务加载时间(ms)："+waitTime);
			
			dao = new CommonDao();
			service = new UpgradeService(dao);
			emailService = new EmailService(dao);

			List<MissionStateTable> missionList = service.getNewMessionList(missionId);//mission_state_table的状态为1或者5，且未过时（针对周期任务）的任务
			logger.debug("Mission_Run 新任务数量:>"+missionList.size());
						
			//遍历任务集合
			if(missionList != null && missionList.size()>0){
				
				ml:for(int i=0;i<missionList.size() && !stop;i++){	//!stop 判断线程是否中断退出
					
					/* 任务校验及初始化业务 Begin */
					MissionStateTable mission  = missionList.get(i);
					
					logger.debug("Mission_Run 任务Id:>"+mission.getMissionId());
					if(mission.getMissionState()==null){	//后续可增加任务告警
						continue;
					}

					//任务状态为3、4、7 无需执行
//					if(mission.getMissionState().intValue() == 3 
//							||mission.getMissionState().intValue() == 4 
//							||mission.getMissionState().intValue() == 7 ){
//						logger.debug("Mission_Run 任务：Id:>"+mission.getMissionId()+" 3、4、7状态 执行结束");
//						continue;
//					}else
					
					//任务状态为1 或 5 ：任务参数校验和初始化任务
					if(mission.getMissionState().intValue() == 1 || mission.getMissionState().intValue() == 5){
						logger.debug("Mission_Run 任务：Id:>"+mission.getMissionId()+" 执行任务初始化");
						
						//初始化任务信息
						if(!checkAndInitMission(mission)){	//校验并初始化任务---第一步---会改变任务的状态
							logger.debug("Mission_Run 任务：Id:>"+mission.getMissionId()+"初始化失败 执行结束");
							continue;
						}
						
					}
					
					/* 判断当前DC是否需要执行 --第二步*/
					List<MissionResult> mrList = null;
						
					if(mission.getLoopFlag()!=null && mission.getLoopFlag().longValue()==1l){	//周期任务
						if(mission.getMissionState() == 2l){
							mrList = service.getMissionResultsForLoopTask(mission.getMissionId(), mission.getMissionType().intValue(),3);
						}else if(mission.getMissionState() ==6l){
							mrList = service.getMissionResultsForLoopTask(mission.getMissionId(), mission.getMissionType().intValue(),5);
						}
					}else{	//非周期任务
						mrList = service.getMissionResultsForTask(mission.getMissionId(), mission.getMissionType().intValue());
					}
					
					if(mrList == null || mrList.size() ==0){	//当前DC无需执行----------->>>??
						continue;
					}
					
					
					
					
					logger.debug("Mission_Run 任务：Id:>"+mission.getMissionId()+((mrList == null || mrList.size() ==0)?"当前DC不执行":"当前DC执行下发"));
					
					//校验并下载附件--第三步
					List<FileComment> missionFileList = null ;
					if(mission.getMissionType().intValue() == 1 
							||mission.getMissionType().intValue() == 6){
						
						missionFileList = service.getMissionFileInformations(mission.getMissionId());
						logger.debug("Mission_Run 任务：Id:>"+mission.getMissionId()+("当前DC有附件 数量："+missionFileList.size()));
					}else{
						logger.debug("Mission_Run 任务：Id:>"+mission.getMissionId()+("当前DC无附件 "));
						Common.assignMssion(mission);
						continue;
					}

					String hostIp = service.getHostIpBySystemId(mission.getSystemId());
					Integer port = Constants.WEB_SOCKET_PORT;
					if(missionFileList != null && missionFileList.size()>0){
//						ServerTable serverTable = Common.getServerTable();
//						if(hostIp.equals(serverTable.getServerIp())){	// 同IP机器，尝试本地复制
//							try {
//								for(FileComment fileComment: missionFileList){
//									fileComment.
//									FileUtils.copyFile(srcFile, destFile);
//								}
//							} catch (Exception e) {
//								logger.equals("文件复制失败");
//							}
//						}
						
						//断点续传下载fileList 的线程结果
						Future<Object> bpf = Common.getBpDownMissionFilesMap().get(mission.getMissionId());
						
						//-- MD5校验在NMSWebBPDownload中
						//-- 未创建下载
						if(bpf == null){
							bpf = createDownload(mission.getMissionId(),hostIp,port,missionFileList);
							if(bpf == null){
								logger.debug("Mission_Run 任务：Id:>"+mission.getMissionId()+(" 附件下载失败 3分后再执行"));
								Common.scheduled.schedule(new LoadNewMissionThread(missionId),3,TimeUnit.MINUTES);
								continue ml;
							}
						}
						
						//-- 下载线程未终止 继续下载中 无操作
						if(!bpf.isDone()){
							logger.debug("Mission_Run 任务：Id:>"+mission.getMissionId()+(" 附件下载未完成 3分后再执行"));
							Common.scheduled.schedule(new LoadNewMissionThread(missionId),3,TimeUnit.MINUTES);
							continue ml;
						}
						
						//-- dff.getBpDownFuture().isDone() == true 已存在下载结果 
						int result = (Integer)bpf.get(1,TimeUnit.SECONDS);
						
						//-- MD5校验在NMSWebBPDownload中
						//-- 下载失败 则重试 0 成功 -1 -2 重试 -3 失败
						if(result == -1 || result == -2){
							bpf = createDownload(mission.getMissionId(),hostIp,port,missionFileList);
							if(bpf == null || !bpf.isDone()){
								Common.scheduled.schedule(new LoadNewMissionThread(missionId),3,TimeUnit.MINUTES);
								continue ml;
							}
						}
						
						//-- 下载成功
						boolean missionDFFlag = true;		//任务下所有文件 下载完成标识 false未完成 true已完成
						String errorFileName = null;
						mfl:for(FileComment fileInfo : missionFileList){
							
							File file = new File(Constants.MISSION_FILE_DOWNLOAD_DIR+fileInfo.getFileName());
							logger.debug("DC下载文件的路径："+Constants.MISSION_FILE_DOWNLOAD_DIR+fileInfo.getFileName());
							if(!file.exists()){	// 文件不存在，下载失败
								missionDFFlag =false;
								errorFileName = fileInfo.getFileName();
								break mfl;
							}
						}
						
						if(!missionDFFlag){//下载失败，所以将结果表示置为失败1
//							List<MissionResult2> mr2List = new ArrayList<MissionResult2>();
							//nodeList
							for( MissionResult mr :  mrList){
								MissionResult2 result2 = new MissionResult2();
								//- 任务Id long
								result2.setMissionId(mr.getMissionId());
								//-- 任务类型 long
								result2.setMissionType(mission.getMissionType());
								//- UUID long
								result2.setUuid(mr.getUuid());
								//- 周期标识 long
								result2.setLoopFlag(mission.getLoopFlag());
								//- 开始执行时间 long
								result2.setStartTime(null);
								//- 结束时间 long
								result2.setEndTime(null);
								//- 配置截取文本 string
								result2.setText(null);
								//- 结果状态 long
								result2.setResult(1l);
								//- 结果描述 string
								result2.setDescription(errorFileName+" "+MissionConstants.ERROR_RESULT_FILE_DOWNLOAD_FAIL);
//								mr2List.add(result2);
								
								Common.addResultToResultList(result2);//DC下载文件失败-2013-3-13  hyx 为了更新任务的状态及描述
							}
//							service.updateMissionResult2ByBatch(mission.getMissionType().intValue(),mr2List);
						}
						
						//清理缓存 和废弃文件
						if(!missionDFFlag){
							for(FileComment fileInfo : missionFileList){
								File file = new File(Constants.MISSION_FILE_DOWNLOAD_DIR+fileInfo.getFileName());
								if(file.exists()){
									file.delete();
									logger.debug(file.getAbsolutePath()+"已删除！");
								}else {
									logger.debug(file.getAbsolutePath()+"不存在");
								}
							}
						}else{
							//--该任务 已无文件可下载， 执行文件下发操作
							Common.assignMssion(mission);
							continue;
						}
					}else{
						//--该任务 已无文件可下载， 执行文件下发操作
						Common.assignMssion(mission);
						continue;
					}
					
					/* 线程中断判断判断 */
					if(Thread.currentThread().isInterrupted()){
						stop = true;
					}
					
				}
			
				//初始化任务结束后，需要统计更新任务的状态-2013-3-13 hyx--增加的原因：初始化的时候可能会插入结果（1：失败），但是又未统计mission_state_table表中的state，此处进行统计
			    service.updateCommonMissionComplete();//非周期任务：任务状态：成功（31）、部分成功（32）、全部失败（30）
			    service.updateLoopMissionComplete();//周期任务
			
			}
		}catch (InterruptedException e) {
			logger.warn("Thread interrupt operation, execute exit",e);
		}catch (Exception e) {
			logger.error("loadNewMission error ",e);
		}finally{
			if(dao!=null){
				dao.close();
				dao=null;
			}
		}
	
	}
	
	/**
	 * 校验并初始化参数
	 * @time Nov 15, 2011-6:21:52 PM
	 * @param missionId
	 */
	public boolean checkAndInitMission(MissionStateTable mission) {
		
		if(mission == null){
			return false;
		}
		
		boolean taskFlag = true;
		
		/* 根据任务类型校验参数 */
		switch (mission.getMissionType().intValue()) {
		case 1:
			taskFlag = checkAndInitTask1(mission);
			break;
		case 4:
			if(mission.getLoopFlag()!=null && mission.getLoopFlag().longValue()==1l){	//周期任务
				taskFlag = checkAndInitLoopTask4(mission);
//				taskFlag = false;
			}else{	//非周期任务
				taskFlag = checkAndInitTask4(mission);
			}
			break;
		case 6:
			taskFlag = checkAndInitTask6(mission);
			break;
			
		default:
			taskFlag = false;
			break;
		}
		
		//更新任务状态描述-2013-3-13 hyx--增加的原因：初始化的时候可能会插入结果（1：失败），但是又未添加描述，此处添加任务状态描述
		String missType = mission.getMissionType()==null?"":mission.getMissionType().toString();
		String isLoop = mission.getLoopFlag()==null?null:mission.getLoopFlag().toString();
		String missId = mission.getMissionId()==null?"":mission.getMissionId().toString();
		if ("4".equals(missType)&&"1".equals(isLoop)){//周期任务
			service.updateLoopMissionStateDesc(missId);//周期任务：type=4
		}else {
			service.updateCommonMissionStateDesc(Integer.parseInt(missType),missId);//非周期任务
		}
		
		return taskFlag;
	}
	
	/**
	 * 校验任务类型1（文件推送）可执行和初始化任务信息
	 * 1、校验参数完整
	 * 2、校验存在附件
	 * 3、初始化任务信息（校验任务下发节点有效、非服务器和管理范围外Node 结果判定失败）
	 * 4、判断当前DC是否可执行该任务
	 * 
	 * @time Feb 23, 2013-6:06:24 PM
	 * @param mission
	 * @return
	 */
	@SuppressWarnings("finally")
	public boolean checkAndInitTask1(MissionStateTable mission){
		boolean taskFlag = true;
		StringBuffer errorInfo = new StringBuffer();
		//查询参数信息和附件信息
		Task1 task1 = service.getTask1ById(mission.getMissionId());		//查询任务具体信息
		List<FileComment> fileCommentsList = null ;
		
		/* 任务可执行校验 */
		//第一步：任务参数完整
		if(task1 == null || StringUtils.isEmpty(task1.getTaskParam())){
			errorInfo.append(MissionConstants.ERROR_TASK_PARAMS);
			taskFlag = false;
		}
		
		//第二步：附件信息校验
		if(taskFlag){
			fileCommentsList = service.getMissionFileInformations(mission.getMissionId());
			if((fileCommentsList == null || fileCommentsList.size()==0)){
				errorInfo.append(MissionConstants.ERROR_TASK_NO_FILE);
				taskFlag=  false;
			}
		}
		
		try {
		
			//第三步：初始化任务
			if(taskFlag){
				logger.debug("missionId:> "+mission.getMissionId()+" 初始化信息");
				//先走1全部初始化（不作节点类型和节点管理范围外判断） 后续确认优化信息
				service.initMissionResults2(mission.getMissionId(),task1.getNodeGroupsId(),task1.getNodeIpsId(),mission.getMissionType().intValue());
//				emailService.sendEmailForMission(mission.getMissionId(),"任务下发通知","任务下发开始");
				emailService.sendEmailForMission(mission.getMissionId(),"i18n_server.LoadNewMissionThread.missionLssue_n81i","i18n_server.LoadNewMissionThread.missionLssueStart_n81i");
				mission.setMissionState(2l);//为了使内存中的数据和数据库中的数据一致，因为service.initMissionResults2()方法修改了missionState状态为2？
			}else{//任务失败
				logger.error("missionId:> "+mission.getMissionId()+" init info>"+errorInfo);
				service.updateMissionState(mission.getMissionId(), 4,format.format(System.currentTimeMillis())+" "+errorInfo);//hyx  修改：第二个参数传递错误
//				emailService.sendEmailForMission(mission.getMissionId(),"任务初始化失败",errorInfo+"");
//				emailService.sendEmailForMission(mission.getMissionId(),"Task initialization failed",errorInfo+"");
				emailService.sendEmailForMission(mission.getMissionId(),"i18n_server.LoadNewMissionThread.missionInitFail_n81i",errorInfo+"");
			}
			
			
			return taskFlag;
		} catch (Exception e) {
			//添加告警
			logger.error("Initialization failed",e);
			taskFlag = false;
		}finally{
			return taskFlag;
		}
	}
	
	@SuppressWarnings("finally")
	public boolean checkAndInitTask4(MissionStateTable mission){
		boolean taskFlag = true;
		StringBuffer errorInfo = new StringBuffer();
		//查询参数信息和附件信息
		Task4 task4 = service.getTask4ById(mission.getMissionId());		//查询任务具体信息
		
		/* 任务可执行校验 */
		//第一步：任务参数完整
		if(task4 == null || StringUtils.isEmpty(task4.getCommandName())|| task4.getCommandType() == 0 ){
//			errorInfo.append("命令执行任务参数为空，任务无法执行");
//			errorInfo.append("The command execution task parameter is empty, and the task cannot be executed");
			errorInfo.append("i18n_server.LoadNewMissionThread.errorInfo1_n81i");
			taskFlag = false ;
		}
		
		//第二步：初始化任务
		try {
		
			if(taskFlag){
				logger.debug("missionId:> "+mission.getMissionId()+" 初始化信息");
				//先走1全部初始化（不作节点类型和节点管理范围外判断） 后续确认优化信息
//				service.initMissionResults(mission.getMissionId(),task1.getNodeGroupsId(),task1.getNodeIpsId(),mission.getMissionType().intValue());
				service.initMissionResults2(mission.getMissionId(),task4.getNodeGroupsId(),task4.getNodeIpsId(),mission.getMissionType().intValue());
				emailService.sendEmailForMission(mission.getMissionId(),"i18n_server.LoadNewMissionThread.missionLssue_n81i","i18n_server.LoadNewMissionThread.missionLssueStart_n81i");
//				mission.setMissionState(2l);
				mission.setMissionState(2l);
			}else{//任务失败
				logger.error("missionId:> "+mission.getMissionId()+" init info>"+errorInfo);
				service.updateMissionState(mission.getMissionId(), 4,format.format(System.currentTimeMillis())+" "+errorInfo);//hyx  修改：第二个参数传递错误
				emailService.sendEmailForMission(mission.getMissionId(),"i18n_server.LoadNewMissionThread.missionExecFail_n81i",errorInfo+"");
			}
			
			return taskFlag;
		} catch (Exception e) {
			//添加告警
			logger.error("Initialization failed",e);
			taskFlag = false;
		}finally{
			return taskFlag;
		}
	}
	
	@SuppressWarnings("finally")
	public boolean checkAndInitLoopTask4(MissionStateTable mission){
		boolean taskFlag = true;
		StringBuffer errorInfo = new StringBuffer();
		//查询参数信息和附件信息
		Task4 task4 = service.getTask4ById(mission.getMissionId());		//查询任务具体信息
		
		/* 任务可执行校验 */
		//第一步：任务参数完整
		if(task4 == null || StringUtils.isEmpty(task4.getCommandName())|| task4.getCommandType() == 0 ){
//			errorInfo.append("命令执行任务参数为空，任务无法执行");
//			errorInfo.append("The command execution task parameter is empty, and the task cannot be executed");
			errorInfo.append("i18n_server.LoadNewMissionThread.errorInfo1_n81i");
			taskFlag = false ;
		}
		
		//- 任务时间的有效性校验
		if(mission.getEndTime()==null || mission.getEndTime().getTime() < System.currentTimeMillis() ){
//			errorInfo.append("已超过任务结束时间 任务未能执行");
//			errorInfo.append("The task has exceeded the end time ,and the task execution has ended");
			errorInfo.append("i18n_server.LoadNewMissionThread.errorInfo2_n81i");
			taskFlag = false ;
		}
		
		SimpleDateFormat format = new SimpleDateFormat(Constants.COMMON_DATE_FORMAT);
		try {

			//初始化任务 任务状态 1 或 5
			logger.debug(mission.getMissionId()+" 周期任务状态"+"  "+mission.getMissionState());
			mission.setNodeGroupsId(task4.getNodeGroupsId());	//保存节点组信息 
			mission.setNodeIpsId(task4.getNodeIpsId());		//保存节点信息 

			//-- 整理并初始化周期任务信息
			service.checkAndInitMissionCycle(mission);// 轮次校验和初始化
			
			//-- 获取当前周期轮次
			LoopMissionRoundInfo roundInfo = null;
			List<LoopMissionRoundInfo> roundInfoList = Common.getLoopMissionRoundInfoList().get(mission.getMissionId());
			if(roundInfoList !=null && roundInfoList.size()>0){
				//-- 获取当前周期轮次
				for (Iterator<LoopMissionRoundInfo> roundIte = roundInfoList.iterator(); roundIte.hasNext();) {
					roundInfo = roundIte.next();
					if(roundInfo.getEndTime().getTime() > System.currentTimeMillis()){
						break;
					}
				}
			}
			
			if(roundInfo == null){
//				errorInfo.append("周期任务轮次初始化异常，任务无法执行");
//				errorInfo.append("Periodic task initialization is abnormal and cannot be performed");
				errorInfo.append("i18n_server.LoadNewMissionThread.errorInfo3_n81i");
				taskFlag = false ;
			}
			
			if(taskFlag && mission.getMissionState()!= null && mission.getMissionState().intValue()==1){	//创建初始化
				logger.info("该周期任务 按正常业务执行");
				
				//-- 预置状态的轮次，初始化当前轮次的结果数据
				if(roundInfo!=null && roundInfo.getMissionState()!=null && roundInfo.getMissionState().longValue()==0l || roundInfo.getMissionState().longValue()==1l){	//0 预置状态，未初始化当前轮次的任务结果信息
					logger.info("周期任务 轮次信息初始化");
					service.initLoopMissionResults2(roundInfo.getCurMissionId(), task4.getNodeGroupsId(),task4.getNodeIpsId(),3);//初始化可下发的结果信息 3 未下发
					roundInfo.setMissionState(2l);	//更新缓存中的任务轮次信息状态
				}

				//- 变更任务状态 1（以创建） -> 2（正在执行）
//				service.updateMissionState(mission.getMissionId(), 2,format.format(System.currentTimeMillis())+" 任务执行开始");
				service.updateMissionState(mission.getMissionId(), 2,format.format(System.currentTimeMillis())+" i18n_server.LoadNewMissionThread.missionStart_n81i");
				mission.setMissionState(2l);
//				emailService.sendEmailForMission(mission.getMissionId(),"任务下发通知","任务开始执行");
//				emailService.sendEmailForMission(mission.getMissionId(),"Notification of send task","Start the task");
				emailService.sendEmailForMission(mission.getMissionId(),"i18n_server.LoadNewMissionThread.missionLssue_n81i","i18n_server.LoadNewMissionThread.missionStart_n81i");
				
			}else if(taskFlag && mission.getMissionState()!= null && mission.getMissionState().intValue()==5){	//撤销初始化
				
				//撤销任务下发操作 （获取当前操作周期或最后一个非初始化周期的轮次信息）
				logger.debug("该周期任务 按撤销业务执行");
				
				
				//-- 旧轮次信息状态记录
				int oldRoundState = roundInfo.getMissionState()==null?0:roundInfo.getMissionState().intValue();
					
				//-- 将当前周期状态 变更为撤销准备周期
				service.updateLoopMissionState(roundInfo.getCurMissionId(),5);
				
				//-- 删除预置周期
				service.deleteLoopMissionPreset(mission.getMissionId(),roundInfo.getCurMissionId());
				
				//-- 更新缓存轮次信息（上面已更新完成）
//				service.updateLoopMissionRoundInfo(Common.getLoopMissionRoundInfoList(), mission.getMissionId());
				
				//-- 将撤销周期的结果数据进行状态初始化
				if(oldRoundState == 0){	//预置周期无结果

					service.initLoopMissionResults2(roundInfo.getCurMissionId(), task4.getNodeGroupsId(),task4.getNodeIpsId(),5);//初始化可下发的结果信息 5 撤销未下发
				}else if(oldRoundState>0){	//存在结果的周期 及2或3

					service.updateMissionResultsResult(roundInfo.getCurMissionId(), 4, 5);
					service.updateLoopMissionState(roundInfo.getCurMissionId(), 6);	//更新 任务轮次信息状态
				}
				
				roundInfo.setMissionState(6l);	//更新缓存中的任务轮次信息状态
				
				//- 变更任务状态 5（准备撤销） -> 6（撤销执行）
				service.updateMissionState(mission.getMissionId(), 6,format.format(System.currentTimeMillis())+" Task revocation start execute");
				mission.setMissionState(6l);
//				emailService.sendEmailForMission(mission.getMissionId(),"任务撤销通知","任务撤销开始执行");
//				emailService.sendEmailForMission(mission.getMissionId(),"Task cancellation notice","Task revocation start execute");
				emailService.sendEmailForMission(mission.getMissionId(),"i18n_server.LoadNewMissionThread.missionRevoke_n81i","i18n_server.LoadNewMissionThread.missionRevokeStart_n81i");
			}
		
			//第三步：初始化任务
			if(!taskFlag){
//				service.updateMissionState(mission.getMissionId(), 4,format.format(System.currentTimeMillis())+" 任务执行失败");
				service.updateMissionState(mission.getMissionId(), 4,format.format(System.currentTimeMillis())+" Task execution failure");
//				emailService.sendEmailForMission(mission.getMissionId(),"任务执行失败",errorInfo+"");
//				emailService.sendEmailForMission(mission.getMissionId(),"Task execution failure",errorInfo+"");
				emailService.sendEmailForMission(mission.getMissionId(),"i18n_server.LoadNewMissionThread.missionExecFail_n81i",errorInfo+"");
			}
			
			return taskFlag;
		} catch (Exception e) {
			logger.error("Initialization failed",e);
			taskFlag = true;
		}finally{
			return taskFlag;
		}
	}
	
	/**
	 * 校验任务类型1（文件推送）可执行和初始化任务信息
	 * 1、校验参数完整
	 * 2、校验存在附件
	 * 3、初始化任务信息（校验任务下发节点有效、非服务器和管理范围外Node 结果判定失败）
	 * 4、判断当前DC是否可执行该任务
	 * 
	 * @time Feb 23, 2013-6:06:24 PM
	 * @param mission
	 * @return
	 */
	@SuppressWarnings("finally")
	public boolean checkAndInitTask6(MissionStateTable mission){
		boolean taskFlag = true;
		StringBuffer errorInfo = new StringBuffer();
		//查询参数信息和附件信息
		Task6 task6 = service.getTask6ById(mission.getMissionId());		//查询任务具体信息
		List<FileComment> fileCommentsList = null ;
		
		/* 任务可执行校验 */
		//第一步：任务参数完整
		if(task6 == null || StringUtils.isEmpty(task6.getCommandName())|| task6.getCommandType() == 0 ){
//			errorInfo.append("升级部署任务参数为空，任务无法执行");
//			errorInfo.append("The upgrade deployment task parameter is empty, and the task cannot be executed");
			errorInfo.append("i18n_server.LoadNewMissionThread.errorInfo4_n81i");
			taskFlag = false;
		}
		
		//第二步：附件信息校验
		if(taskFlag){
			fileCommentsList = service.getMissionFileInformations(mission.getMissionId());
			/** 逆向任务 无附件，其判断标示为OldTaskId 不为空 **/
			if(task6.getVersion()==null && task6.getOldTaskId()==null && (fileCommentsList == null || fileCommentsList.size()==0)){
				errorInfo.append(MissionConstants.ERROR_TASK_NO_FILE);
				taskFlag=  false;
			}
		}
		
		try {
		
			//第三步：初始化任务
			if(taskFlag){
				logger.debug("missionId:> "+mission.getMissionId()+" 初始化信息");
				//先走1全部初始化（不作节点类型和节点管理范围外判断） 后续确认优化信息
				service.initMissionResults2(mission.getMissionId(),task6.getNodeGroupsId(),task6.getNodeIpsId(),mission.getMissionType().intValue());
//				emailService.sendEmailForMission(mission.getMissionId(),"任务下发通知","任务下发开始");
//				emailService.sendEmailForMission(mission.getMissionId(),"Notification of send task","Start task");
				emailService.sendEmailForMission(mission.getMissionId(),"i18n_server.LoadNewMissionThread.missionLssue_n81i","i18n_server.LoadNewMissionThread.missionLssueStart_n81i");
				mission.setMissionState(2l);
			}else{//任务失败
				logger.error("missionId:> "+mission.getMissionId()+" init info>"+errorInfo);
				service.updateMissionState(mission.getMissionId(), 4,format.format(System.currentTimeMillis())+" "+errorInfo);//hyx  修改：第二个参数传递错误
//				emailService.sendEmailForMission(mission.getMissionId(),"任务执行失败",errorInfo+"");
//				emailService.sendEmailForMission(mission.getMissionId(),"Task execution failure",errorInfo+"");
				emailService.sendEmailForMission(mission.getMissionId(),"i18n_server.LoadNewMissionThread.missionExecFail_n81i",errorInfo+"");
			}
			
			return taskFlag;
		} catch (Exception e) {
			//添加告警
			logger.error("Initialization failed",e);
			taskFlag = false;
		}finally{
			return taskFlag;
		}
	}

	/**
	 * 创建下载线程
	 * @time Mar 20, 2012-4:12:42 PM
	 * @param missionFileList
	 * @return
	 */
	private Future<Object> createDownload(Long missionId ,String ip,Integer port,List<FileComment> missionFileList){
		try {
			Future<Object> bpf = Common.service.submit(new NMSWebBPDownload(ip,port,missionFileList,Constants.MISSION_FILE_DOWNLOAD_DIR,NMSWebBPDownload.TYPE_MISSION));
			bpf.get(Constants.MISSION_FILE_DOWNLOAD_DELAY, TimeUnit.SECONDS);
			if(!bpf.isDone()){
				Common.getBpDownMissionFilesMap().put(missionId, bpf);
			}
			return bpf;
		} catch (Exception e) {
			logger.error("Failure to create a download thread ",e);
			return null;
		}
	}
	
	public static void main(String [] args) {
//		Common.service.submit(new LoadNewMissionThread(1343l));
		Common.service.submit(new LoadNewMissionThread(4125l));
	}
}
