/*
#=============================================================================
#																			   
#			copyright (c) 2009 Origin Enterprise Solution LTD.		   
#																			   
#=============================================================================
# File name: DatasetFileDown.java
# File description: 										   	
#=============================================================================
#	Date		Name		    Action	Description of Change					   
#	2011-4-20	liqz  	                      创建		下载数据集(From Shaangu)		
#   2011-5-19   liqz			修改			允许下载未发布的数据集，文件夹下的数据集也允许下载
#=============================================================================
 */
package cn.com.customization.download;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.teamcenter.rac.aif.AbstractAIFApplication;
import com.teamcenter.rac.aif.AbstractAIFOperation;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.kernel.TCAccessControlService;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentDataset;
import com.teamcenter.rac.kernel.TCComponentFolder;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentProcess;
import com.teamcenter.rac.kernel.TCComponentPseudoFolder;
import com.teamcenter.rac.kernel.TCComponentTask;
import com.teamcenter.rac.kernel.TCComponentTcFile;
import com.teamcenter.rac.kernel.TCComponentUser;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCPreferenceService;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.ConfirmationDialog;
import com.teamcenter.rac.util.MessageBox;

import cn.com.customization.imports.importfiles.ORProgressBarThread;
import cn.com.customization.util.GetCommonInfo;
import cn.com.customization.util.PackFailDownInfo;
import cn.com.customization.util.PackResultInfo;
import cn.com.customization.util.PackSuccessfulInfo;
import cn.com.customization.util.ResultDialog;
import cn.com.customization.util.ShowMessageDialog;
import cn.com.customization.util.UtilApi;
import cn.com.customization.util.WriteAndCopyFile;

@SuppressWarnings("deprecation")
public class DatasetFileDown extends AbstractAIFOperation implements Runnable {
	private TCSession					session						= null;
	private InterfaceAIFComponent		targetComponent				= null;
	private ORProgressBarThread			progressbarthread			= null;
	private GetCommonInfo				checkcommon;
	private String						path						= "";
	private int							downDataSetCount			= 0;
	private int							isNotHavePriviligeCount		= 0;
	private int							haveEqualDataSetCount		= 0;
	private String						validTypeOption				= "CUST_batchdown_validtype";
	// 当origin_showLogFile中的值为true则会生成日志文件：c:\\batchExportDataset.log
	private String						isShowLogOption				= "CUST_showLogFile";
	private int							notReleasedDataSetCount		= 0;
	private boolean						isDownReleased				= false;
	private List<TCComponentDataset>	haveDownDataSet				= null;
	private WriteAndCopyFile			writeLog;
	private String						logFileName					= "c:/batchExportDataset.log";
	private List<String>				notExistFiles				= new ArrayList<String>();
	private int							downCount					= 0;
	private List<PackFailDownInfo>		failDownInfos				= new ArrayList<PackFailDownInfo>();
	private int							needDownCount				= 0;
	private List<PackSuccessfulInfo>	successfulInfos				= new ArrayList<PackSuccessfulInfo>();
	private String						currentJob					= "";
	private String						successfulDir				= System.getenv("temp");//"c:/ugs/log";
	private boolean						isShiftProcessDown;
	private String						changePackageName			= "更改单";
	private String						technologyPackageName		= "技术文件";

	//private TCUserService				userService					= null;
	private List<String>				logsList					= new ArrayList<String>();
	private boolean						isContainsGGD				= false;
	private boolean						isContainsTechnologyItem	= false;

	public DatasetFileDown(AbstractAIFApplication application, TCSession tcsession, InterfaceAIFComponent targetCom, boolean isShiftProcessDown) {
		checkcommon = new GetCommonInfo(tcsession);
		session = tcsession;
		targetComponent = targetCom;
		writeLog = new WriteAndCopyFile();
		this.isShiftProcessDown = isShiftProcessDown;

		//userService = (TCUserService) session.getUserService();

		File dir = new File(successfulDir);
		if (!dir.exists()) {
			dir.mkdir();
		}
		if (isShowLog()) {
			File file = new File(logFileName);
			if (file.exists()) {
				writeLog.writeFile(logFileName, false, "\r\n");
			} else {
				try {
					file.createNewFile();
					writeLog.writeFile(logFileName, false, "\r\n");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} else {
			File file = new File(logFileName);
			if (file.exists()) {
				file.delete();
			}
		}
	}

	private void writeLogFile(String fileName, String content) {
		if (isShowLog()) {
			content = content + "\r\n";
			writeLog.writeFile(fileName, true, content);
		}
	}

	private void writeSuccessfulLogFile(String fileName, String content) {
		content = content + "\r\n";
		writeLog.writeFile(fileName, true, content);
		logsList.add(content);
	}

	public String getTime() {
		String strTime = "";
		try {
			SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss:SSS");
			strTime = bartDateFormat.format(new Date());
			// System.out.println(strTime);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strTime;
	}

	@Override
	public void executeOperation() throws Exception {
		System.out.println("Begin to call filedown operation...");
		String cuurentPath = checkcommon.getChoosePath();
		path = cuurentPath;
		isDownReleased = false;
		isDownReleased();
		haveDownDataSet = new ArrayList<TCComponentDataset>();
		if ((cuurentPath != null) && (cuurentPath.length() == 0)) {
			return;
		} else {
			if (checkcommon.isExistFiles(cuurentPath)) {
				int value = ConfirmationDialog.post("提示","指定的目录下非空，是否下载?");
				if(value == ConfirmationDialog.NO){
					return;
				}
			}
		}
		try {
			writeLogFile(logFileName, "开始下载: " + getTime());
			// writeLogFile("所选路径为: " + cuurentPath, logFileName);
			writeLogFile(logFileName, " ");
			int importAll = 0;

			PackSuccessfulInfo succesfulDataset = new PackSuccessfulInfo();
			succesfulDataset.setIndex("序号");
			succesfulDataset.setItemID("零组件ID");
			succesfulDataset.setItemRev("版本");
			succesfulDataset.setItemOwner("所有者");
			succesfulDataset.setDataset("数据集");
			succesfulDataset.setRefFile("命名的引用");
			successfulInfos.add(succesfulDataset);

			if (targetComponent instanceof TCComponentItemRevision) {
				progressbarthread = new ORProgressBarThread("数据集导出中......", "数据导出中，请稍等...");
				progressbarthread.start();
				session.setStatus("导出中...");
				getDataSetFromItemRevision((TCComponentItemRevision) targetComponent, cuurentPath);
			} else {
				if (targetComponent instanceof TCComponentDataset) {
					return;
				} else {
					if (targetComponent instanceof TCComponentItem) {
						progressbarthread = new ORProgressBarThread("数据集导出中......", "数据导出中，请稍等...");
						progressbarthread.start();
						session.setStatus("导出中...");
						getDataSetFromItem((TCComponentItem) targetComponent, cuurentPath);
					} else {
						if (targetComponent instanceof TCComponentFolder) {
//							importAll = new GetMessageDialog("INFO", "是否导出子文件夹?").getValue();
							importAll = ConfirmationDialog.post("提示","是否导出子文件夹?");
							currentJob = ((TCComponentFolder) targetComponent).getProperty("object_name");
							System.out.println("TCComponentFolder===========" + targetComponent);
						} else {
							if (targetComponent instanceof TCComponentTask) {
								TCComponentTask task = (TCComponentTask) targetComponent;
								// task.getName(); 电子签名
								TCComponentProcess process = task.getProcess();
								if (process != null) {
									currentJob = process.toString(); // 000009/H;1-sgitem测试
									System.out.println("targetComponent.currentJob()===========" + currentJob);
								}
							}
						}
						progressbarthread = new ORProgressBarThread("数据集导出中......", "数据导出中，请稍等...");
						progressbarthread.start();
						session.setStatus("导出中...");
						getTargetCom(targetComponent, cuurentPath, importAll);
					}
				}
			}
			session.setReadyStatus();
			progressbarthread.setBool(true);

			writeLogFile(logFileName, " ");
			writeLogFile(logFileName, "总结：");
			writeLogFile(logFileName, "存在数据集:" + haveDownDataSet.size() + "个");
			writeLogFile(logFileName, "未发布数据集:" + notReleasedDataSetCount + "个");
			writeLogFile(logFileName, "无权限数据集:" + isNotHavePriviligeCount + "个");
			writeLogFile(logFileName, "需要下载文件:" + needDownCount + "个");
			writeLogFile(logFileName, "成功下载文件:" + downDataSetCount + "个");
			writeLogFile(logFileName, "无引用文件数据集:" + notExistFiles.size() + "个");
			writeLogFile(logFileName, "未成功下载文件:" + (needDownCount - downDataSetCount) + "个");

			PackResultInfo resultInfo = new PackResultInfo();
			SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd:HHmmss");
			String time = date.format(new Date());
			resultInfo.setTime(time);
			resultInfo.setPerson(session.getUser().toString());
			resultInfo.setJob(currentJob);

			resultInfo.setExistDataSetCount(haveDownDataSet.size());
			resultInfo.setNeedNum(needDownCount);
			resultInfo.setSuccessNum(downDataSetCount);
			resultInfo.setNoReleasedNum(notReleasedDataSetCount);
			resultInfo.setNoPrivilegelNum(isNotHavePriviligeCount);
			resultInfo.setNoReferenceNum(notExistFiles.size());
			resultInfo.setEqualNameNum(haveEqualDataSetCount);
			resultInfo.setFailNum((needDownCount - downDataSetCount));
			resultInfo.setFailDownInfo(failDownInfos);

			// 时间：2010-06-15:8890 下载人：XXXXXX, 所选流程（目录）：XXXXXXXXXX
			// 存在数据集:80
			// 未发布数据集：76
			// 无权限数据集：0
			// 需下载文件：30
			// 成功下载文件：80
			// 无引用文件数据集：0

			// 未成功下载文件列表：
			// 零组件id 版本 所有者 数据集，命名的引用
			String logPath = successfulDir + "/批量下载文件日志_" + (new SimpleDateFormat("yyyyMMdd")).format(new Date()) + ".log";
			writeSuccessfulLogFile(logPath, "  ");
			writeSuccessfulLogFile(logPath, "===========================================================================================================================");
			writeSuccessfulLogFile(logPath, "时间:" + time + "     下载人:" + session.getUser().toString() + "     所选流程(目录):" + currentJob);
			writeSuccessfulLogFile(logPath, "  ");
			writeSuccessfulLogFile(logPath, "存在数据集:" + haveDownDataSet.size());
			writeSuccessfulLogFile(logPath, "未发布数据集:" + notReleasedDataSetCount);
			writeSuccessfulLogFile(logPath, "无权限数据集:" + isNotHavePriviligeCount);
			writeSuccessfulLogFile(logPath, "需下载文件:" + needDownCount);
			writeSuccessfulLogFile(logPath, "成功下载文件:" + downDataSetCount);
			writeSuccessfulLogFile(logPath, "无引用文件数据集:" + notExistFiles.size());
			writeSuccessfulLogFile(logPath, "  ");
			writeSuccessfulLogFile(logPath, "已成功下载文件列表:");
			writeSuccessfulLogFile(logPath, "---------------------------------------------------------------------------");
			for (int i = 0; i < successfulInfos.size(); i++) {
				PackSuccessfulInfo successfulInfo = successfulInfos.get(i);
				writeSuccessfulLogFile(logPath, appendSpace(successfulInfo.getIndex().trim(), 5) + appendSpace(successfulInfo.getItemID().trim(), 32) + appendSpace((successfulInfo.getItemRev() == null ? "" : successfulInfo.getItemRev().trim()), 5) + appendSpace(successfulInfo.getItemOwner().trim(), 25) + appendSpace(successfulInfo.getDataset().trim(), 50) + appendSpace(successfulInfo.getRefFile().trim(), 50));
			}
			writeSuccessfulLogFile(logPath, "  ");
			// 服务器端日志 remove by sz 2017-6-1
//			try {
//				Object objs[] = new Object[1];
//				objs[0] = logsList.toArray();
//				userService.call("DatasetDownLog", objs);
//			} catch (TCException e) {
//				e.printStackTrace();
//			}
			//end remove
			if (haveDownDataSet.size() == 0) {
				new ShowMessageDialog("信息提示", "下载了0个数据集！", "");
				return;
			}
			new ResultDialog(resultInfo, session);
		} catch (Exception e) {
			session.setReadyStatus();
			if (progressbarthread != null) {
				progressbarthread.setBool(true);
			}
			MessageBox.post("数据导出出现异常:" + e.getMessage(), "ERROR", 1);
			e.printStackTrace();
		}
	}

	private String appendSpace(String str, int num) {
		if (str.length() < num) {
			for (int i = UtilApi.length(str) + 1; i <= num; i++) {
				str += " ";
			}
		}
		return str;
	}

	private void getTargetType(InterfaceAIFComponent aif) {
		isContainsGGD = false;
		isContainsTechnologyItem = false;
		try {
			if (aif.getChildren() != null) {
				AIFComponentContext[] getChild = aif.getChildren();
				if (getChild.length != 0) {
					isContainsTechnologyItem = true;
					int revCount = 0;
					for (int i = 0; i < getChild.length; i++) {
						InterfaceAIFComponent childComponent = getChild[i].getComponent();
						if (childComponent instanceof TCComponentItemRevision) {
							TCComponentItemRevision itemRevision = (TCComponentItemRevision) childComponent;
							if (itemRevision != null) {
								++revCount;
								String revType = itemRevision.getType();
								if (revType.equals("GGDitem Revision") || revType.equals("HTDitem Revision")) {
									isContainsGGD = true;
									isContainsTechnologyItem = false;
								} else {
									if (!revType.equals("技术文件 Revision")) {
										isContainsTechnologyItem = false;
									}
								}
							}
						}
					}
					if (revCount == 0) {
						isContainsTechnologyItem = false;
					}
				}
			}
		} catch (Exception e) {
			session.setReadyStatus();
			progressbarthread.setBool(true);
			MessageBox.post("遍历时出错:" + e.getMessage(), "ERROR", 1);
			e.printStackTrace();
		}
	}

	/**
	 * getTargetCom:得到数据集对象
	 * @param @return 设定文件
	 * @param aif
	 * @param cuurentPath 文件要保存路径
	 * @param importAll importAll=2要导出子文件夹，1只是导出第一层子文件。
	 * @return String 对象类型
	 * @throws
	 * @since CodingExample　Ver 1.1
	 */
	private void getTargetCom(InterfaceAIFComponent aif, String cuurentPath, int importAll) {
		if (aif.toString().equalsIgnoreCase("root_target_attachments") || aif.toString().equalsIgnoreCase("目标")) {
			System.out.println("aif=============" + aif);
			getTargetType(aif);
			if (isContainsGGD) {
				cuurentPath = createFile(path, changePackageName);
			} else {
				if (isContainsTechnologyItem) {
					cuurentPath = createFile(path, technologyPackageName);
				}
			}
		}
		System.out.println("cuurentPath=============" + cuurentPath);
		try {
			AIFComponentContext[] getChild = aif.getChildren();
			if (getChild.length != 0) {
				for (int i = 0; i < getChild.length; i++) {
					InterfaceAIFComponent childComponent = getChild[i].getComponent();
					if (childComponent instanceof TCComponentDataset) {
						datasetFileDown((TCComponentDataset) childComponent, cuurentPath, null);
					} else if (childComponent instanceof TCComponentTask) {
						getTargetCom(childComponent, cuurentPath, importAll);
					} else if (childComponent instanceof TCComponentItem) {
						if (aif instanceof TCComponentPseudoFolder) {
							TCComponentPseudoFolder psefolder1 = (TCComponentPseudoFolder) aif;
							String objectString1 = psefolder1.getProperty("object_string");
							if ((objectString1.equalsIgnoreCase("root_target_attachments")) || (objectString1.equalsIgnoreCase("root_reference_attachments")) || (objectString1.equalsIgnoreCase("目标")) || (objectString1.equalsIgnoreCase("引用"))) {
								continue;
							}
						}
						getDataSetFromItem((TCComponentItem) childComponent, cuurentPath);
					} else if ((childComponent instanceof TCComponentFolder)) {
						if (aif instanceof TCComponentPseudoFolder) {
							TCComponentPseudoFolder psefolder1 = (TCComponentPseudoFolder) aif;
							String objectString1 = psefolder1.getProperty("object_string");
							if ((objectString1.equalsIgnoreCase("root_target_attachments")) || (objectString1.equalsIgnoreCase("root_reference_attachments")) || (objectString1.equalsIgnoreCase("目标")) || (objectString1.equalsIgnoreCase("引用"))) {
								continue;
							}
						}
//						if (!path.equalsIgnoreCase(cuurentPath)) {
//							continue;
//						}
						File file = null;
						if (importAll == 2) {
							String folderName = childComponent.toString();
							List<String> list = new ArrayList<String>();
							list.add("\\");
							list.add("/");
							list.add(":");
							list.add("*");
							list.add("?");
							list.add("\"");
							list.add("<");
							list.add(">");
							list.add("|");
							for (int j = 0; j < list.size(); j++) {
								while (folderName.indexOf(list.get(j)) >= 0) {
									folderName = folderName.replace(list.get(j), "_");
								}
							}
							file = new File(cuurentPath + "\\" + folderName);
							if (!file.exists()) {
								file.mkdir();
							} else {
								file = new File(cuurentPath + "\\" + folderName + "_" + UtilApi.getTimeNum());
								file.mkdir();
							}
							getTargetCom(childComponent, file.getAbsolutePath(), importAll);
						} else {
							continue;
						}
					} else if (childComponent instanceof TCComponentItemRevision) {
						getDataSetFromItemRevision((TCComponentItemRevision) childComponent, cuurentPath);
					} else {
						if (childComponent instanceof TCComponentPseudoFolder) {
							TCComponentPseudoFolder psefolder = (TCComponentPseudoFolder) childComponent;
							String objectString = psefolder.getProperty("object_string");
							if (objectString.equalsIgnoreCase("root_target_attachments") || objectString.equalsIgnoreCase("目标")) {
								getTargetCom(childComponent, cuurentPath, importAll);
							}
						}
					}
				}
			}
		} catch (Exception e) {
			session.setReadyStatus();
			progressbarthread.setBool(true);
			MessageBox.post("在提取数据时出现异常:" + e.getMessage(), "ERROR", 1);
			e.printStackTrace();
		}
	}

	/**
	 * getDataSetFromItemRevision:通过版本得到数据集
	 * @param @return 设定文件
	 * @param tcRevision
	 * @param cuurentPath 文件要保存路径
	 * @throws
	 * @since CodingExample　Ver 1.1
	 */
	private void getDataSetFromItemRevision(TCComponentItemRevision tcRevision, String cuurentPath) {
		if (tcRevision == null) {
			return;
		}
		try {
			tcRevision.refresh();
		} catch (TCException e2) {
			e2.printStackTrace();
		}
		try {
			TCComponent tccomps[] = tcRevision.getRelatedComponents("IMAN_specification");
			try {
				String type = tcRevision.getType();
				String revision = tcRevision.getProperty("item_revision_id");
				
				if (isShiftProcessDown) {
					TCComponentProcess process = tcRevision.getCurrentJob();
					String processName = process.getRootTask().toString();
					// System.out.println("processName===============" +
					// processName);
					// System.out.println("type================" + type);
					if (processName.startsWith("SG_ECR_") && (type.equals("GGDitem Revision"))) {
						for (int i = 0; i < tccomps.length; i++) {
							if (tccomps[i] instanceof TCComponentDataset) {
								TCComponentDataset dataset = (TCComponentDataset) tccomps[i];
								if ((dataset.toString().contains("/" + revision + "/")) || (dataset.toString().contains("/" + revision))) {
									datasetFileDown(dataset, cuurentPath, tcRevision);
								}
							}
						}
					} else {
						if (processName.startsWith("SG_HTR_")) {
							for (int i = 0; i < tccomps.length; i++) {
								if (tccomps[i] instanceof TCComponentDataset) {
									TCComponentDataset dataset = (TCComponentDataset) tccomps[i];
									if ((dataset.toString().contains("/" + revision + "/")) || (dataset.toString().contains("/" + revision))) {
										datasetFileDown(dataset, cuurentPath, tcRevision);
									}
								}
							}
						} else {
							for (int i = 0; i < tccomps.length; i++) {
								if (tccomps[i] instanceof TCComponentDataset) {
									TCComponentDataset dataset = (TCComponentDataset) tccomps[i];
									datasetFileDown(dataset, cuurentPath, tcRevision);
								}
							}
						}
					}
				} else {
					for (int i = 0; i < tccomps.length; i++) {
						if (tccomps[i] instanceof TCComponentDataset) {
							datasetFileDown((TCComponentDataset) tccomps[i], cuurentPath, tcRevision);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (TCException e) {
			e.printStackTrace();
		}
	}

	/**
	 * getDataSetFromItem:通过Item得到数据集
	 * @param @return 设定文件
	 * @param item
	 * @param cuurentPath 文件要保存路径
	 * @return String 对象类型
	 * @throws
	 * @since CodingExample　Ver 1.1
	 */
	private void getDataSetFromItem(TCComponentItem item, String cuurentPath) {
		TCComponentItemRevision tcRevision;
		try {
			item.refresh();
		} catch (TCException e2) {
			e2.printStackTrace();
		}
		try {
			tcRevision = item.getLatestItemRevision();
			if (tcRevision == null) {
				return;
			}
			try {
				TCComponent tccomps[] = tcRevision.getRelatedComponents("IMAN_specification");
				for (int i = 0; i < tccomps.length; i++) {
					if (tccomps[i] instanceof TCComponentDataset) {
						datasetFileDown((TCComponentDataset) tccomps[i], cuurentPath, tcRevision);
					}
				}
			} catch (TCException e) {
				e.printStackTrace();
			}
		} catch (TCException e1) {
			e1.printStackTrace();
		}
	}

	/**
	 * datasetFileDown:导出数据集对象的引用文件
	 * @param @return 设定文件
	 * @param dataset
	 * @param fileCurrentPath
	 * @return String 对象类型
	 * @throws
	 * @since CodingExample　Ver 1.1
	 */

	private void datasetFileDown(TCComponentDataset dataSet, String fileCurrentPath, TCComponentItemRevision itemRevision) {
		try {
			dataSet.refresh();
		} catch (TCException e2) {
			e2.printStackTrace();
		}
		if (haveDownDataSet != null) {
			if (haveDownDataSet.contains(dataSet)) {
				return;
			}
		}
		// String fileCurrentPath = currentPath;
		haveDownDataSet.add(dataSet);
		PackFailDownInfo dataSetInfo = new PackFailDownInfo();
		try {
			String itemID = "";
			String rev = "";
			if (itemRevision != null) {
				itemID = itemRevision.getProperty("item_id");
				rev = itemRevision.getProperty("current_revision_id");
			}
			String owner = dataSet.getProperty("owning_user");
			dataSetInfo.setOwner(owner);
			dataSetInfo.setItemId(itemID);
			dataSetInfo.setRev(rev);
			dataSetInfo.setDatasetName(dataSet.toString());
			dataSetInfo.setDataSet(dataSet);
			dataSetInfo.setItemRev(itemRevision);
		} catch (TCException e3) {
			writeLogFile(logFileName, e3.getMessage());
			e3.printStackTrace();
		}

		writeLogFile(logFileName, "存在数据集:" + dataSet.toString());
		// System.out.println("dataSet............" + dataSet.toString());
		try {
			String release = dataSet.getProperty("release_status_list").trim();
			if (release != null) {
				// String regex = ".*Released.*";
				// Pattern pattern = Pattern.compile(regex,
				// Pattern.CASE_INSENSITIVE);
				// Matcher match = pattern.matcher(release);
				// boolean find = match.find();
				if (release.length() == 0) {
					notReleasedDataSetCount++;
					writeLogFile(logFileName, "未发布");
					if (isDownReleased) {
						dataSetInfo.setReason("未发布");
						failDownInfos.add(dataSetInfo);
						writeLogFile(logFileName, "");
						return;
					}
				} else {
					writeLogFile(logFileName, "已经发布");
				}
			}
		} catch (TCException e2) {
			e2.printStackTrace();
		}
		try {
			boolean isCanExport = false;
			isCanExport = checkAccessPrivilige(session.getUser(), dataSet, "EXPORT");
			if (!isCanExport) {
				++isNotHavePriviligeCount;
				dataSetInfo.setReason("没有导出权限");
				failDownInfos.add(dataSetInfo);
				writeLogFile(logFileName, "没有导出权限");
				writeLogFile(logFileName, " ");
				return;
			} else {
				writeLogFile(logFileName, "有导出权限 ");
			}
		} catch (TCException e1) {
			e1.printStackTrace();
		}
		TCComponentTcFile tcFile = null;
		String fileName = "";
		try {
			if ((dataSet.getTcFiles() != null) && (dataSet.getTcFiles().length > 0)) {
				for (int i = 0; i < dataSet.getTcFiles().length; i++) {
					tcFile = dataSet.getTcFiles()[i];
					if (tcFile == null) {
						return;
					}
					tcFile.refresh();
					fileName = tcFile.getProperty("original_file_name");
					if (fileName != null) {
						needDownCount++;
						dataSetInfo.setFilePath(fileCurrentPath);
						dataSetInfo.setReference_file(fileName);
						dataSetInfo.setNeedDown("true");
						String fileType = "";
						String preFileName = "";
						int index = fileName.lastIndexOf(".");
						if (index > 0) {
							fileType = fileName.substring(index, fileName.length());
							preFileName = fileName.substring(0, index);
						} else {
							preFileName = fileName;
						}
						boolean flag = checkcommon.existFile(fileCurrentPath, fileName);
						if (flag) {
							haveEqualDataSetCount++;
							int pos = fileName.indexOf('.');
							if (pos > 0) {
								fileName = preFileName + "_" + UtilApi.getTimeNum() + fileType;
							}
						}
						if (fileName.indexOf('/') >= 0) {
							fileName = fileName.replace('/', '_');
						}
						downCount = 0;
						getTCFile(tcFile, fileCurrentPath, fileName, dataSetInfo);
					}
				}
			} else {
				dataSetInfo.setReason("不存在引用文件");
				failDownInfos.add(dataSetInfo);
				notExistFiles.add(dataSet.toString());
				writeLogFile(logFileName, "不存在引用文件！");
			}
			writeLogFile(logFileName, " ");
		} catch (Throwable e) {
			writeLogFile(logFileName, "导出文件时出现异常！");
			writeLogFile(logFileName, e.getMessage());
			writeLogFile(logFileName, " ");
			e.printStackTrace();
		}
	}

	private File getTCFile(TCComponentTcFile tcFile, String fileCurrentPath, String fileName, PackFailDownInfo dataSetInfo) {
		++downCount;
		if (downCount == 2) {
			writeLogFile(logFileName, "第二次下载");
		}
		File file = null;
		try {
			file = tcFile.getFile(fileCurrentPath, fileName);
			if (file != null) {
				++downDataSetCount;
				writeLogFile(logFileName, "导出文件:" + fileName + "      " + getTime());
				writeLogFile(logFileName, " ");
				// successfulInfos
				PackSuccessfulInfo succesfulDataset = new PackSuccessfulInfo();
				succesfulDataset.setIndex(String.valueOf(downDataSetCount));
				succesfulDataset.setItemID(dataSetInfo.getItemId());
				succesfulDataset.setItemRev(dataSetInfo.getRev());
				succesfulDataset.setItemOwner(dataSetInfo.getOwner());
				succesfulDataset.setDataset(dataSetInfo.getDatasetName());
				succesfulDataset.setRefFile(file.getName());
				successfulInfos.add(succesfulDataset);
			} else {
				writeLogFile(logFileName, "没有导出文件！");
			}
		} catch (Throwable e) {
			writeLogFile(logFileName, "文件导出时出现异常");
			String exceptionMessage = e.getMessage();
			writeLogFile(logFileName, exceptionMessage);
			writeLogFile(logFileName, " ");
			e.printStackTrace();
			if (downCount < 2) {
				file = getTCFile(tcFile, fileCurrentPath, fileName, dataSetInfo);
			} else {
				dataSetInfo.setReason(exceptionMessage);
				failDownInfos.add(dataSetInfo);
			}
		}
		return file;
	}

	/**
	 * checkAccessPrivilige:检查用户对给Component是否有权限
	 * @param @return 设定文件
	 * @return String 对象类型
	 * @throws
	 * @since CodingExample　Ver 1.1
	 */
	private boolean checkAccessPrivilige(TCComponentUser user, TCComponent comp, String accessName) throws TCException {
		TCAccessControlService accessService = ((TCSession) session).getTCAccessControlService();
		boolean returnboolean = accessService.checkUsersPrivilege(user, comp, accessName);
		return returnboolean;
	}

	private boolean isShowLog() {
		boolean isShowLog = false;
		TCPreferenceService preSer = session.getPreferenceService();
		String value = preSer.getString(4, isShowLogOption).trim();
		if (value.equalsIgnoreCase("true")) {
			isShowLog = true;
		}
		return isShowLog;
	}

	public void isDownReleased() {
		TCPreferenceService preSer = session.getPreferenceService();
		String type = preSer.getString(4, validTypeOption).trim();
		if (type.equalsIgnoreCase("released")) {
			isDownReleased = true;
		}
	}

	private String createFile(String filePath, String fileName) {
		System.out.println("路径：" + filePath + "/" + fileName);
		File file = new File(filePath + "/" + fileName);
		if (!file.exists()) {
			try {
				file.mkdir();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return file.getAbsolutePath();
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			System.out.println("run________________-");
			executeOperation();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
