/*
#=======================================================================================================
#
#                   Copyright (c) 2007 Origin Enterprise Solution LTD.
#
#=======================================================================================================
# File description:  CreateDataSet.java
#=======================================================================================================
#	 Date	       time   	   Name	 	Action	   Description of Change
#	2011-1-18      下午04:57:58    tyl  	Ini	        	 初始化文件
#	2011-4-21		16:11	   liqz		Modify			文件个数限制由原来的200个改为500个
#	2012-2-28				   liqz	  	Modify			如果导入的是dwg文件，则将图纸属性同步到form中
#	2012-3-27				   liqz	  	Modify			屏蔽2012-2-28日修改的同步图纸的代码										   
#=======================================================================================================
 */
package cn.com.customization.imports.importfiles;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.customization.util.GetMessagePromptDialog;

import com.teamcenter.rac.aif.AbstractAIFUIApplication;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.commands.paste.PasteCommand;
import com.teamcenter.rac.kernel.NamedReferenceContext;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentDataset;
import com.teamcenter.rac.kernel.TCComponentDatasetDefinition;
import com.teamcenter.rac.kernel.TCComponentDatasetDefinitionType;
import com.teamcenter.rac.kernel.TCComponentDatasetType;
import com.teamcenter.rac.kernel.TCComponentFolder;
import com.teamcenter.rac.kernel.TCComponentForm;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.kernel.TCTypeService;
import com.teamcenter.rac.util.MessageBox;

public class CreateDataSet {
	private TCSession session;
	private ORProgressBarThread progressbarthread = null;
	private AbstractAIFUIApplication app;
	private boolean isHaveShowMessage = false;
	private int selectFileCount = 0;
	private int importFileCount = 0;
	private int failImportFileCount = 0;
	private boolean isImportFolder = false;
	private boolean isError = false;
	private Map<String, String> fileTypeList;
	private TCComponent targetRelComponent = null;

	public CreateDataSet(AbstractAIFUIApplication app, boolean isImportFolder, ORProgressBarThread progressbarthread, TCComponent targetRelComponent) {
		this.app = app;
		this.session = (TCSession) app.getSession();
		this.progressbarthread = progressbarthread;
		this.isImportFolder = isImportFolder;
		this.targetRelComponent = targetRelComponent;
		fileTypeList = new HashMap<String, String>();
		fileTypeList = new GetAllOptionValue(app).getFileTypeFromOption();
	}

	/**
	 * getImportFile:得到用户所选择的文件
	 * 
	 * @param @return 设定文件
	 * @return String 对象类型
	 * @throws
	 * @since CodingExample　Ver 1.1
	 */
//	public boolean getImportFile(List<String> filepath, String filter, TCComponent parentCom) {
	public boolean getImportFile(List<String> filepath, String filter, TCComponent parentCom,String strRelName) {
		List<String> filelist = filepath;
		selectFileCount = filelist.size();
		System.out.println("selectFileCount = "+selectFileCount);
		if (parentCom != null) {
			try {
				isError = false;
				if (filelist.size() > 0) {
					int importNum = GetCommonInfo.getSuccessNum();
					System.out.println("importNum = "+importNum);
					for (int i = 0; i < filelist.size(); i++) {
						if (importNum + importFileCount >= 500) {
							progressbarthread.setBool(true);
							session.setReadyStatus();
							isError = true;
							MessageBox.post(AIFUtility.getActiveDesktop().getShell(), "单次导入超过500个文件限制，程序被中止！", "信息提示", MessageBox.INFORMATION);
							return isError;
						}
						if (!isError) {
							isError = false;
							createDataSet(filelist.get(i), parentCom,strRelName);
						} else {
							progressbarthread.setBool(true);
							session.setReadyStatus();
							return isError;
						}
					}
					progressbarthread.setBool(true);
					session.setReadyStatus();
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				failImportFileCount = selectFileCount - importFileCount;
				GetCommonInfo.setNeedNum(selectFileCount + GetCommonInfo.getNeedNum());
				GetCommonInfo.setFailNum(failImportFileCount + GetCommonInfo.getFailNum());
				GetCommonInfo.setSuccessNum(importFileCount + GetCommonInfo.getSuccessNum());
			}
		}
		return isError;
	}

	/**
	 * createDataSet:将数据集导入到相应的版本下
	 * 
	 * @param @return 设定文件
	 * @return String 对象类型
	 * @throws
	 * @since CodingExample　Ver 1.1
	 */
	private void createDataSet(String filePath, TCComponent parentCom,String strRelName) {
		File file = new File(filePath);
		int equalsCount = 0;
		boolean isrename = false;
		if (file.isFile()) {
			String name = file.getName();
			// String strDatasetName = name.substring(0, name.lastIndexOf("."));
			String strDatasetName = name;
			byte[] bytestr = strDatasetName.replace(" ", "").getBytes();
			// 数据集名称过长，取前128字节
			if (bytestr.length > 128) {
				strDatasetName = new String(bytestr, 0, 128);
			}
			String suffix = name.substring(name.lastIndexOf(".") + 1);
			suffix = suffix.toLowerCase();

//			List<String> getAllDataSetNames = new GetAllDataSetNames().getDatasetNames(parentCom);
			List<String> getAllDataSetNames = null;
			if(suffix.equalsIgnoreCase("jt") || suffix.equalsIgnoreCase("jpg")){
				getAllDataSetNames = new GetAllDataSetNames().getDatasetNames(parentCom,"IMAN_Rendering");
			}else{
				getAllDataSetNames = new GetAllDataSetNames().getDatasetNames(parentCom,strRelName);
			}
			if ((getAllDataSetNames != null) && (getAllDataSetNames.size() > 0)) {
				for (int i = 0; i < getAllDataSetNames.size(); i++) {
					if (getAllDataSetNames.get(i).equals(strDatasetName)) {
						if (equalsCount == 0) {
							++equalsCount;
						} else {
							++equalsCount;
						}
					}
				}
			}
			if ((equalsCount == 0) || (isHaveShowMessage)) {
				if (isImportFolder) {
//					if (parentCom instanceof TCComponentFolder) {
//						addDataSetToFolder((TCComponentFolder) parentCom, strDatasetName, suffix, filePath);
					addDataSetToFolder(parentCom, strDatasetName, suffix, filePath,strRelName);
//					}
				} else {
					if (parentCom instanceof TCComponentItemRevision) {
						if(suffix.equalsIgnoreCase("jt") || suffix.equalsIgnoreCase("jpg")){
							addDataSetToItemRevision((TCComponentItemRevision) parentCom, strDatasetName, suffix, filePath,fileTypeList,"IMAN_Rendering");
						}else{
							addDataSetToItemRevision((TCComponentItemRevision) parentCom, strDatasetName, suffix, filePath,fileTypeList,"IMAN_specification");
						}
					}
				}
				// 将重命名后的文件删除
				if (isrename) {
					File renamedFile = new File(filePath);
					{
						if (renamedFile.exists()) {
							renamedFile.delete();
						}
					}
				}
			} else {
				isHaveShowMessage = false;
				if (equalsCount > 0) {
					progressbarthread.setBool(true);
					session.setReadyStatus();
					int value = new GetMessagePromptDialog("信息提示", "存在相同名称的数据集【" + strDatasetName + "】，是否按追加方式导入?").getValue();
					isHaveShowMessage = true;
					if (value == 0) {
						progressbarthread = new ORProgressBarThread("数据集导入中.....", "数据导入中，请稍等...");
						progressbarthread.start();
						session.setStatus("正在导入...");
						if (isImportFolder) {
							if (parentCom instanceof TCComponentFolder) {
								addDataSetToFolder((TCComponentFolder) parentCom, strDatasetName, suffix, filePath,strRelName);
							}
						} else {
							if (parentCom instanceof TCComponentItemRevision) {
								if(suffix.equalsIgnoreCase("jt") || suffix.equalsIgnoreCase("jpg")){
									addDataSetToItemRevision((TCComponentItemRevision) parentCom, strDatasetName, suffix, filePath,fileTypeList,"IMAN_Rendering");
								}else{
									addDataSetToItemRevision((TCComponentItemRevision) parentCom, strDatasetName, suffix, filePath,fileTypeList,"IMAN_specification");
								}
							}
						}
						if (isrename) {
							File renamedFile = new File(filePath);
							{
								if (renamedFile.exists()) {
									renamedFile.delete();
								}
							}
						}
					} else {
						isError = true;
						progressbarthread.setBool(true);
						session.setReadyStatus();
						return;
					}
				}
			}
		}
	}

	/**
	 * createDatasetToRelation:在选择的关系文件夹下创建数据集
	 * @param String 文件路径
	 * @param TCComponentItemRevision 关系文件夹所在的 item Revision
	 * @param String 关系文件夹名称
	 * */
	private void createDatasetToRelation(String filePath,TCComponentItemRevision itemRev,String strRelName){
		try {
			File file = new File(filePath);
			if (file.isFile()) {
				String name = file.getName();
				String suffix = name.substring(name.lastIndexOf(".") + 1);
				suffix = suffix.toLowerCase();
				
				if(suffix.equalsIgnoreCase("dwg")){
					fileTypeList.put(suffix,"DWG");
				}
				
				String strTaskName = "";
				TCComponent[] processList = itemRev.getReferenceListProperty("process_stage_list");
				if(processList != null){
					if(processList.length >= 2){
						TCComponent taskcomp = processList[processList.length -1];
						strTaskName = taskcomp.getProperty("object_name");
					}
				}
				
				System.out.println("createDatasetToRelation:: strTaskName = " + strTaskName);
				SimpleDateFormat  df  =   new   SimpleDateFormat( "yyyyMMdd HH:mm"); 
				String strDatasetName = strTaskName + "_" + session.getUser().getProperty("user_name") +"_" + df.format(new  Date());
				addDataSetToItemRevision(itemRev, strDatasetName, suffix, filePath,fileTypeList,strRelName);
			}
		} catch (TCException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * addDataSet:将数据集导入到相应的版本下
	 * 
	 * @param @return 设定文件
	 * @return String 对象类型
	 * @throws
	 * @since CodingExample　Ver 1.1
	 */
	private void addDataSetToItemRevision(TCComponentItemRevision itemRevision, String strDatasetName, String suffix, String filePath,Map<String, String> fileTypeList,String strRel) {
		try {
			TCTypeService service = session.getTypeService();
			if (service != null) {
				TCComponentDatasetType datasetType = (TCComponentDatasetType) service.getTypeComponent("Dataset");
//				MessageBox.post("suffix="+suffix, "提示", MessageBox.INFORMATION);
//				MessageBox.post("fileTypeList.get(suffix)="+fileTypeList.get(suffix), "提示", MessageBox.INFORMATION);
				System.out.println("suffix="+suffix);
//				System.out.println("fileTypeList.get(suffix)="+fileTypeList.get(suffix));
				TCComponentDataset tcd = datasetType.create(strDatasetName, "description", fileTypeList.get(suffix));
				String[] arrTargetName = { filePath };

				String[] dataset = getFileType(datasetType, fileTypeList.get(suffix));
				tcd.setFiles(arrTargetName, dataset);
				if(targetRelComponent != null){
					PasteCommand pastecommand = new PasteCommand(new TCComponent[] {tcd},new TCComponent[] {targetRelComponent},app.getDesktop());
					try {
						pastecommand.executeModal();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}else{
					itemRevision.add(strRel, tcd);
				}
				
				/*============20120327  liqz 同步速度慢，现场要求屏蔽掉===========*/
//				if(suffix.equalsIgnoreCase("dwg")){
//					String[] arrProp = getPropertyFromOption(itemRevision);
//					getDWGProperty(itemRevision, arrProp, filePath);
//				}
				/*============20120327  liqz 同步速度慢，现场要求屏蔽掉===========*/
				importFileCount++;
			}
		} catch (TCException e) {
			progressbarthread.setBool(true);
			session.setReadyStatus();
			if(e.getMessage().contains("属性 view 是不可修改的")){
				MessageBox.post("属性 view 是不可修改的！，请选择其他关系文件夹执行操作！","提示",MessageBox.WARNING);
			}else{
				int value = new GetMessagePromptDialog("信息提示", "不可识别数据集类型的导入文件【" + filePath + "】", "是否忽略?").getValue();
				if (value == 0) {
					progressbarthread = new ORProgressBarThread("数据集导入中.....", "数据导入中，请稍等...");
					progressbarthread.start();
					session.setStatus("正在导入...");
				} else {
					isError = true;
				}
				e.printStackTrace();
			}
		}
	}

//	private void addDataSetToFolder(TCComponentFolder folder, String strDatasetName, String suffix, String filePath) {
	private void addDataSetToFolder(TCComponent folder, String strDatasetName, String suffix, String filePath,String strRelName) {
		try {
			Map<String, String> fileTypeList = new HashMap<String, String>();
			fileTypeList = new GetAllOptionValue(app).getFileTypeFromOption();
			TCTypeService service = session.getTypeService();
			if (service != null) {
				TCComponentDatasetType datasetType = (TCComponentDatasetType) service.getTypeComponent("Dataset");
				TCComponentDataset tcd = datasetType.create(strDatasetName, "description", fileTypeList.get(suffix));
				String[] arrTargetName = { filePath };
				// String[] dataset = { getFileType(datasetType, fileTypeList.get(suffix)) };
				String[] dataset = getFileType(datasetType, fileTypeList.get(suffix));
				tcd.setFiles(arrTargetName, dataset);
				
				if(strRelName.length() > 0){
					folder.add(strRelName, tcd);
				}else{
					folder.add("contents", tcd);
				}
				importFileCount++;
			}
		} catch (TCException e) {
			progressbarthread.setBool(true);
			session.setReadyStatus();
			int value = new GetMessagePromptDialog("信息提示", "不可识别数据集类型的导入文件【" + filePath + "】", "是否忽略?").getValue();
			if (value == 0) {
				progressbarthread = new ORProgressBarThread("数据集导入中.....", "数据导入中，请稍等...");
				progressbarthread.start();
				session.setStatus("正在导入...");
			} else {
				isError = true;
			}
			e.printStackTrace();
		}
	}

	/**
	 * getFileType:将数据集相应的引用文件的类型
	 * 
	 * @param @return 设定文件
	 * @return String 对象类型
	 * @throws
	 * @since CodingExample　Ver 1.1
	 */
	private String[] getFileType(TCComponentDatasetType datasetType, String tctype) {
		List<String> typeList = new ArrayList<String>();
		if (tctype.equalsIgnoreCase("CATPart")) {
			typeList.add("catpart");
		} else if (tctype.equalsIgnoreCase("CATDrawing")) {
			typeList.add("catdrawing");
		} else if (tctype.equalsIgnoreCase("CATProduct")) {
			typeList.add("catproduct");
		} else if(tctype.equalsIgnoreCase("MSWordX") || tctype.equalsIgnoreCase("MSWord")){
			typeList.add("word");
		}else if(tctype.equalsIgnoreCase("MSExcelX") || tctype.equalsIgnoreCase("MSExcel")){
			typeList.add("excel");
		}else if(tctype.equalsIgnoreCase("ACADDWG")){
			typeList.add("DWG");
		}else if(tctype.equalsIgnoreCase("DirectModel")){
			typeList.add("JTPART");
		}else {
			try {
				TCTypeService service = session.getTypeService();
				TCComponentDatasetDefinitionType dsdefType;
				dsdefType = (TCComponentDatasetDefinitionType) service.getTypeComponent("DatasetType");
				TCComponentDatasetDefinition definition = dsdefType.find(tctype);
				NamedReferenceContext[] contexts = definition.getNamedReferenceContexts();

				if ((contexts != null) && (contexts.length > 0)) {
					for (int m = 0; m < contexts.length; m++) {
						//System.out.println("contexts[m].getNamedReference()="+contexts[m].getNamedReference());
						//MessageBox.post("contexts[m]="+contexts[m].getNamedReference(), "提示", MessageBox.INFORMATION);
						typeList.add(contexts[m].getNamedReference());
					}
				}
			} catch (TCException e) {
				progressbarthread.setBool(true);
				session.setReadyStatus();
				e.printStackTrace();
			}
		}
		String[] types = new String[typeList.size()];
		for (int i = 0; i < typeList.size(); i++) {
			types[i] = (String) typeList.get(i);
			System.out.println("types[i]="+types[i]);
		}
		//MessageBox.post("types="+types.toString(), "提示", MessageBox.INFORMATION);
		System.out.println("types="+types.toString());
		return types;
	}
	
	/**
	 * getSubmitFile:根据文件列表导入数据到item Revision的指定关系下
	 * @param List<String> 文件列表的 List
	 * @param TCComponentItemRevision  关系对象所在的item Revision对象 
	 * @param String 关系文件夹名称
	 * */
	public boolean getSubmitFile(List<String> filepaths ,TCComponentItemRevision revision,String strRelName){
		List<String> filelist = filepaths;
		selectFileCount = filelist.size();
		if (revision != null) {
			try {
				isError = false;
				if (filelist.size() > 0) {
					int importNum = GetCommonInfo.getSuccessNum();
					for (int i = 0; i < filelist.size(); i++) {
						if (importNum + importFileCount >= 500) {
							progressbarthread.setBool(true);
							session.setReadyStatus();
							isError = true;
							MessageBox.post(AIFUtility.getActiveDesktop().getShell(), "单次导入超过500个文件限制，程序被中止！", "信息提示", MessageBox.INFORMATION);
							return isError;
						}
						if (!isError) {
							isError = false;
							createDatasetToRelation(filelist.get(i),revision,strRelName);
						} else {
							progressbarthread.setBool(true);
							session.setReadyStatus();
							return isError;
						}
					}
					progressbarthread.setBool(true);
					session.setReadyStatus();
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				failImportFileCount = selectFileCount - importFileCount;
				GetCommonInfo.setNeedNum(selectFileCount + GetCommonInfo.getNeedNum());
				GetCommonInfo.setFailNum(failImportFileCount + GetCommonInfo.getFailNum());
				GetCommonInfo.setSuccessNum(importFileCount + GetCommonInfo.getSuccessNum());
			}
		}
		return isError;
	}
	
	/**
	 * getPropertyFromOption:根据当前选定的Item类型，从首选项获取该类型需要同步的属性
	 * @param TCComponentItemRevision itemRevision
	 * @return String[] revision和form的属性对应关系数组
	 * */
	@SuppressWarnings("unused")
	private String[] getPropertyFromOption(TCComponentItemRevision itemRevision){
		String[] arrOption = itemRevision.getSession().getPreferenceService().getStringValues("Dacastal_AutoCAD_Map");
		if(arrOption == null || arrOption.length == 0){
			return null;
		}
		
		String[] arrProp = new String[2];
		StringBuffer strRevisionProp  = new StringBuffer();
		StringBuffer strFormProp  = new StringBuffer();
		
		String strType = itemRevision.getType();
		for(int i = 0; i < arrOption.length ;i++){
			String strTemp = arrOption[i]; 
			if(strTemp.startsWith(strType)){
				int index = strTemp.indexOf(".");
				if(index > 0 ){
					String strOptionType = strTemp.substring(0,index);
					String value = strTemp.substring(index + 1);
					
					if(strOptionType.equalsIgnoreCase(strType)){
						if(strRevisionProp.length() == 0){
							strRevisionProp.append(value);	
						}else{
							strRevisionProp.append(",").append(value);
						}
					}else{
						if(strFormProp.length() == 0){
							strFormProp.append(value);
						}else{
							strFormProp.append(",").append(value);
						}
					}
				}
			}
		}
		
		System.out.println("strRevisionProp = " + strRevisionProp);
		System.out.println("strFormProp = " + strFormProp);
		
		arrProp[0] = strRevisionProp.toString();
		arrProp[1] = strFormProp.toString();
		return arrProp;
	}
	
	/**
	 * getDWGProperty::根据属性名对应关系获取DWG图纸的属性值
	 * @param TCComponentItemRevision revision
	 * @param String[] revision和form的属性对应关系数组
	 * @param strFilePath DWG文件路径
	 * */
	@SuppressWarnings("unused")
	private void getDWGProperty(TCComponentItemRevision revision,String[] pArrProp,String strFilePath){
		if(pArrProp == null){
			return;
		}
		HashMap<String,String> mapRevProp = new HashMap<String,String>();
		HashMap<String,String> mapRevFormProp = new HashMap<String,String>();
		
		Runtime rn = Runtime.getRuntime();
		Process p = null;
		try {
			String str = System.getenv("TPR");
			if (str.endsWith("\\")) {
				str = str + "plugins\\";
			} else {
				str = str + "\\plugins\\";
			}
			str = "\"" + str + "DxfExportExample.exe\"" + " \"" + strFilePath + "\" \"" + pArrProp[0] + "\" \"" + pArrProp[1] + "\"";
			System.out.println("getDWGProperty:: str=" + str);
			p = rn.exec("cmd /c  start exit && " + str);
			BufferedReader inputBufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
			BufferedReader errorinputBufferedReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
			String line = null;
			String errorline = null;
			
			while ((line = inputBufferedReader.readLine()) != null) {
				System.out.println("从exe返回属性名和值: line = " + line);
				if(line.contains(":")){
					String[] arrType = line.split(":");
					if(arrType[0].equalsIgnoreCase("ItemRevision")){
						if(arrType[1].contains(";")){
							String[] arrRevPropValue = arrType[1].split(";");
							for(int i = 0 ; i < arrRevPropValue.length;i++){
								String[] temp = arrRevPropValue[i].split("="); 
								if(temp[0].equalsIgnoreCase("item_revision_id") || temp[0].equalsIgnoreCase("item_id")){
									continue;
								}
								if(temp.length == 2){
									mapRevProp.put(temp[0],temp[1]);	
								}else{
									mapRevProp.put(temp[0],"");
								}	
							}
						}else{
							String[] temp = arrType[1].split("=");
							if(temp[0].equalsIgnoreCase("item_revision_id") || temp[0].equalsIgnoreCase("item_id")){
								continue;
							}
							if(temp.length == 2){
								mapRevProp.put(temp[0],temp[1]);	
							}else{
								mapRevProp.put(temp[0],"");
							}
						}
					}else if(arrType[0].equalsIgnoreCase("ItemRevision Master")){
						if(arrType[1].contains(";")){
							String[] arrRevFormPropValue = arrType[1].split(";");
							for(int i = 0 ; i < arrRevFormPropValue.length;i++){
								String[] temp = arrRevFormPropValue[i].split("="); 
								if(temp.length == 2){
									mapRevFormProp.put(temp[0],temp[1]);	
								}else{
									mapRevFormProp.put(temp[0],"");
								}
							}
						}else{
							String[] temp = arrType[1].split("=");
							if(temp.length == 2){
								mapRevFormProp.put(temp[0],temp[1]);	
							}else{
								mapRevFormProp.put(temp[0],"");
							}
						}
					}
				}
			}
			while ((errorline = errorinputBufferedReader.readLine()) != null) {
				System.out.println(errorline);
			}
			if (errorline != null) {
				System.out.println("error occur...");
				p.destroy();
			}
		//	p.waitFor();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("Error to run the exe");
		}

		try {
			revision.setProperties(mapRevProp);
			TCComponent tccomponent = revision.getRelatedComponent("IMAN_master_form_rev");
			if(tccomponent instanceof TCComponentForm){
				TCComponentForm form = (TCComponentForm) tccomponent;
				form.setProperties(mapRevFormProp);
			}
		} catch (TCException e) {
			e.printStackTrace();
		}
	}
}
