package com.teamcenter.rac.kernel;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.kernel.ics.ICSAdminClass;
import com.teamcenter.rac.kernel.ics.ICSAdminClassAttribute;
import com.teamcenter.rac.kernel.ics.ICSKeyLov;
import com.teamcenter.rac.kernel.ics.ICSProperty;
import com.teamcenter.rac.util.FileUtility;
import com.teamcenter.rac.util.MessageBox;

/**
 * 此类继承系统InterfaceDatasetAction类，用于重写preProcess方法在打开 数据集 时前操作。
 * 
 * @author hubing
 * @version 1.0, 2015-01-6
 */

public class OpenDatasetSignoff implements InterfaceDatasetAction {
	private boolean isTE = false;

	// 关闭数据集的时候触发，我们可以通过此方法实现从数据集的命名引用文件关联属性到我们的表单或者版本等
	@Override
	public boolean postProcess(TCComponentDataset arg0, String arg1, int arg2) {

		System.out.println("关闭数据集出发操作" + arg1 + "/" + arg2);
		if (arg0 != null) {
			if (arg0.getType().equals("LD6_CAD2")) {
				// 关闭数据集的时候也更改注册表
				openCad();
			}
		}
		return false;
	}

	public StringBuffer sb;

	@SuppressWarnings("deprecation")
	@Override
	public int preProcess(TCComponentDataset tccomponentdataset, AEShell arg1, int arg2) {
		isTE = false;
		sb = new StringBuffer();
		System.out.println("打开数据集");
		TCPreferenceService tcp = tccomponentdataset.getSession().getPreferenceService();
		try {
			TCComponentItemRevision tempRev = (TCComponentItemRevision) tccomponentdataset
					.getReferenceProperty("item_revision");// 获得当前数据集所在版本对象
			if (tempRev == null) {
				return 0;
			}
			tempRev.refresh();

			// SB处理
			if (tempRev != null) {
				String type = tccomponentdataset.getType();
				if (type.equals("MSExcel") || type.equals("MSExcelX") || type.equals("MSWord")
						|| type.equals("MSWordX")) {
					String tempType = tempRev.getType();
					System.out.println("tempType======>" + tempType);
					String[] types = tcp.getStringArray(TCPreferenceService.TC_preference_site,
							tempType + "_AutoSignAttr");
					if (types == null || types.length < 2) {
						return 0;
					}

					boolean isExist = false;
					String localUid = tccomponentdataset.getUid();

					String[] gxList = types[0].split(",");
					main2: for (int j = 0; j < gxList.length; j++) {
						TCComponent[] relatedComponents = tempRev.getRelatedComponents(gxList[j]);
						for (int i = 0; i < relatedComponents.length; i++) {
							TCComponent tcComponent = relatedComponents[i];
							if (tcComponent instanceof TCComponentDataset && tcComponent.getUid().equals(localUid)) {
								isExist = true;
								System.out.println("关系下存在该数据集");
								break main2;
							}
						}
					}
					if (!isExist) {
						System.out.println("关系下不存在该数据集，退出");
						return 0;
					}

					StringBuffer infoSB = new StringBuffer();
					for (int i = 1; i < types.length; i++) {
						String[] prop = types[i].split("=");
						if (prop == null || prop.length != 2) {
							continue;
						}

						System.out.println("prop ==》 " + prop[0] + " || " + prop[1]);

						String value = "";
						if (prop[0].startsWith("@")) {
							// "="左边的以"@"开始,以")"结尾
							System.out.println("以@开头");
							// ([CMImplements#SB6_ECRLRevision#CMImplements#SB6_PRLRevision].Item.item_id|[CMImplements#SB6_PRLRevision].Item.item_id)=问题报告编号
							String[] gxArrays = prop[0].substring(1,prop[0].length()).split("\\|");
							System.out.println("gxArrays ==》 " + Arrays.toString(gxArrays));
							for (String singleGx : gxArrays) {
								String multipleValues = getMultipleValues(new TCComponentItemRevision[] { tempRev },
										singleGx);
								value += multipleValues;
							}
							if (value != null && value.length() > 0) {
								value = value.substring(0, value.length() - 1);
							}
						} else if (prop[0].startsWith("[")) {
							value = getMultipleValues(new TCComponentItemRevision[] { tempRev }, prop[0]);
							if (value != null && value.length() > 0) {
								value = value.substring(0, value.length() - 1);
							}
						} else {
							String[] relations = prop[0].split("\\.");
							if (relations != null && relations.length == 2) {
								value = getSingleValue(tempRev, relations[0], relations[1]);
							}
						}

						System.out.println("finalValue : " + value);

						if (prop[1].startsWith("(") && prop[1].endsWith(")")) {
							prop[1] = prop[1].substring(1, prop[1].length() - 1);
							System.out.println("存在lov下拉属性，值为：" + value);
							String[] selections = prop[1].split(",");
							for (int j = 0; j < selections.length; j++) {
								String[] values = selections[j].split("#");
								if (values != null && values.length == 2 && values[1].equals(value)) {
									System.out.println("√");
									prop[1] = values[0];
									value = "√";
									break;
								}
							}
						}

						if (value != null) {
							infoSB.append(prop[1]).append("=").append(value).append("|");
						}
					}

					String filePath = System.getenv("TEMP") + "\\project.txt";
					System.out.println("filePath = " + filePath);
					deleteFileIfExists(filePath);
					if (infoSB.toString().endsWith("|")) {
						try {

							FileOutputStream writerStream = new FileOutputStream(filePath);
							BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(writerStream));
							bw.write(infoSB.toString().substring(0, infoSB.toString().lastIndexOf("|")));
							bw.close();
							writerStream.close();

							System.out.println(infoSB.toString().substring(0, infoSB.toString().lastIndexOf("|")));
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return 0;
	}

	public String getMultipleValues(TCComponentItemRevision[] targetRevs, String singleGx) throws Exception {
		// singleGx =
		// "[CMImplements#SB6_ECRLRevision-SB6_RRLRevision#CMImplements#SB6_PRLRevision].Item.item_id"
		String[] relations = singleGx.split("\\.");

		StringBuffer values = new StringBuffer();
		if (relations.length == 3 && relations[0].startsWith("[") && relations[0].endsWith("]")) {
			String[] tempRelation = relations[0].substring(1, relations[0].length() - 1).split("#");
			
			for (int j = 0; j < tempRelation.length; j++) {
				String relation = tempRelation[j];
				String[] types = tempRelation[++j].split("-");
				System.out.println("当前关系类型: " + relation);
				System.out.println("当前关系下需要判断的类型有: " + Arrays.toString(types));
				
				for (TCComponentItemRevision targetRev : targetRevs) {
					targetRevs = getTargetRevs(targetRev, relation, types);
				}
			}

			for (TCComponentItemRevision targetRev : targetRevs) {
				String singleValue = getSingleValue(targetRev, relations[1], relations[2]);
				values.append(singleValue);
				values.append(";");
			}
		}

		return values.toString();
	}

	public TCComponentItemRevision[] getTargetRevs(TCComponent component, String relation, String[] targetType)
			throws Exception {
		TCComponentItemRevision rev = null;
		if (component instanceof TCComponentItem) {
			rev = ((TCComponentItem) component).getLatestItemRevision();
		} else if (component instanceof TCComponentItemRevision) {
			rev = (TCComponentItemRevision) component;
		}
		
		if(rev == null) {
			throw new Exception("rev is null");
		}
		TCComponent[] relatedComponents = rev.getRelatedComponents(relation);
		System.out.println("当前关系下存在该类型的个数: " + relatedComponents.length);
		List<TCComponentItemRevision> revList = new ArrayList<TCComponentItemRevision>();
		for (int i = 0; i < relatedComponents.length; i++) {
			String gxComponentType = relatedComponents[i].getStringProperty("object_type");
			System.out.println("当前关系下的类型 " + gxComponentType);
			for (int j = 0; j < targetType.length; j++) {
				if (gxComponentType.equals(targetType[j])) {
					if (gxComponentType.endsWith("Revision")) {
						revList.add((TCComponentItemRevision) relatedComponents[i]);
					} else {
						revList.add(((TCComponentItem) relatedComponents[i]).getLatestItemRevision());
					}
					break;
				}
			}
		}

		return revList.stream().toArray(TCComponentItemRevision[]::new);
	}

	public String getSingleValue(TCComponentItemRevision targetRev, String type, String prop) throws TCException {
		TCComponentItem item = targetRev.getItem();
		TCComponent revForm = targetRev.getRelatedComponent("IMAN_master_form_rev");
		String value = "";
		switch (type.toUpperCase()) {
		case "ITEM":
			value = hx_GetProp(item, prop);
			System.out.println("prop = " + prop + " || value = " + value);
			break;
		case "REV":
			value = hx_GetProp(targetRev, prop);
			System.out.println("prop = " + prop + " || value = " + value);
			break;
		case "FORM":
			value = hx_GetProp(revForm, prop);
			System.out.println("prop = " + prop + " || value = " + value);
			break;
		default:
			break;
		}
		return enhancedFormat(value);
	}

	public static String enhancedFormat(String input) {
		try {
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-d HH:mm");
			LocalDateTime.parse(input, formatter);
			return input.split(" ")[0].replace("-", ".");
		} catch (DateTimeParseException e) {
			return input;
		}
	}

	public static void deleteFileIfExists(String filePath) {
		File file = new File(filePath);
		if (file.exists()) {
			if (file.delete()) {
				System.out.println("文件已成功删除: " + filePath);
			} else {
				System.out.println("无法删除文件: " + filePath);
			}
		} else {
			System.out.println("文件不存在，无需处理: " + filePath);
		}
	}

	public static void runWsf(String wsfPath, String[] paras) throws Exception {
		ArrayList<String> cmdVector = new ArrayList<>();
		cmdVector.add("cscript");
		cmdVector.add(wsfPath);
		for (String para : paras) {
			cmdVector.add(para);
		}
		StringBuilder builder = new StringBuilder("wscript ").append(wsfPath).append(" ").append(paras[0]).append(" ")
				.append(paras[1]);
		System.out.println(builder.toString());
		String[] cmd = (String[]) cmdVector.toArray(new String[cmdVector.size()]);
		Process process = Runtime.getRuntime().exec(cmd);
		process.waitFor();
	}

	/**
	 * 处理万丰的数据集打开前操作
	 * 
	 * @param caxaDataset
	 * @throws TCException
	 */
	public void wf_SetCAXAFile(TCComponentDataset caxaDataset, TCPreferenceService tcp) throws TCException {
		StringBuffer infoSB = new StringBuffer();
		TCComponentItemRevision rev = null;
		TCComponentItem item = null;
		TCComponentForm revForm = null;
		TCComponentForm itemForm = null;
		TCComponentProject project = null;
		String datasetName = null;
		String[] vals = null;
		if (caxaDataset == null) {
			return;
		}
		TCComponentTcFile[] tcFiles = caxaDataset.getTcFiles();
		// File file = null;
		if (tcFiles != null && tcFiles.length != 0) {

			datasetName = tcFiles[0].getStringProperty("object_string");
		}
		System.out.println(" datasetName =" + datasetName);
		// = caxaDataset.getStringProperty("object_name");
		rev = (TCComponentItemRevision) caxaDataset.getReferenceProperty("item_revision");// 获得当前数据集所在版本对象

		if (rev == null) {
			return;
		}
		revForm = (TCComponentForm) (rev.getReferenceListProperty("IMAN_master_form_rev"))[0];
		item = rev.getItem();
		TCComponent[] projects = null;
		TCComponent[] tcs = null;
		TCComponent[] tasks = null;
		AIFComponentContext[] whereReferenced = item.whereReferenced();
		for (AIFComponentContext aifComponentContext : whereReferenced) {
			InterfaceAIFComponent component = aifComponentContext.getComponent();
			if (component instanceof TCComponentFolder) {
				TCComponentFolder targetComp = (TCComponentFolder) component;
				try {
					tcs = targetComp.getTCProperty("fnd0StartedWorkflowTasks").getReferenceValueArray();
					if (tcs != null && tcs.length > 0) {

						tasks = tcs[0].getTCProperty("fnd0RootScheduleTask").getReferenceValueArray();
					} else {
						// MessageBox.post("该文件夹没有走过流程！","提示",MessageBox.INFORMATION);
					}
					if (tasks != null && tasks.length > 0) {
						TCComponent schedule = tasks[0].getTCProperty("schedule_tag").getReferenceValue();
						projects = schedule.getTCProperty("project_list").getReferenceValueArray();
					} else {
						// MessageBox.post("没有时间表任务！","提示",MessageBox.INFORMATION);
					}
				} catch (TCException e) {
					e.printStackTrace();
				}
			}
		}
		// TCComponent[] projects = rev.getReferenceListProperty("project_list");
		if (projects != null && projects.length > 0) {
			project = (TCComponentProject) projects[0];
		}

		String[] refValues = null;

		refValues = tcp.getStringArray(TCPreferenceService.TC_preference_site, "WFSXYSMapping");

		if (refValues == null || refValues.length == 0) {
			// MessageBox.post("首选项配置错误,请联系管理员!!!!", "错误", MessageBox.ERROR);
			System.out.println("首选项配置错误,请联系管理员!!!!");
			return;
		}
		for (String refValue : refValues) {
			String[] valueS = refValue.split("=");
			String value = null;
			if (valueS == null || valueS.length != 2) {
				continue;
			}
			String[] propNameS = valueS[1].split("\\.");
			if (propNameS == null || propNameS.length != 2) {
				continue;
			}
			switch (propNameS[0].toUpperCase()) {
			case "ITEM":
				value = hx_GetProp(item, propNameS[1]);
				break;
			case "REV":
				value = hx_GetProp(rev, propNameS[1]);
				break;
			case "REVMASTER":
				value = hx_GetProp(revForm, propNameS[1]);
				break;
			case "PROJECT":
				value = hx_GetProp(project, propNameS[1]);
				break;
			case "CLASS":
				value = hx_GetPropClass(rev, propNameS[1]);
				break;
			case "ITEMMASTER":
				break;
			default:
				break;

			}
			if ("wf2_ctsgnrDpt".equals(propNameS[1]) || "wf2_ctsgnr".equals(propNameS[1])
					|| "wf2_ctsgnrDate".equals(propNameS[1]) || "wf2_ctsgnrIdea".equals(propNameS[1])
					|| "wf2_ctsgnrDpt_1".equals(propNameS[1]) || "wf2_ctsgnr_1".equals(propNameS[1])
					|| "wf2_ctsgnrDate_1".equals(propNameS[1]) || "wf2_ctsgnrIdea_1".equals(propNameS[1])) {
				System.out.println("11111111111111111111" + value);
				if (value == null) {
					continue;
				}
				if (value.contains("$")) {
					System.out.println("进行分割");
					vals = value.split("\\$");
				} else {
					vals = new String[] { value };
				}

				for (int i = 0; i < vals.length; i++) {
					String val = valueS[0] + (i + 1);
					System.out.println("val==============" + val);
					System.out.println("vals[" + i + "]=================" + vals[i]);
					if ("wf2_ctsgnrDpt".equals(propNameS[1]) || "wf2_ctsgnrDpt_1".equals(propNameS[1])) {
						String[] values = vals[i].split("\\.");
						if (2 < values.length && values.length <= 3) {
							vals[i] = values[values.length - 3];
						} else if (values.length > 3) {
							vals[i] = values[values.length - 3];
						} else if (values.length == 2) {
							vals[i] = values[values.length - 2];
						}
						System.out.println("部门==============" + vals[i]);
					}
					infoSB.append(val).append("=").append(vals[i]).append("|");
				}
			}

			if (value != null) {
				infoSB.append(valueS[0]).append("=").append(value).append("|");
			}

		}

		TCComponent[] releases = caxaDataset.getReferenceListProperty("release_status_list");
		if (releases != null && releases.length > 0) {
			Date dateProperty = caxaDataset.getDateProperty("date_released");
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");// 设置日期格式
			String time = df.format(dateProperty);
			String strfb = "PLM审核通过" + time;
			infoSB.append("PLM标记").append("=").append(strfb).append("|");
		}

		if (infoSB.toString().endsWith("|")) {
			String filePath = System.getenv("TEMP") + "\\project.txt";
			// String filePath1 = System.getenv("TEMP") + "\\AutoCAD.txt";
			try {

				FileOutputStream writerStream = new FileOutputStream(filePath);
				BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(writerStream));
				bw.write(infoSB.toString().substring(0, infoSB.toString().lastIndexOf("|")));
				System.out.println();
				bw.close();
				writerStream.close();

				System.out.println(infoSB.toString().substring(0, infoSB.toString().lastIndexOf("|")));
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	/**
	 * 处理宏协的CAXA数据集打开前操作
	 * 
	 * @param caxaDataset
	 * @throws TCException
	 */
	public void hx_SetCAXAFile(TCComponentDataset caxaDataset, TCPreferenceService tcp) throws TCException {
		StringBuffer infoSB = new StringBuffer();
		TCComponentItemRevision rev = null;
		TCComponentItem item = null;
		TCComponentForm revForm = null;
		TCComponentForm itemForm = null;
		String datasetName = null;
		if (caxaDataset == null) {
			return;
		}
		TCComponentTcFile[] tcFiles = caxaDataset.getTcFiles();
		// File file = null;
		if (tcFiles != null && tcFiles.length != 0) {

			datasetName = tcFiles[0].getStringProperty("object_string");
		}
		System.out.println(" datasetName =" + datasetName);
		// = caxaDataset.getStringProperty("object_name");
		rev = (TCComponentItemRevision) caxaDataset.getReferenceProperty("item_revision");// 获得当前数据集所在版本对象

		if (rev == null) {
			return;
		}
		revForm = (TCComponentForm) (rev.getReferenceListProperty("IMAN_master_form_rev"))[0];
		item = rev.getItem();

		String[] refValues = tcp.getStringArray(TCPreferenceService.TC_preference_site, "HxCaxaMapping");
		if (refValues == null || refValues.length == 0) {
			MessageBox.post("HxCaxaMapping首选项未配置，请联系管理员！！", "提示", MessageBox.INFORMATION);
			return;
		}

		for (String refValue : refValues) {
			String[] valueS = refValue.split("=");
			String value = null;
			if (valueS == null || valueS.length != 2) {
				continue;
			}
			String[] propNameS = valueS[1].split("\\.");
			if (propNameS == null || propNameS.length != 2) {
				continue;
			}
			switch (propNameS[0].toUpperCase()) {
			case "ITEM":
				value = hx_GetProp(item, propNameS[1]);
				break;
			case "REV":
				value = hx_GetProp(rev, propNameS[1]);
				break;
			case "REVMASTER":
				value = hx_GetProp(revForm, propNameS[1]);
				break;
			case "ITEMMASTER":
				break;
			default:
				break;

			}

			infoSB.append(valueS[0]).append("=").append(value).append("|");
		}

		if (infoSB.toString().endsWith("|")) {
			String filePath = System.getenv("TEMP") + "\\" + datasetName + ".txt";

			try {
				// TxtFileRWHelper textFile = new TxtFileRWHelper(
				// filePath);
				//
				//
				// textFile.writeTxtFile2(infoSB.toString().substring(0,
				// infoSB.toString().lastIndexOf("|")));

				FileOutputStream writerStream = new FileOutputStream(filePath);
				BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(writerStream));
				StringBuffer sb = new StringBuffer();
				bw.write(infoSB.toString().substring(0, infoSB.toString().lastIndexOf("|")));
				System.out.println();
				bw.close();
				writerStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	/**
	 * 获取属性
	 * 
	 * @param comp
	 * @return
	 */
	public String hx_GetProp(TCComponent comp, String refInfo) {
		if (comp == null) {
			return null;
		}
		if (refInfo == null) {
			return null;
		}
		String value = null;
		try {
			value = comp.getProperty(refInfo);
			
			TCProperty prop = comp.getTCProperty(refInfo);
			if (prop == null) {
				System.out.println("prop is null !");
				return value;
			}
			value = prop.getDisplayValue();
		} catch (TCException e) {
			e.printStackTrace();
		}
		return value;
	}

	/**
	 * 获取分类属性
	 * 
	 * @param comp
	 * @return
	 */
	public String hx_GetPropClass(TCComponent comp, String refInfo) {
		if (comp == null) {
			return null;
		}
		if (refInfo == null) {
			return null;
		}
		String classvalue = null;
		try {
			String classname = comp.getClassificationClass();
			if (classname == null || classname.equals("")) {
				return null;
			}
			int classid = 0;
			boolean islov = false;
			Map<String, String> map = new HashMap<>();
			TCClassificationService classificationService = comp.getSession().getClassificationService();
			// ICSSearchResult[] results =
			// classificationService.searchICOs("A020101",null, 0);

			ICSAdminClass c = classificationService.newICSAdminClass();

			c.load(classname);
			ICSAdminClassAttribute[] icsAttrS = c.getAttributes();
			if (icsAttrS != null) {
				for (ICSAdminClassAttribute attr : icsAttrS) {
					if (attr.isReferenceAttribute()) {// 引用属性
						continue;
					}
					if (attr.isReference()) {
						continue;
					}
					int propID = attr.getAttributeId();
					String propDisName = attr.getName();

					if ((propID + "").equals(refInfo)) {
						classid = propID;
						ICSKeyLov lov1 = attr.getFormat1().getKeyLov();
						lov1 = (lov1 == null ? attr.getFormat2().getKeyLov() : lov1);
						if (lov1 != null) {
							islov = true;
							String[] keys = lov1.getKeys();

							for (String key : keys) {
								String value = lov1.getValueOfKey(key);
								map.put(key, value);// <真实值,显示值>
							}
						}
					}
				}
			}
			if (classid == 0) {
				System.out.println("找不到这个id=" + classid);
				return null;
			}
			ICSProperty[] icsProps = comp.getClassificationObjects()[0].getICSProperties(true);
			if (icsProps == null && icsProps.length <= 0) {
				return null;
			}
			for (int w = 0; w < icsProps.length; w++) {
				if (icsProps[w].getId() == classid) {
					classvalue = icsProps[w].getValue();
					if (islov) {
						if (map.containsKey(classvalue)) {
							classvalue = map.get(classvalue);
						}
					}
				}
			}
		} catch (TCException e) {
			e.printStackTrace();
		}
		return classvalue;
	}

	public void setByPass(boolean val) throws TCException {
		TCUserService userservice = null;
		if (userservice == null) {
			userservice = ((TCSession) AIFUtility.getCurrentApplication().getSession()).getUserService();
		}
		Object[] obj = new Object[1];
		obj[0] = "origin";
		if (val) {
			userservice.call("ORIGIN_set_bypass", obj);
		} else {
			userservice.call("ORIGIN_close_bypass", obj);
		}
	}

	public void setTypeToFile(String type, TCComponentDataset dataset, TCComponentItemRevision revision) {
		String[] fileNames = null;
		String dwgFile = "file";
		try {
			fileNames = dataset.getFileNames("TM2_dwg");
		} catch (TCException e1) {
			e1.printStackTrace();
		}
		if (fileNames != null) {
			for (String fileName : fileNames) {
				System.out.println(fileName);
				if (fileName.endsWith(".dwg")) {
					dwgFile = fileName;
					break;
				}
			}
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-dd");
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS");
		String tempPath = System.getenv("TEMP");
		String itemID = "";
		try {
			itemID = revision.getStringProperty("item_id");
		} catch (TCException e1) {
			e1.printStackTrace();
		}
		if (tempPath == null) {
			System.out.println(" TEMP ==NULL");
			return;
		}
		try {
			File folder = new File(tempPath + "\\" + sdf.format(new Date()));
			if (!folder.exists()) {
				folder.mkdir();
			}

			FileOutputStream writerStream = new FileOutputStream(
					tempPath + "\\" + sdf.format(new Date()) + "\\" + sdf2.format(new Date()) + ".txt");
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(writerStream, "UTF-8"));
			StringBuffer sb = new StringBuffer();
			bw.write(dwgFile + "|" + itemID);
			System.out.println(dwgFile + "|" + itemID);
			bw.close();
			writerStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 改变数据集的命名引用
	 * 
	 * @param tccomponentDataset
	 * @param quote
	 * @param type
	 * @param path
	 * @throws TCException
	 */
	public void changeDataSet(TCComponentDataset tccomponentDataset, String quote, String type, String path)
			throws TCException {
		String myPath[] = { path };
		String myQuote[] = { quote };// 引用"excel"
		String myType[] = { type };// 类型"MSExcelX"
		String myPlain[] = { "Plain" };

		// 删除数据集的引用
		deleDateSetRef(tccomponentDataset);
		// 数据集的替换
		tccomponentDataset.setFiles(myPath, myType, myPlain, myQuote);
	}

	/**
	 * 删除数据集的命名引用
	 * 
	 * @param dataset
	 * @throws TCException
	 */
	private void deleDateSetRef(TCComponentDataset dataset) throws TCException {

		TCComponentTcFile[] tcFiles = dataset.getTcFiles();
		for (int i = 0; i < tcFiles.length; i++) {
			// 得到数据集的引用类型
			String str_temp = getNamedRefType(dataset, tcFiles[i]);
			// 删除引用
			dataset.removeNamedReference(str_temp);
		}

	}

	/**
	 * 得到数据集的引用类型
	 * 
	 * @param datasetComponent
	 * @param tccomponent
	 * @return
	 * @throws TCException
	 */
	private String getNamedRefType(TCComponentDataset datasetComponent, TCComponentTcFile tccomponent)
			throws TCException {
		String s;
		s = "";
		TCProperty tcproperty;
		TCProperty tcproperty1;
		TCComponent atccomponent[];
		String as[];
		int i;
		int j;
		int k;
		try {
			tcproperty = datasetComponent.getTCProperty("ref_list");
			tcproperty1 = datasetComponent.getTCProperty("ref_names");
			if (tcproperty == null || tcproperty1 == null)
				return s;
		} catch (TCException tcexception) {
			return s;
		}
		// ref_list:123.xlsx
		// datasetComponent.getRelatedComponents("ref_list")
		atccomponent = tcproperty.getReferenceValueArray();
		// 得到当前ref_names:excel
		as = tcproperty1.getStringValueArray();
		if (atccomponent == null || as == null)
			return s;
		i = atccomponent.length;
		if (i != as.length)
			return s;
		j = -1;
		k = 0;
		do {
			if (k >= i)
				break;
			if (tccomponent == atccomponent[k]) {
				j = k;
				break;
			}
			k++;
		} while (true);
		if (j != -1)
			s = as[j];
		return s;
	}

	/**
	 * 下载文件
	 * 
	 * @param comps
	 * @return
	 * @throws TCException
	 * @throws IOException
	 */
	public String downLoadFile(TCComponent comp) throws TCException {
		if (comp == null) {
			return "";
		}
		String value = "";
		String tempPath = System.getenv("TEMP");
		// MessageBox.post(" tempPath =
		// "+tempPath,"INFO",MessageBox.INFORMATION);
		if (tempPath == null) {
			tempPath = "";
		} else if (!tempPath.endsWith("\\")) {
			tempPath = tempPath + "\\";
		}
		String name = comp.getStringProperty("object_name");
		// for(TCComponent comp : comps){
		try {
			if (comp instanceof TCComponentDataset) {
				TCComponentTcFile[] tcFiles = ((TCComponentDataset) comp).getTcFiles();
				File file = null;
				if (tcFiles != null && tcFiles.length != 0) {
					file = tcFiles[0].getFmsFile();
					String fileName = tempPath + name;
					File dirFile = new File(fileName);
					FileUtility.copyFile(file, dirFile);

					return fileName;
				}
			}
		} catch (TCException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// }
		return value;
	}

	/**
	 * 下载文件
	 * 
	 * @param comps
	 * @return
	 * @throws TCException
	 * @throws IOException
	 */
	public String downLoadFile2(TCComponent comp) {
		if (comp == null) {
			return "";
		}
		String value = "";
		String tempPath = System.getenv("TEMP");
		// MessageBox.post(" tempPath =
		// "+tempPath,"INFO",MessageBox.INFORMATION);
		if (tempPath == null) {
			tempPath = "";
		} else if (!tempPath.endsWith("\\")) {
			tempPath = tempPath + "\\";
		}
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		// for(TCComponent comp : comps){
		try {
			if (comp instanceof TCComponentDataset) {
				TCComponentTcFile[] tcFiles = ((TCComponentDataset) comp).getTcFiles();
				File file = null;
				if (tcFiles != null && tcFiles.length != 0) {
					file = tcFiles[0].getFmsFile();
					String fileName = file.getName();
					String fileDix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
					// fileName = tempPath + sdf.format(new Date()) + fileDix;
					fileName = tempPath + fileDix;
					File dirFile = new File(fileName);
					FileUtility.copyFile(file, dirFile);

					return fileName;
				}
			}
		} catch (TCException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// }
		return value;
	}

	public void openCad() {

		String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
		String exePath = path.substring(1, path.indexOf("com.connor.signoff")).replace("/", "\\");
		exePath = exePath + "CADregedit.bat";
		File file = new File(exePath);

		if (file != null && file.exists()) {
			System.out.println("执行注册表修改");
			Runtime rn = Runtime.getRuntime();
			Process p = null;
			try {
				p = rn.exec("\"" + exePath + "\"");
				// Thread.sleep(1000L);
			} catch (Exception e) {
				System.out.println("Error exec!");
			}
		} else {
			System.out.println("不存在" + exePath + "文件");
		}
		// org.eclipse.swt.widgets.MessageBox box = new
		// org.eclipse.swt.widgets.MessageBox(
		// Display.getCurrent().getActiveShell(), SWT.ICON_INFORMATION
		// | SWT.YES | SWT.NO);

		// 设置对话框的标题
		// box.setText("提示");
		// 设置对话框显示的消息
		// box.setMessage("是否用中望CAD打开？");
		// 打开对话框，将返回值赋给choice
		// int choice = box.open();
		// 打印出所选择的值
		// if (choice == SWT.YES) {

		// System.out.print("Yes");
		// exePath = exePath + "CADregedit.bat";
		// // } else if (choice == SWT.NO) {
		// // System.out.print("No");
		// // exePath = exePath + "CADregedit.bat";
		// // }
		//
		// File file = new File(exePath);
		//
		// if (file != null && file.exists()) {
		// System.out.println("执行注册表修改");
		// Runtime rn = Runtime.getRuntime();
		// Process p = null;
		// try {
		// p = rn.exec("\"" + exePath + "\"");
		// Thread.sleep(1000L);
		// } catch (Exception e) {
		// System.out.println("Error exec!");
		// }
		// } else {
		// System.out.println("不存在" + exePath + "文件");
		// }
	}

	/*
	 * 解析数据集
	 */
	class DatasetParser {
		private TCComponentItemRevision rev;
		private TCComponentForm form;
		private TCComponentItemRevision whereRev;
		private TCComponentForm whereForm;

		public DatasetParser(TCComponentItemRevision rev, TCComponentForm form) {

			this.rev = rev;

			this.form = form;

		}

		public DatasetParser(TCComponentItemRevision rev, TCComponentForm form, TCComponentItemRevision whereRev,
				TCComponentForm whereForm) {

			this.rev = rev;

			this.form = form;

			this.whereRev = whereRev;

			this.whereForm = whereForm;

		}

		public DatasetParser(TCComponentItemRevision rev) {
			this.rev = rev;

		}

		// 根据首选项值，获得对应对象的内容，并返回需要写入txt文档中的内容
		public Vector<String> parsePreference(String[] preferenceValues) throws TCException {
			Vector<String> realm_attr = new Vector<String>();// “域名=属性值”的集合

			for (int i = 0; i < preferenceValues.length; i++) {
				String[] obj_attrs = preferenceValues[i].split("=");
				StringBuffer sb = new StringBuffer(obj_attrs[1]);// 域名
				sb.append("="); // =
				if (obj_attrs.length == 2) {
					String str = "";
					if (obj_attrs[0].contains("+")) {
						String[] attrs = obj_attrs[0].split("\\+");
						for (String attr : attrs) {
							if (attr.contains(".")) {
								str += getAttr(attr);
							} else {
								str += attr;
							}
						}
						System.out.println("str================" + str);
					} else {
						str = getAttr(obj_attrs[0]);
						System.out.println("obj_attrs[1]================" + obj_attrs[1]);
						System.out.println("str================" + str);
					}
					sb.append(str);
					String value = "";
					String val = sb.toString();
					if (obj_attrs[1].contains("图号") || obj_attrs[1].contains("名称")) {
						if (val.contains(".")) {
							String[] vals = val.split("\\.");
							StringBuilder valsb = new StringBuilder(vals[0]);
							for (int j = 0; j < vals.length; j++) {
								valsb.append(vals[j]);
							}
							value = valsb.toString();
						} else {
							value = sb.toString();
						}
					} else {
						value = sb.toString();
					}
					realm_attr.add(value);
				} else {
					return null;
				}
			}
			return realm_attr;
		}

		public String getAttr(String obj_attrs) throws TCException {
			int index = obj_attrs.indexOf('.');
			String value = "";
			String name = form.getStringProperty("object_name");
			System.out.println("name===========" + name);
			if (index != -1) {
				String obj = obj_attrs.substring(0, index);
				String att = obj_attrs.substring(index + 1);

				if ("Rev".equals(obj)) { // 属性值
					String proValue = null;
					if (isTE && (att.equals("item_id") || att.equals("object_name"))) {
						AIFComponentContext[] pContextS = rev.getItem().whereReferencedByTypeRelation(
								new String[] { "TM2_ProductRevision" }, new String[] { "TM2_gytz" });
						for (AIFComponentContext aifcc : pContextS) {
							System.out.println("aifcc.getComponent().getType()++++>" + aifcc.getComponent().getType());
						}
						if (pContextS != null && pContextS.length > 0) {
							try {
								proValue = ((TCComponentItemRevision) pContextS[0].getComponent()).getItem()
										.getProperty(att);
								System.out.println("TM2_ProductRevision =>PROP>[" + att + "]=[" + proValue + "]");
							} catch (Exception e) {
								e.printStackTrace();
							}
						} else {
							proValue = " ";
						}
					} else {
						proValue = rev.getProperty(att);
					}
					if (proValue != null)
						value = proValue;

				} else if ("Form".equals(obj)) {
					System.out.println("formType=====>" + form.getType());
					System.out.println("att===>" + att);
					String proValue = form.getProperty(att);
					if (proValue != null) {
						value = proValue;
					}
				} else if ("ItemRev".equals(obj)) {
					TCComponent tag = rev.getReferenceProperty("items_tag");
					String proValue = tag.getProperty(att);
					if (proValue != null)
						value = proValue;
					value.replace(" ", "\n");
				} else if ("WhereForm".equals(obj)) {
					if (whereForm != null) {
						System.out.println("whereFormType=====>" + whereForm.getType());
						System.out.println("att===>" + att);
						String proValue = whereForm.getProperty(att);
						if (proValue != null) {
							value = proValue;
						}
					}

				} else if ("WhereRev".equals(obj)) {
					if (whereRev != null) {
						System.out.println("whereRevType=====>" + whereRev.getType());
						System.out.println("att===>" + att);
						String proValue = whereRev.getProperty(att);
						if (proValue != null) {
							value = proValue;
						}
					}

				}

			} else {
				return null;
			}
			return value;
		}

	}

	/*
	 * 读，写Text文档
	 */
	class TxtFileRWHelper {
		private File txtFile = null;
		private BufferedReader br = null;
		private BufferedWriter bw = null;

		public TxtFileRWHelper(String txtFilePath) {
			this.txtFile = new File(txtFilePath);
			if (!this.txtFile.exists()) {
				try {
					this.txtFile.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		// 读 Text文件
		// 返回值：Text文件内容，Vector每个成员相当于一行数据
		public Vector<String> readTxtFile() throws IOException {
			Vector<String> txtFileContent = new Vector<String>();
			br = new BufferedReader(new FileReader(txtFile));
			if (!txtFile.canRead()) {
				txtFile.setReadable(true);
			}
			String line = br.readLine();
			while (line != null) {
				txtFileContent.add(line);
				line = br.readLine();
			}
			br.close();
			br = null;
			return txtFileContent;
		}

		// 写text文件
		// 入参：Vector<String>Vector中的每个成员作为一行数据处理
		public void writeTxtFile(Vector<String> txtFileContent) throws IOException {
			bw = new BufferedWriter(new FileWriter(txtFile));
			if (!txtFile.canWrite()) {
				txtFile.setWritable(true);
			}
			for (int i = 0; i < txtFileContent.size(); i++) {
				bw.write(txtFileContent.get(i));
				sb.append(txtFileContent.get(i));
				if (i != txtFileContent.size() - 1) {
					bw.write("|");
					sb.append("|");
				}
			}
			bw.close();
			bw = null;

		}

		// 写text文件
		// 入参：Vector<String>Vector中的每个成员作为一行数据处理
		public void writeTxtFile2(String txtFileContent) throws IOException {
			bw = new BufferedWriter(new FileWriter(txtFile));
			if (!txtFile.canWrite()) {
				txtFile.setWritable(true);
			}
			bw.write(txtFileContent);
			bw.close();
			bw = null;

		}

		// 删除text 文件
		public void deleteTxtFile() {
			if (txtFile.exists()) {
				txtFile.delete();
			}

		}

	}

}
