package com.nms.server.thread.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.Charset;
import java.util.Calendar;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import net.sf.json.JSONObject;

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

import com.nms.server.bean.MissionResult2;
import com.nms.server.bean.ReturnFilePO;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.util.FileUtils;
import com.nms.server.util.UnicodeReader;

/**
 * XML解析线程
 * 
 * @author ZGGG3
 * 
 */
public class ReturnFileReaderThread implements Runnable {
	Logger logger = Logger.getLogger(ReturnFileReaderThread.class);
	private String dir;
	private String name; // 自定义Thread Name

	public ReturnFileReaderThread(String name, String url) {
		this.dir = url;
		this.name = name;
	}

	public void run() {
		// 为当前线程命名 ，用与开发阶段友好输出。
		Thread.currentThread().setName(name);

		try {
			File root = new File(dir);
			File[] dirFiles = FileUtils.listFilesForDirectory(root);
			
			// 解析文件数为0时，终止该计划任务
			if(dirFiles==null || dirFiles.length==0){
				Common.cancelRunnableAtOnce(dir);
				return;
			}
			
			for(File driFile : dirFiles){
				
				logger.info("文件夹路径 :>" + driFile.getAbsolutePath());

				//获取目录下的.return文件集合
				File[] files = FileUtils.sortByFileNameASC(FileUtils.listFilesEndWith(driFile, ".return")); // 按文件名称 升序排序
				
				// 解析文件数为0时，终止该计划任务
				if(files==null || files.length==0){
					FileUtils.deleteDirectory(driFile);
					continue;
				}
			
				logger.debug("文件夹路径 " + files.length + "个文件，解析开始");
				long l = Calendar.getInstance().getTimeInMillis();
				if (files != null && files.length > 0) {
					for (File file : files) {
						if(file.length()>0){
							
							BufferedReader reader = new BufferedReader(new UnicodeReader(new FileInputStream(file), Charset.defaultCharset().name()));
							String data = StringUtils.trim(reader.readLine());
							
							if(StringUtils.isNotEmpty(data)){
								
								ReturnFilePO returnFilePO = (ReturnFilePO) JSONObject.toBean(JSONObject.fromObject(data), ReturnFilePO.class);
								String fnInfo = "";
								if(StringUtils.isEmpty(returnFilePO.getReturnFileName())){
									fnInfo= "";
								}else{
//									fnInfo= " 回传成功";
//									fnInfo= " Success comes back";
									fnInfo= " i18n_server.ReturnFileReaderThread.fnInfo_n81i";
								}
								MissionResult2 result2 = new MissionResult2(
										returnFilePO.getTaskId(),
										returnFilePO.getTaskType(),
										returnFilePO.getUuid(),
										returnFilePO.getStartTime().getTime(),
										returnFilePO.getEndTime().getTime(),
										null,
										returnFilePO.getState(),
										returnFilePO.getResDesc()+ fnInfo,
										null,
										returnFilePO.getIsLoop()
										);
								
								if(StringUtils.isNotEmpty(returnFilePO.getReturnFileName())){
									String rFilePath = file.getParentFile().getAbsolutePath()+File.separator+returnFilePO.getReturnFileName();
									File rFile = new File(rFilePath);
									
									if(rFile.exists()){	//回传文件存在
										System.out.println("回传文件存在");
										
										result2.setFileInfo(returnFilePO.getReturnFileName());
										FileUtils.copyFile(rFile, new File(Constants.MISSION_FILE_UPLOAD_DIR+returnFilePO.getReturnFileName()));
										rFile.delete();
									}else{
										System.out.println("回传文件不存在");
										result2.setDescription(result2.getDescription()+"\n"+returnFilePO.getReturnFileName()+"不存在");
									}
								}
								
								Common.addResultToResultList(result2);
							}
							reader.close();
						}
						file.delete();
					}
				}
				logger.debug(driFile.getAbsolutePath()+" 解析完成耗时：>"+(Calendar.getInstance().getTimeInMillis()-l));
				//清理
				files = FileUtils.sortByFileNameASC(FileUtils.listFilesEndWith(driFile, ".tp")); // 按文件名称 升序排序
				if(files!=null && files.length>0){
					for(File file : files){
						file.delete();
					}
				}
				
				//删除当前目录
				driFile.delete();
			}
			logger.debug("临时文件清理完成");
		} catch (Exception e) {
			logger.error("",e);
		}finally{
		}
	}

	public static void main(String[] args) {
		long l = Calendar.getInstance().getTimeInMillis();
		Future<?> future = Common.service.submit(new ReturnFileReaderThread("文件解析线程", "D:\\ControllerData\\dc_zip\\resove\\return"));
		try {
			future.get();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(Calendar.getInstance().getTimeInMillis()-l);
	}
}
