/*
#=============================================================================
#																			   
#			copyright (c) 2009 Origin Enterprise Solution LTD.		   
#																			   
#=============================================================================
# File name: ImportFile.java
# File description: 										   	
#=============================================================================
#	Date		Name		    Action	Description of Change					   
#	2017-5-24     上午10:40:43    SZ   	Ini	                  初始化文件  										
#=============================================================================
 */
package cn.com.customization.imports.importfiles;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.com.customization.util.ShowMessageDialog;

import com.teamcenter.rac.aif.AbstractAIFUIApplication;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.TCAccessControlService;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentFolder;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentUser;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCProperty;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;

public class ImportFile {
	/**
	 * Creates a new instance of ImportFile.
	 */
	private AbstractAIFUIApplication	app;
	private TCSession					session;
	private TCComponent					selectedTarget;
	private boolean						isImportFolder;
	private ORProgressBarThread			progressbarthread	= null;
	private int							level				= 0;
	private boolean						isError				= false;
	private TCComponent parentRevision = null;
	private TCComponent targetRelComponent = null;
	//private boolean isPSEUDOFOLDER = false;
	private String strRelName = "";
	
	public ImportFile(AbstractAIFUIApplication app, boolean isImportFolder) {
		this.app = app;
		this.session = (TCSession) (app.getSession());
		this.isImportFolder = isImportFolder;
		GetCommonInfo.setNeedNum(0);
		GetCommonInfo.setFailNum(0);
		GetCommonInfo.setSuccessNum(0);
		getTargetComponent();
		session.setReadyStatus();
	}

	public ImportFile(AbstractAIFUIApplication app,TCComponent[] component){
		this.app = app;
		this.session = (TCSession) (app.getSession());
		parentRevision = component[0];
		targetRelComponent = component[1];
		GetCommonInfo.setNeedNum(0);
		GetCommonInfo.setFailNum(0);
		GetCommonInfo.setSuccessNum(0);
		submitDataset((TCComponentItemRevision)parentRevision);
		session.setReadyStatus();
	}
	
	/**
	 * getTargetComponent:得到用户所选的对象
	 * @param @return 设定文件
	 * @return String 对象类型
	 * @throws
	 * @since CodingExample　Ver 1.1
	 */
	private void getTargetComponent() {
		try {
			if (isImportFolder) {
				selectedTarget = new GetTargetComponent(app).getSelectedComponent();
				if(selectedTarget.getType().equals("PseudoFolder")){
					//isPSEUDOFOLDER = true;
					strRelName = selectedTarget.getProperty("property_name");
					AIFComponentContext[] context = selectedTarget.whereReferenced();
					selectedTarget = (TCComponent) context[0].getComponent();
				}
				
				if (selectedTarget != null) {
					boolean isCanRevise = false;
					try {
						isCanRevise = checkAccessPrivilige(session.getUser(), selectedTarget, "WRITE");
					}
					catch (TCException e) {
						e.printStackTrace();
					}
					if (isCanRevise) {
						executeImport(selectedTarget);
					} else {
						MessageBox.post(AIFUtility.getActiveDesktop().getShell(), "您对当前目录无修改权限！", "信息提示", MessageBox.INFORMATION);
					}
				}
			} else {
				importDatasetToRevision();
			}
		} catch (TCException e) {
			e.printStackTrace();
		}
	}

	/**
	 * importDatasetToRevision:导入数据集到版本
	 * */
	private void importDatasetToRevision(){
		boolean isReleased = false;
		selectedTarget = new GetTargetComponent(app).getItemRevision();
		if ((selectedTarget != null)) {
			TCComponentItemRevision itemRevision = (TCComponentItemRevision) selectedTarget;
			boolean isWritable = false;
			try {
				isWritable = checkAccessPrivilige(session.getUser(), itemRevision, "WRITE");
				String itemType = itemRevision.getItem().getProperty("object_type").trim();
				System.out.println("itemType==================" + itemType);
				
				TCComponent[] arrayOfTCComponent;
				try {
					TCProperty localTCProperty = itemRevision.getTCProperty("release_status_list");
					arrayOfTCComponent = localTCProperty.getReferenceValueArray();
					if (arrayOfTCComponent.length > 0) {
						isReleased = true;
						/*=============Added by liqz on 20110420 Begin 如果有写权限仍可以导入===============*/
						if(!isWritable){
							MessageBox.post(AIFUtility.getActiveDesktop().getShell(), "当前版本对象已经发布，你对它没有写权限，不能进行导入！", "信息提示", MessageBox.INFORMATION);
							return;
						}
						/*=============Added by liqz on 20110420 End 如果有写权限仍可以导入===============*/
					}
				}
				catch (TCException e) {
					e.printStackTrace();
				}
			}catch (TCException e2) {
				e2.printStackTrace();
			}

			if (!isReleased || isWritable) {
				boolean isCreateUser = false;
				try {
					String currentUser = session.getUser().getUserId();
					String createUser = itemRevision.getProperty("owning_user");
					createUser = (createUser.replace(" ", "")).substring(createUser.indexOf("("), createUser.length() - 2);
					if (currentUser.equalsIgnoreCase(createUser)) {
						isCreateUser = true;
					}
				}
				catch (TCException e1) {
					e1.printStackTrace();
				}
				boolean flagPriChild = false;
				try {
					flagPriChild = checkAccessPrivilige(session.getUser(), itemRevision, "IMPORT");
				}
				catch (TCException e) {
					e.printStackTrace();
				}
				
				if(!isWritable){
					MessageBox.post(AIFUtility.getActiveDesktop().getShell(), "你不具有该item版本的批量写权限！", "信息提示", MessageBox.INFORMATION);
					return;
				}
//				if ((!flagPriChild) || (!isCreateUser)) {
				if (!flagPriChild) {
					MessageBox.post(AIFUtility.getActiveDesktop().getShell(), "你不具有该item版本的批量导入权限！", "信息提示", MessageBox.INFORMATION);
					return;
				} else {
					executeImport(itemRevision);
				}
			}
		}
	}
	
	/**
	 * executeImport:实现导入
	 * @param @return 设定文件
	 * @return String 对象类型
	 * @throws
	 * @since CodingExample　Ver 1.1
	 */
	private void executeImport(final TCComponent component) {
		if (component != null) {
			try {
				if (isImportFolder) {
					List<String> filepaths = new GetChoosePath(app, new ArrayList<String>(), true).getChoosePath();
					if ((filepaths == null) || (filepaths.size() == 0)) { return; }
					progressbarthread = new ORProgressBarThread("数据集导入中.....", "数据导入中，请稍等...");
					progressbarthread.start();
					session.setStatus("正在导入...");
					for (int i = 0; i < filepaths.size(); i++) {
						if (!isError) {
//							importFolder(new File(filepaths.get(i)), (TCComponentFolder) selectedTarget, 0);
							importFolder(new File(filepaths.get(i)), selectedTarget, 0,strRelName);
						} else {
							break;
						}
					}
				} else {
					List<String> filterFileTypes = new GetAllOptionValue(app).getFileType();
					final List<String> filepaths = new GetChoosePath(app, filterFileTypes, false).getChoosePath();
					if ((filepaths == null) || (filepaths.size() == 0)) { return; }

					progressbarthread = new ORProgressBarThread("数据集导入中.....", "数据导入中，请稍等...");
					progressbarthread.start();
					session.setStatus("正在导入...");
					isError = new CreateDataSet(app, false, progressbarthread, null).getImportFile(filepaths, "no", selectedTarget,"");
				}
			}
			catch (Exception e) {
				e.printStackTrace();
			}
			finally {
				progressbarthread.setBool(true);
				session.setReadyStatus();
				int failNum = GetCommonInfo.getFailNum();
				int successNum = GetCommonInfo.getSuccessNum();
				int needNum = GetCommonInfo.getNeedNum();
				if (isError) {
					new ShowMessageDialog("信息提示！", "成功导入" + successNum + "个文件！", "");
				} else {
					/*============modified by liqz on 20110421 不限制导入级数 Begin=================*/
//					if (level > 2) {
//						MessageBox.post(AIFUtility.getActiveDesktop().getShell(), "文件夹超过3级限制，导入操作被中止！", "信息提示", MessageBox.INFORMATION);
//					}
					/*============modified by liqz on 20110421 不限制导入级数 End=================*/
					if (failNum == 0) {
						new ShowMessageDialog("信息提示！", "本次需导入" + needNum + "个文件,成功导入" + successNum + "个文件！", "");
					} else {
						new ShowMessageDialog("信息提示！", "本次需导入" + needNum + "个文件,成功导入" + successNum + "个文件", "未成功导入" + failNum + "个文件");
					}
				}
			}
		}
	}

//	private void importFolder(File file, TCComponentFolder currentFolder, int level) {
	private void importFolder(File file, TCComponent currentFolder, int level,String strRelName) {
		if (file == null) { return; }
		if (file.isDirectory()) {
			TCComponentFolder folder = new CreateFolder(session).createNewFolder(file.getName(), "");
			try {
				if(level == 0 && strRelName.length() > 0){
					currentFolder.add(strRelName, folder);
				}else{
					currentFolder.add("contents", folder);
				}
			}
			catch (TCException e) {
				e.printStackTrace();
			}
			File[] files = file.listFiles();
			List<String> fileList = new ArrayList<String>();
			List<File> dirList = new ArrayList<File>();
			for (int i = 0; i < files.length; i++) {
				File listFile = files[i];
				if (listFile.isFile()) {
					fileList.add(listFile.getAbsolutePath());
				} else {
					dirList.add(listFile);
				}
			}
			if ((fileList != null) && (fileList.size() > 0)) {
				isError = new CreateDataSet(app, true, progressbarthread, null).getImportFile(fileList, "no", folder,"");
				if (isError) { return; }
			}
			if ((dirList != null) && (dirList.size() > 0)) {
				level = level + 1;
				System.out.println("level========================" + level);
				if (this.level < level) {
					this.level = level;
				}
				/*============modified by liqz on 20110421 不限制导入级数 Begin=================*/
				for (int i = 0; i < dirList.size(); i++) {
					currentFolder = folder;
					if (!isError) {
//						importFolder(dirList.get(i), currentFolder, level);
						importFolder(dirList.get(i), currentFolder, level,strRelName);
					} else {
						return;
					}
				}
			}
		} else {
			List<String> fileList = new ArrayList<String>();
			fileList.add(file.getAbsolutePath());
			isError = new CreateDataSet(app, true, progressbarthread, null).getImportFile(fileList, "no", currentFolder,strRelName);
			if (isError) { return; }
		}
	}

	/**
	 * checkAccessPrivilige:检查是否有权限
	 * @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;
	}


	/**
	 * submitDataset:执行创建（导入）数据集
	 * */
	private void submitDataset(TCComponentItemRevision itemRevision){
		try{
			List<String> filterFileTypes = new GetAllOptionValue(app).getFileType();
			List<String> filepaths = new GetChoosePath(app, filterFileTypes, false).getChoosePath();
			if ((filepaths == null) || (filepaths.size() == 0)) { return; }
			progressbarthread = new ORProgressBarThread("提交评审附件中.....", "数据提交中，请稍等...");
			progressbarthread.start();
			session.setStatus("正在提交...");
			CreateDataSet objCreate = new CreateDataSet(app, false, progressbarthread, targetRelComponent);
			String strRelName = targetRelComponent.getProperty("property_name");
			objCreate.getSubmitFile(filepaths, itemRevision,strRelName);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			progressbarthread.setBool(true);
			session.setReadyStatus();
			int failNum = GetCommonInfo.getFailNum();
			int successNum = GetCommonInfo.getSuccessNum();
			int needNum = GetCommonInfo.getNeedNum();
			if (isError) {
				new ShowMessageDialog("信息提示！", "成功提交" + successNum + "个文件！", "");
			} else {
				if (failNum == 0) {
					new ShowMessageDialog("信息提示！", "本次需提交" + needNum + "个文件,成功提交" + successNum + "个文件！", "");
				} else {
					new ShowMessageDialog("信息提示！", "本次需提交" + needNum + "个文件,成功提交" + successNum + "个文件", "未成功导入" + failNum + "个文件");
				}
			}
		}
	}
}
