package com.connor.signoff.soa.handler;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DateFormat;
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 java.util.UUID;

import org.apache.commons.lang.StringUtils;

import com.teamcenter.clientx.AppXSession;
import com.teamcenter.schemas.soa._2006_03.exceptions.ServiceException;
import com.teamcenter.services.strong.core.DataManagementService;
import com.teamcenter.services.strong.core.SessionService;
import com.teamcenter.services.strong.core._2007_01.DataManagement.WhereReferencedInfo;
import com.teamcenter.services.strong.core._2007_01.DataManagement.WhereReferencedResponse;
import com.teamcenter.services.strong.query.SavedQueryService;
import com.teamcenter.services.strong.query._2006_03.SavedQuery;
import com.teamcenter.soa.client.model.ErrorStack;
import com.teamcenter.soa.client.model.ModelObject;
import com.teamcenter.soa.client.model.Property;
import com.teamcenter.soa.client.model.ServiceData;
import com.teamcenter.soa.client.model.strong.Dataset;
import com.teamcenter.soa.client.model.strong.Group;
import com.teamcenter.soa.client.model.strong.ImanQuery;
import com.teamcenter.soa.client.model.strong.User;
import com.teamcenter.soa.client.model.strong.WorkspaceObject;
import com.teamcenter.soa.client.FileManagementUtility;
import com.teamcenter.soa.client.GetFileResponse;

public class TcUtils {

	private static DateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	public static String TYPE_DATE = "date";
	public static String TYPE_DATE_TIME = "dateTime";
	private static Map<Integer,String> bomMap = null;
	
//	// 文件类型映射表
//	public static Map<String, String[]> fileTypeMap = new HashMap<String, String[]>();
//	static {
//		fileTypeMap.put("xlsx", new String[] { "MSExcelX", "excel" });
//		fileTypeMap.put("xls", new String[] { "MSExcel", "excel" });
//		fileTypeMap.put("xlsm", new String[] { "MSExcelX", "excel" });
//		fileTypeMap.put("csv", new String[] { "MSExcelX", "excel" });
//		fileTypeMap.put("txt", new String[] { "Text", "Text" });
//		fileTypeMap.put("docx", new String[] { "MSWordX", "word" });
//		fileTypeMap.put("doc", new String[] { "MSWord", "word" });
//		fileTypeMap.put("pptx", new String[] { "MSPowerPointX", "powerpoint" });
//		fileTypeMap.put("ppt", new String[] { "MSPowerPoint", "powerpoint" });
//		fileTypeMap.put("pdf", new String[] { "PDF", "PDF_Reference" });
//		fileTypeMap.put("jpg", new String[] { "Image", "Image" });
//		fileTypeMap.put("jpeg", new String[] { "Image", "Image" });
//		fileTypeMap.put("png", new String[] { "Image", "Image" });
//		fileTypeMap.put("gif", new String[] { "Image", "Image" });
//		fileTypeMap.put("dwg", new String[] { "ACADDWG", "DWG" });
//	}
//	
//	public static String transRefId(String refId) {
//		return refId.replaceAll("[|/\\:\\*\\?<>\\\\\"]", "_");
//	}
//
//	public static void main(String[] args) {
//		Float	usercount = Float.parseFloat("3.83");
//		System.out.println(usercount);
//
//	}
//
//	// 根据ItemID查找零件
//	public static TCComponentItem findItemByItemId(String itemId, TCSession session) {
//		TCComponentItem myQueryedItem = null;
//
//		try {
//			TCComponentItemType itemType = (TCComponentItemType) session.getTypeComponent("Item");
//			myQueryedItem = itemType.find(itemId);
//			if (myQueryedItem != null)
//				return myQueryedItem;
//
//		} catch (TCException e) {
//			e.printStackTrace();
//		}
//		return null;
//	}
//	
//	
//	// 根据ItemID批量查询查找零件xxx;xxxx;yyyy
//		public static TCComponentItem[] findItemByItemIds(String itemIds, TCSession session) {
//			TCComponentItem[] myQueryedItem = null;
//
//			try {
//				TCComponentItemType itemType = (TCComponentItemType) session.getTypeComponent("Item");
//				myQueryedItem = itemType.findItems(itemIds);
//				if (myQueryedItem != null)
//					return myQueryedItem;
//
//			} catch (TCException e) {
//				e.printStackTrace();
//			}
//			return null;
//		}
//
//	public static TCComponentItemRevision findItemRevisonByItemIdAndRevision(String itemId, String revNo, TCSession session) {
//		try {
//			TCComponentItem item = findItemByItemId(itemId, session);
//			if (item == null) {
//				return null;
//			}
//			return item.getLatestItemRevision().findRevision(revNo);
//		} catch (TCException e) {
//			e.printStackTrace();
//		}
//		return null;
//	}
//
//	/**
//	 * 将tccomponent从新窗口打开TCcomponent
//	 * @param tcComponent
//	 */
////	public static void openComponent(TCComponent tcComponent) {
////		IApplicationDefService appDefService = AifrcpPlugin.getApplicationDefService();
////		ApplicationDef appDef = appDefService.getApplicationDef("com.teamcenter.rac.ui.perspectives.navigatorPerspective");
////
////		if (appDef == null) {
////			appDef = appDefService.getApplicationDefByPerspectiveId("com.teamcenter.rac.ui.perspectives.navigatorPerspective");
////		}
////		TCComponent[] comps = new TCComponent[] { tcComponent };
////		appDef.openApplication(comps);
////	}
//	public static void openComponent(TCComponent tcComponent) {
//		IPerspectiveDefService iperspectivedefservice = (IPerspectiveDefService) OSGIUtil.getService(AifrcpPlugin.getDefault(), IPerspectiveDefService.class);
//		String s = "com.teamcenter.rac.ui.perspectives.navigatorPerspective";
//		IPerspectiveDef iperspectivedef = iperspectivedefservice.findByLegacyAppId(s);
//		TCComponent[] comps = new TCComponent[] { tcComponent };
//		iperspectivedef.openPerspective(comps);
//	}
//	
//
//	public static void test(TCComponent tcComponent){
//		IPerspectiveDefService iperspectivedefservice = (IPerspectiveDefService) OSGIUtil.getService(AifrcpPlugin.getDefault(), IPerspectiveDefService.class);
//		String s = "com.teamcenter.rac.ui.views.ActiveWorkspaceView.newView";
//		IPerspectiveDef iperspectivedef = iperspectivedefservice.findByLegacyAppId(s);
//		TCComponent[] comps = new TCComponent[] { tcComponent };
//		iperspectivedef.openPerspective(comps);
//	}
//	
//	/**
//	 * 将tccomponent从新窗口打开TCcomponent
//	 * @param tcComponent
//	 */
////	public static void openComponentToStructuerManager(TCComponent tcComponent) {
////		IApplicationDefService appDefService = AifrcpPlugin.getApplicationDefService();
////		ApplicationDef appDef = appDefService.getApplicationDef("com.teamcenter.rac.pse.PSEApplication");
////		TCComponent[] comps = new TCComponent[] { tcComponent };
////		appDef.openApplication(comps);
////	}
//	public static void openComponentToStructuerManager(TCComponent tcComponent) {
//		IPerspectiveDefService iperspectivedefservice = (IPerspectiveDefService) OSGIUtil.getService(AifrcpPlugin.getDefault(), IPerspectiveDefService.class);
//		String s = "com.teamcenter.rac.pse.PSEApplication";
//		IPerspectiveDef iperspectivedef = iperspectivedefservice.findByLegacyAppId(s);
//		TCComponent[] comps = new TCComponent[] { tcComponent };
//		iperspectivedef.openPerspective(comps);
//	}
//
//	public static String printExecption(Throwable e) {
//		StringBuffer output = new StringBuffer();
//		e.printStackTrace();
//		StackTraceElement[] stes = e.getStackTrace();
//		output.append("异常:" + e.toString());
//		for (int i = 0; i < stes.length; i++) {
//			StackTraceElement stackTraceElement = stes[i];
//			output.append("at " + stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName() + "(" + stackTraceElement.getFileName() + ":"
//					+ stackTraceElement.getLineNumber() + ")");
//		}
//		if (output.length() > 4000) {
//			return output.substring(0, 4000);
//		}
//		return output.toString();
//	}
//
//	public static void printTccompent(TCComponent tcComponent) {
//		System.out.println("printf ......tccomponet.........begin");
//		System.out.println("class " + tcComponent.getClass());
//		try {
//			if (tcComponent == null && tcComponent.getPropertyNames().length == 0) {
//				return;
//			}
//			String[] values = tcComponent.getProperties(tcComponent.getPropertyNames());
//			int i = 0;
//			for(String property : tcComponent.getPropertyNames()){
//				System.out.print("key: " + property);
//				System.out.print(values[i]);
//				i++;
//			}
////			Iterator it = tcComponent.getProperties().keySet().iterator();
////			while (it.hasNext()) {
////				String key = (String) it.next();
////				System.out.print("key: " + key);
////				System.out.print(tcComponent.getProperties().get(key));
////			}
//			System.out.println();
//		} catch (TCException e) {
//			e.printStackTrace();
//		}
//		System.out.println("printf ......tccomponet.........end");
//	}
//
//	public static TCComponentBOMViewRevision getBomViewRevision(TCComponentItemRevision componentItemRevision) throws Exception {
//		AIFComponentContext[] contexts = componentItemRevision.getChildren();
//		for (AIFComponentContext componentContext : contexts) {
//			String objecttype = componentContext.getComponent().getType();//getProperty("object_type");
//			if (objecttype.equals("BOMView Revision")) {
//				return (TCComponentBOMViewRevision) componentContext.getComponent();
//			}
//		}
//		return null;
//	}
//
//	public static String[] getTCPreferenceArray(String key, TCSession session,int tcScope) {
//		TCPreferenceService tcprefsvr = session.getPreferenceService();
//		if(tcScope == -1) {
//			tcScope = TCPreferenceService.TC_preference_site;
//		}
//		return tcprefsvr.getStringArray(tcScope, key);
//	}
//
//	public static String getTCPreference(String key, TCSession session ,int tcScope) {
//		TCPreferenceService tcprefsvr = session.getPreferenceService();
//		if(tcScope == -1) {
//			tcScope = TCPreferenceService.TC_preference_site;
//		}
//		return tcprefsvr.getString(tcScope, key);
//	}
//
//	/**
//	 * 设置窗口位于屏幕中间
//	 * 
//	 * @param display
//	 *            设备
//	 * @param shell
//	 *            要调整位置的窗口对象
//	 */
//	public static void center(Display display, Shell shell) {
//		Rectangle bounds = display.getPrimaryMonitor().getBounds();
//		Rectangle rect = shell.getBounds();
//		int x = bounds.x + (bounds.width - rect.width) / 2;
//		int y = bounds.y + (bounds.height - rect.height) / 2;
//		shell.setLocation(x, y);
//	}
//
//	/**
//	 * "TC_Generic_Architecture","ArchitectureRevision"
//	 * 
//	 * @param comp
//	 * @param relation
//	 * @param type
//	 * @return
//	 * @throws TCException
//	 */
//	public static InterfaceAIFComponent getChildByRelation(TCComponent comp, String relation, String type) throws TCException {
//		AIFComponentContext[] components = comp.getChildren(relation);
//		for (AIFComponentContext componentContext : components) {
//			if (type.equals(componentContext.getComponent().getType())) {
//				return componentContext.getComponent();
//			}
//		}
//		return null;
//	}
//
//	/**
//	 * "TC_Generic_Architecture","ArchitectureRevision"
//	 * 
//	 * @param comp
//	 * @param relation
//	 * @param type
//	 * @return
//	 * @throws Exception
//	 */
//	public static InterfaceAIFComponent getChildByRelationAndName(TCComponent comp, String relation, String type, String name) throws Exception {
//		AIFComponentContext[] components = comp.getChildren(relation);
//		for (AIFComponentContext componentContext : components) {
//			if (type.equals(componentContext.getComponent().getType()) && name.equalsIgnoreCase(componentContext.getComponent().getProperty("object_name"))) {
//				return componentContext.getComponent();
//			}
//		}
//		return null;
//	}
//
//	public static String getTCConfigRuleName(TCSession session) {
//		TCPreferenceService tcprefsvr = session.getPreferenceService();
//		String TCConfigRuleName = "";
//		try {
//			// TC_Output_BOM_RevConfig
//			// TC_SendToSRM_Rev_Rule_OLD
//			TCConfigRuleName = tcprefsvr.getString(TCPreferenceService.TC_preference_site, "TC_Output_BOM_RevConfig");
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return TCConfigRuleName;
//	}
//
//	public static String getTCConfigNewRuleName(TCSession session) {
//		TCPreferenceService tcprefsvr = session.getPreferenceService();
//		String TCConfigRuleName = "";
//		try {
//			// TC_Output_BOM_RevConfig
//			// TC_SendToSRM_Rev_Rule_OLD
//			TCConfigRuleName = tcprefsvr.getString(TCPreferenceService.TC_preference_site, "TC_SendToSRM_Rev_Rule_NEW");
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return TCConfigRuleName;
//	}
//	
//	public static String getTCConfigOldRuleName(TCSession session) {
//		TCPreferenceService tcprefsvr = session.getPreferenceService();
//		String TCConfigRuleName = "";
//		try {
//			// TC_Output_BOM_RevConfig
//			// TC_SendToSRM_Rev_Rule_OLD
//			TCConfigRuleName = tcprefsvr.getString(TCPreferenceService.TC_preference_site, "TC_SendToSRM_Rev_Rule_OLD");
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return TCConfigRuleName;
//	}
//
//	public static String readTxt(String txtPath) {
//		StringBuffer sb = new StringBuffer();
//		try {
//			BufferedReader in = new BufferedReader(new FileReader(txtPath));
//			String line = null;
//			while ((line = in.readLine()) != null) {
//				sb.append(line);
//			}
//			return sb.toString();
//		} catch (Exception e) {
//			e.printStackTrace();
//			return null;
//		}
//	}
//
//
//	/**
//	 * 签入
//	 * @throws TCException 
//	 */
//	public static void signin(TCSession session, TCComponent component) throws TCException{
//		TCReservationService tcreservationservice = session.getReservationService();
//		if(component != null && tcreservationservice.isReserved(component)){
//			tcreservationservice.unreserve(component);
//		}
//	}
//	
//
//	
//	/**
//	 * 创建零件
//	 * @param itemID           零件id
//	 * @param itemName         零件名
//	 * @param itemType_name    零件的类型
//	 * @param Revision         版本
//	 * @param desc             描述
//	 * @param compObj          零件创建的位置（为空则创建在newStaff下）
//	 * @return
//	 */
//	public static TCComponentItem createItem(String itemID, String itemName, String itemType_name, String Revision, String desc, InterfaceAIFComponent compObj, Shell shell) {
//		AbstractAIFSession mysession = RACUIUtil.getTCSession();
//		TCSession imansession = (TCSession) mysession;
//		String[] EntryVal = new String[1];
//		EntryVal[0] = itemID;
//		if (mysession instanceof TCSession) {
//			try {
//				TCComponentItem myQueryedItem = null;
//				TCComponentItemType itemType = (TCComponentItemType) imansession.getTypeComponent("Item");
//				if (itemName == null || itemName == "")
//					itemName = itemID;
//				myQueryedItem = itemType.create(itemID, Revision, itemType_name, itemName, desc, null);
//				if (compObj instanceof TCComponentFolder) {
//					TCComponent comp = (TCComponent) compObj;
//					comp.add("contents", myQueryedItem);
//					return myQueryedItem;
//				} else if (compObj instanceof TCComponentBOMLine) {
//					TCComponentBOMLine compbomline = (TCComponentBOMLine) compObj;
//					compbomline.add(myQueryedItem, "");
//				} else {
//					imansession.getUser().getNewStuffFolder().add("contents", myQueryedItem);
//					return myQueryedItem;
//				}
//
//				return myQueryedItem;
//			} catch (TCException e) {
//				if(shell != null){
//					MessageBox.post(shell, "创建Item时出错\n错误提示:" + e.toString(), "提示", MessageBox.INFORMATION);
//				}else{
//					MessageBox.post("创建Item时出错\n错误提示:" + e.toString(), "提示", MessageBox.INFORMATION);
//				}
//				e.printStackTrace();
//				return null;
//			}
//		}
//		return null;
//	}
//	
//	/**
//	 * 获取单个选中
//	 */
//	public static InterfaceAIFComponent getSelectedObj(){
//		AbstractAIFUIApplication application = AIFUtility.getCurrentApplication();
//		InterfaceAIFComponent selectObj = application.getTargetComponent();
//		return selectObj;
//	}
//	
//	/**
//	 * 获取多个选中
//	 */
//	public static InterfaceAIFComponent[] getSelectedObjs(){
//		AbstractAIFUIApplication application = AIFUtility.getCurrentApplication();
//		InterfaceAIFComponent[] selectObj = application.getTargetComponents();
//		return selectObj;
//	}
//	
//	/**
//	 * 获取单个选中的ITEM对象，无选中对象返回null
//	 */
//	public static TCComponentItem getSelectedItem(){
//		InterfaceAIFComponent selectObj = getSelectedObj();
//		if(selectObj == null){
//			return null;
//		}
//		if(selectObj instanceof TCComponentItem){
//			TCComponentItem item = (TCComponentItem) selectObj;
//			return item;
//		}else{
//			MessageBox.post("选中的对象非Item对象！", "错误", MessageBox.ERROR);
//			return null;
//		}
//	}
//	
//	/**
//	 * 获取单个选中的ItemRevision对象，无选中对象返回null
//	 */
//	public static TCComponentItemRevision getSelectedItemRevision(){
//		InterfaceAIFComponent selectObj = getSelectedObj();
//		if(selectObj == null){
//			return null;
//		}
//		if(selectObj instanceof TCComponentItemRevision){
//			TCComponentItemRevision itemRev = (TCComponentItemRevision) selectObj;
//			return itemRev;
//		}else{
//			MessageBox.post("选中的对象非ItemRevision对象！", "错误", MessageBox.ERROR);
//			return null;
//		}
//	}
//	
//	/**
//	 * 获取单个选中的Bomline对象，无选中对象返回null
//	 */
//	public static TCComponentBOMLine getSelectedBomline(){
//		InterfaceAIFComponent selectObj = getSelectedObj();
//		if(selectObj == null){
//			return null;
//		}
//		if(selectObj instanceof TCComponentBOMLine){
//			TCComponentBOMLine bomline = (TCComponentBOMLine) selectObj;
//			return bomline;
//		}else{
//			MessageBox.post("选中的对象非BOMLine对象！", "错误", MessageBox.ERROR);
//			return null;
//		}
//	}
//	
//	/**
//	 * 获取bomwindow,可通过bomwin获取bomline，用完记得close
//	 * TCComponentBOMLine bomline = bomWin.setWindowTopLine(null, newItem, null, null);
//	 * @throws TCException 
//	 */
//	public static TCComponentBOMWindow getBomWin() throws TCException{
//		TCSession session = RACUIUtil.getTCSession();
//		TCComponentRevisionRuleType imancomponentrevisionruletype = (TCComponentRevisionRuleType) session.getTypeComponent("RevisionRule");
//		TCComponentRevisionRule imancomponentrevisionrule = imancomponentrevisionruletype.getDefaultRule();
//		TCComponentBOMWindowType imancomponentbomwindowtype = (TCComponentBOMWindowType) session.getTypeComponent("BOMWindow");
//		TCComponentBOMWindow bomWin = imancomponentbomwindowtype.create(imancomponentrevisionrule);
//		return bomWin;
//	}
//	
//	
//	
//	/**
//	 * 获取当前时间字符串
//	 * @param type:TYPE_DATE_FORMAT、TYPE_DATE_TIME_FORMAT
//	 * @return 当前时间字符串（默认返回yyyy-MM-dd HH:mm:ss）
//	 */
//	public static String getDateString(String type){
//		if(type.equals(TYPE_DATE)){
//			return dateFormat.format(new Date());
//		}else if(type.equals(TYPE_DATE_TIME)){
//			return dateTimeFormat.format(new Date());
//		}else{
//			return dateTimeFormat.format(new Date());
//		}
//	}
//	
//	/**
//	 * 通过零件版本获取零件表单
//	 * @param revision
//	 * @return
//	 */
//	public static TCComponentForm getFormFromRev(TCComponentItemRevision revision){
//		TCComponentForm itemRevForm = null;
//		if(revision != null){
//			AIFComponentContext[] itemRevForms = null;
//			try {
//				itemRevForms = revision.getChildren("IMAN_master_form_rev");
//			} catch (TCException e) {
//				e.printStackTrace();
//			}
//			if(itemRevForms.length > 0){
//				itemRevForm = (TCComponentForm) itemRevForms[0].getComponent();
//			}
//		}
//		return itemRevForm;
//	}
//	
//	/**
//	 * 获取插件根目录
//	 * @param pluginName 插件名称
//	 * @throws IOException 
//	 * @return 插件所在根目录
//	 */
//	public static String getPluginRootPath(String pluginName) throws IOException{
//		String path =FileLocator.toFileURL(Platform.getBundle(pluginName).getEntry("")).getPath();
//		return path;
//	}
//	
//	/**
//	 * 获取模板数据集下载下来后的绝对路径
//	 * @param type 类型，如excel
//	 * @param refType 类型关系，如MSExcel。具体关系可参考最顶上关系表
//	 * @return
//	 * @throws TCException
//	 */
//	public static String getTcDateSetPath(String prefrenceName, String type, String refType, String groupName) throws TCException{
//		return getTcDateSet(prefrenceName, type, refType, groupName).getAbsolutePath();
//	}
//	
//	/**
//	 * 获取模板数据集
//	 * @return
//	 * @throws TCException
//	 */
//	public static File getTcDateSet(String prefrenceName, String type, String refType, String groupName) throws TCException{
//		TCSession session = RACUIUtil.getTCSession();
//		//获取数据集名称
//		TCPreferenceService tcprefsvr = session.getPreferenceService();
//		String[] exportTemplate = tcprefsvr.getStringArray(TCPreferenceService.TC_preference_site, prefrenceName);
//		String exportFileName = exportTemplate[0];
//		//通过查询构建器找到数据集
//		TCComponentQueryType queryType = (TCComponentQueryType) session.getTypeComponent("ImanQuery");
//		TCComponentQuery orderByVehicleQuery = (TCComponentQuery) queryType.find("数据集...");
//		TCQueryClause[] clauses = orderByVehicleQuery.describe();
//		
//		String[] tmp_displayNames = new String[3];
//		String[] tmp_values = new String[3];
//		for (int i = 0; i < clauses.length; i++) {
//			if (clauses[i].getAttributeName().equals("object_name")) {
//				tmp_displayNames[0] = clauses[i].getUserEntryNameDisplay();
//				continue;
//			}
//			if (clauses[i].getAttributeName().equals("object_type")) {
//				tmp_displayNames[1] = clauses[i].getUserEntryNameDisplay();
//				continue;
//			}
//			if (clauses[i].getAttributeName().equals("owning_group.name")){
//				tmp_displayNames[2] = clauses[i].getUserEntryNameDisplay();
//				continue;
//			}
//		}
//		
//		tmp_values[0] = exportFileName;
//		tmp_values[1] = refType;
//		tmp_values[2] = groupName;
//		
//		//将文件存入临时路径
//		TCComponent[] comps = orderByVehicleQuery.execute(tmp_displayNames, tmp_values);
//		File[] file = null;
//		for (TCComponent comp : comps) {
//			TCComponentDataset dataSet = (TCComponentDataset) comp;
//			file = dataSet.getFiles(type, System.getProperty("java.io.tmpdir"));
//		}
//		if(file == null || !file[0].exists()){
//			MessageBox.post("导出" + type + "出错，存入临时文件失败", "错误", MessageBox.ERROR);
//			return null;
//		}else{
//			return file[0];
//		}
//	}
//	
//	/**
//	 * 检查是否存已经存在数据集
//	 * @param dataSetType  数据集类型：如MSExcel
//	 */
//	public static boolean checkHasDataSet(TCComponentItemRevision itemrev, String dataSetType){
//		TCComponent [] com = null;
//		boolean hasDataSet = false;
//		//检查是否已经存在数据集
//		try {
//			com = itemrev.getRelatedComponents("IMAN_specification");
//			TCComponentDataset d = null;
//			for (int n = 0; n < com.length; n++) {
//				if(com[n].getClassType().equals("Dataset")){
//					d = (TCComponentDataset)com[n];
//					String name = d.getTCProperty("object_name").getStringValue();
//					String type = d.getTCProperty("object_type").getStringValue();
//					if(name.endsWith(itemrev.getItem().toDisplayString())&&type.equals(dataSetType)){
//						//MessageBox.post("已经存在数据集，请手动删除后再生成！", "提示", MessageBox.INFORMATION);
//						hasDataSet = true;
//					}
//				}
//			}
//		} catch (TCException e) {
//			e.printStackTrace();
//		}
//		return hasDataSet;
//	}
//	
//	/**
//	 * 上传到TC本地临时文件并挂在Itemrev下
//	 * @param itemrev TC零件版本
//	 * @param outputFilePathName 临时文件路径                  
//	 * @param isDelFile  是否删除临时文件
//	 * @param ref 关系。默认IMAN_specification
//	 * @throws TCException
//	 */
//	public static void upload(TCComponentItemRevision itemrev, String outputFilePathName, boolean isDelFile, String ref) throws TCException{
//		if(StringUtils.isBlank(ref)){
//			ref = "IMAN_specification";
//		}
//		TCComponentDatasetType datasetType;
//		TCSession session = RACUIUtil.getTCSession();
//		TCComponentDataset dataset = null;
//		datasetType = (TCComponentDatasetType)session.getTypeComponent("Dataset");
//		dataset =datasetType.create(itemrev.getItem().toDisplayString(), "", getDataSetTypeFromFileName(outputFilePathName)[0]);
//		itemrev.add(ref, dataset);
//		
//		try {
//			writeDateSet(dataset, outputFilePathName, itemrev, isDelFile);
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}
//	
//	/**
//	 * 通过文件全名获取TC数据集关系
//	 * @return String[]  如：{ "MSExcelX", "excel" }
//	 */
//	public static String[] getDataSetTypeFromFileName(String fileName){
//		if(fileName.indexOf(".") < 0){
//			throw new RuntimeException("后缀名错误");
//		}
//		String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
//		if(!fileTypeMap.containsKey(suffix)){
//			throw new RuntimeException("后缀名：" + suffix + "关系错误");
//		}
//		return fileTypeMap.get(suffix);
//	}
//	
//	/**
//	 * 写入数据集
//	 * @param dataset
//	 * @param outputFileName
//	 * @param itemrev
//	 * @param dataSetType
//	 * @param isDelFile
//	 * @throws IOException
//	 * @throws FileNotFoundException
//	 * @throws Exception
//	 * @throws TCException
//	 */
//	public static void writeDateSet(TCComponentDataset dataset, String outputFilePathName, TCComponentItemRevision itemrev, boolean isDelFile) throws IOException, FileNotFoundException, Exception, TCException {
//		File output = new File(outputFilePathName);
//		String dataSetType = getDataSetTypeFromFileName(outputFilePathName)[0];
//		String fileName = output.getName();
//		String path = output.getParent() + File.separator + itemrev.getItem().toDisplayString() + fileName.substring(fileName.lastIndexOf("."));
//		output.renameTo(new File(path));
//		File out = new File(path);
//		String[] impfileNames = new String[]{out.getAbsolutePath()};
//		String[] nameRef = guessDatasetReferences(dataSetType, impfileNames);
//		dataset.setFiles(impfileNames, nameRef);
//		dataset.refresh();
//		dataset.lock();
//		dataset.save();
//		dataset.unlock();
//		if(output.exists() && isDelFile){
//			output.delete();
//		}
//	}
//	
//	/**
//	 * 获取数据集关系名
//	 * @param datasetType
//	 * @param files
//	 * @return
//	 * @throws Exception
//	 */
//	private static String[] guessDatasetReferences(String datasetType, String files[]) throws Exception {
//		System.out.println((new StringBuilder("dataset type:")).append(datasetType).toString());
//		TCSession session = RACUIUtil.getTCSession();
//		TCComponentDatasetDefinitionType dsdefType = (TCComponentDatasetDefinitionType)session.getTypeComponent("DatasetType");
//		TCComponentDatasetDefinition dsdef = dsdefType.find(datasetType);
//		NamedReferenceContext contexts[] = dsdef.getNamedReferenceContexts();
//		String refs[] = new String[files.length];
//		if (contexts.length == 1) {
//			for (int i = 0; i < refs.length; i++)
//				refs[i] = contexts[0].getNamedReference();
//		}
//		if (contexts.length > 1) {
//			for (int i = 0; i < files.length; i++) {
//				String ext = "";
//				String fname = (new File(files[i])).getName();
//				int pos = fname.lastIndexOf('.');
//				if (pos >= 0)
//					ext = fname.substring(pos);
//				for (int j = 0; j < contexts.length; j++) {
//					String pattern = contexts[j].getFileTemplate();
//					int pos1 = pattern.lastIndexOf('.');
//					if (pos1 < 0)
//						continue;
//					String re = pattern.substring(pos1);
//					if (!ext.equalsIgnoreCase(re))
//						continue;
//					refs[i] = contexts[j].getNamedReference();
//					break;
//				}
//			}
//		}
//		return refs;
//	}
//	/**
//	 * 获取TC打开数据集的路径
//	 * @param arg1
//	 * @return
//	 */
//	public static String getCaxaFile(AEShell arg1) {
//		File[] caxaFile = null;
//		try {
//			Method method = AEShell.class.getDeclaredMethod("askExportedFiles");
//	        method.setAccessible(true);
//	        Object retData = method.invoke(arg1);
//	        caxaFile = (File[])retData;
//	        return caxaFile[0].getAbsolutePath();
//		} catch (SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		return null;
//	}
//	/**
//	 * 获取TC打开数据集的路径
//	 * @param arg1
//	 * @return
//	 */
//	public static File getCaxaFile(String arg1) {
//		File finalCaxa = null;
//		// 清除bak等备份文件
//		File tempCacheFile = new File(arg1);
//		File[] allFiles = tempCacheFile.listFiles();
//		for (int i = allFiles.length - 1; i >= 0; i--) {
//			if (!allFiles[i].getAbsolutePath().toLowerCase().endsWith(".exb")) {
//				allFiles[i].delete();
//			} else {
//				finalCaxa = allFiles[i];
//			}
//		}
//		return finalCaxa;
//	}
//	public static String getFileName(TCComponentDataset tccomponentdataset) throws TCException {
//		// TODO Auto-generated method stub
//		TCComponent[] reList = tccomponentdataset.getRelatedComponents("ref_list");
//		if (reList == null || reList.length == 0) {
//			return "0";
//		} else if (reList.length == 1) {
//			return reList[0].getProperty("original_file_name");
//		} else if (reList.length > 1) {
//			return "2";
//		}
//		return null;
//	}
//	
//	public static TCComponentItemRevision getReferenceRev(TCComponentDataset arg0) {
//		int x = 0;
//		TCComponentItemRevision targetrev = null;
//		boolean workflow = false;
//		try {
//			AIFComponentContext[] revs = arg0.whereReferenced();
//			for (int i = 0; i < revs.length; i++) {
//				if (revs[i].getComponent() instanceof TCComponentItemRevision) {
//					TCComponentItemRevision rev = (TCComponentItemRevision) revs[i].getComponent();
//					TCComponent[] datasets = rev.getRelatedComponents("IMAN_specification");
//					for (int j = 0; j < datasets.length; j++) {
//						if (datasets[j].getUid().equals(arg0.getUid())) {
//							workflow = true;
//							targetrev = rev;
//							x++;
////						break;
//						}
//					}
//					if (workflow == true) {
////					break;
//					}
//
//				}
//			}
//		} catch (TCException e1) {
//			e1.printStackTrace();
//		}
//		if (x > 1) {
//			return null;
//		}
//		return targetrev;
//
//	}
//	
//	/**
//	 * 下载文件
//	 * 
//	 * @param comps
//	 * @return
//	 * @throws TCException
//	 * @throws IOException
//	 */
//	public static String downLoadCaxaFile(TCComponent comp,TCComponent rev,File finalCaxa) {
//		if (comp == null) {
//			return "";
//		}
//		String tempPath = System.getenv("TEMP");
//	if (!tempPath.endsWith("\\")) {
//			tempPath = tempPath + "\\";
//		}
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//		String fileName = finalCaxa.getName();
////		System.out.println("fileName:" + fileName);
//		String fileDix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
//		try {
//			fileName = tempPath +rev.getProperty("item_id")+"-"+rev.getProperty("item_revision_id")+ sdf.format(new Date()) + fileDix;
//			File dirFile = new File(fileName);
//			FileUtility.copyFile(finalCaxa, dirFile);
//		} catch (TCException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		
//		return fileName;
//	}
//	
//	/**
//	 * 获取Temp下的caxa文件
//	 * @param caxaDataset caxa数据集
//	 * @return caxa文件
//	 * @throws TCException
//	 */
//	public static File getCaxaDatasetFile(TCComponentDataset caxaDataset) throws TCException {
//	    File file = null;
//		String datasetName = null;
//		TCComponentTcFile[] tcFiles = caxaDataset.getTcFiles();
//		// File file = null;
//		if (tcFiles != null && tcFiles.length != 0) {
//	
//			datasetName = tcFiles[0].getStringProperty("object_string");
//		}
//		datasetName = datasetName.substring(0, datasetName.lastIndexOf('.'));
//		// 可能带有命名引用的文件带有两个.exb的后缀，要处理下
//		if (datasetName.endsWith(".exb") || datasetName.endsWith(".EXB")) {
//			datasetName = datasetName.substring(0, datasetName.lastIndexOf('.'));
//		}
//		file = new File(System.getenv("TEMP") + "\\" + datasetName + ".xml");
//		if(file != null) {
//			System.out.println("file:" + file);
//			System.out.println(" datasetName =" + datasetName);
//			// = caxaDataset.getStringProperty("object_name");
//			
//			System.out.println("tcfile:" + tcFiles[0].getWorkingDir());
//			System.out.println("tcfile2:" + tcFiles[0]);
//		}
//		return file;
//	}
//	
//	/**
//	 * 获取属性
//	 * 
//	 * @param comp
//	 * @return
//	 */
//	public static String hx_GetProp(TCComponent comp, String refInfo) {
//		if (comp == null) {
//			return null;
//		}
//		if (refInfo == null) {
//			return null;
//		}
//		try {
//			return comp.getProperty(refInfo);
//		} catch (TCException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		return "";
//	}
	/**
	 * 
	 * @param tccomponentdataset 
	 * @param tccomponentdataset
	 * @return
	 */
	public static int checkPDF(Dataset tccomponentdataset) {
		try {
			if (tccomponentdataset.getTypeObject().getName().equals("PDF")) {
				
				if(tccomponentdataset == null){
			        return 1;
			    }
			    DataManagementService dmService = DataManagementService.getService(AppXSession.getConnection());
			    FileManagementUtility fmu = new FileManagementUtility(AppXSession.getConnection(),
			            null,
			            new String[] { "http://192.168.2.242:4544" },
			            new String[] { "http://192.168.2.242:4544" },
			           "D://TEMP//fcc_tmp");
			    ModelObject[] objects = {tccomponentdataset};
	            dmService.refreshObjects(objects);
	            dmService.getProperties(objects, new String[]{"ref_list"});
	            objects = tccomponentdataset.get_ref_list();

	            GetFileResponse getFileResponse = fmu.getFiles(objects);
	            File[] fileinfovec = getFileResponse.getFiles();
//	            outFile = fileinfovec[0];

				// 检查命名引用的文件大小
				if (fileinfovec.length > 0) {
					File file = fileinfovec[0];
					if (file.length() == 0) {
//						MessageBox.post("请检查命名引用中原文件是否损毁或者大小为0", "", MessageBox.INFORMATION);
						return 1;
					}
				}
			}
			return 0;
		} catch (Exception e1) {
			
			e1.printStackTrace();
		}
		return 1;
	}
//	/**
//	 * 检查命名引用中原文件是否异常
//	 * @param tccomponentdataset 数据集
//	 * @return
//	 */
//	public static int checkDatasetFileName(TCComponentDataset tccomponentdataset) {
//		String originalFileName = "";
//		try {
//			originalFileName = TcUtils.getFileName(tccomponentdataset);
//			if (originalFileName.equals("0") || originalFileName.equals("2")) {
//				MessageBox.post("请检查命名引用中原文件是否异常", "", MessageBox.INFORMATION);
//				return 1;
//			}
//		} catch (TCException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//			MessageBox.post("Teamcenter异常："+e1.getMessage(), "", MessageBox.ERROR);
//		}
//		return 0;
//	}
//	public static String newString(String oldName) {
////		String newName=oldName;
//		if (oldName.contains("/")) {
//			System.out.println("bingo");
//			oldName = getNewName("/", oldName);
//		}
//		if (oldName.contains("*")) {
//			oldName = getNewName("*", oldName);
//		}
//		if (oldName.contains("\\")) {
//			oldName = getNewName("\\", oldName);
//		}
//		if (oldName.contains(":")) {
//			oldName = getNewName(":", oldName);
//		}
//		if (oldName.contains("?")) {
//			oldName = getNewName("?", oldName);
//		}
//		if (oldName.contains("\"")) {
//			oldName = getNewName("\"", oldName);
//		}
//		if (oldName.contains("<")) {
//			oldName = getNewName("<", oldName);
//		}
//		if (oldName.contains(">")) {
//			oldName = getNewName(">", oldName);
//		}
//		if (oldName.contains("|")) {
//			oldName = getNewName("|", oldName);
//		}
//		if (oldName.contains("（")) {
//			oldName = getNewName("（", oldName);
//		}
//		if (oldName.contains("）")) {
//			oldName = getNewName("）", oldName);
//		}
//		return oldName;
//	}
//
//	public static String getNewName(String illegalCharacter, String oldString) {
//		if (illegalCharacter.equals("（")) {
//			oldString = oldString.replace(illegalCharacter, "(");
//		} else if (illegalCharacter.equals("）")) {
//			oldString = oldString.replace(illegalCharacter, ")");
//
//		} else {
//
//			oldString = oldString.replace(illegalCharacter, "--");
//		}
//		return oldString;
//	}
    // 影响分析向上获取对象
    public static List<ModelObject> getWhereReference(WorkspaceObject[] obj){
        List<ModelObject> list = new ArrayList<ModelObject>();
        DataManagementService dataManagementService = DataManagementService.getService(AppXSession.getConnection());
        WhereReferencedResponse response =  dataManagementService.whereReferenced(obj,1);
        WhereReferencedInfo[] info =  response.output[0].info;
        for (int i = 0; i < info.length; i++) {
            list.add(info[i].referencer);
        }
        return list;
    }
    public static void setByPass(boolean b) throws Exception {
//      dataManagementService = DataManagementService.getService(AppXSession.getConnection());
//      queryService = SavedQueryService.getService(AppXSession.getConnection());
//      tcUser = ZwCADService.tcUser;
      com.teamcenter.services.strong.core._2007_12.Session.StateNameValue[] propPairs = new com.teamcenter.services.strong.core._2007_12.Session.StateNameValue[1];
      propPairs[0] = new com.teamcenter.services.strong.core._2007_12.Session.StateNameValue();
      propPairs[0].name = new String("bypassFlag");
      propPairs[0].value = new String(Property.toBooleanString(b));
      ServiceData data = SessionService.getService(AppXSession.getConnection()).setUserSessionState(propPairs);
//      checkPartialError(data);
  }
    public static void changeOwnershipModelObject(ModelObject user, String groupName, ModelObject[] modls) throws Exception
    {
        DataManagementService ser1 = DataManagementService.getService( AppXSession.getConnection() );
        //ModelObject user  = findUser( userName ) ;

        if( user != null )
        {
            System.out.println("................................owning user found..................................");

        } else {


            //The configured EPI-Owning-user is not found in Teamcenter.

            System.out.println("................  EPI-owning user not found ................");

            throw new Exception("Change ownership service: 003.Change ownership service - The configured EPI-owning user is not found in Teamcenter.");

        }
        ModelObject userGroup = null;
        if(groupName!=""){
            userGroup  = findGroup( groupName ) ;
        }else{
            ser1.getProperties(new ModelObject[]{user},new String[]{"default_group"});
            userGroup = user.getPropertyObject("default_group").getModelObjectValue();
        }


        if( userGroup != null )
        {

            System.out.println("................................owning group found..................................");

        }else{

            System.out.println("................  EPI-owning group not found ................");

            throw new Exception("Change ownership service: 004.Change ownership service - The configured EPI-owning group is not found in Teamcenter.");

        }



        com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner[] ownerData = new com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner[modls.length];
        for(int i = 0 ; i <modls.length ;i++) {
            com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner ownrObj = new com.teamcenter.services.strong.core._2006_03.DataManagement.ObjectOwner();

            ownrObj.object = modls[i];
            ownrObj.group = (Group) userGroup;
            ownrObj.owner = (User) user;
            ownerData[i] = ownrObj;
        }
        ServiceData returnData = ser1.changeOwnership( ownerData );

        System.out.println( "****************************** Ownership changed successfully ******************************" );

        if(returnData.sizeOfPartialErrors() > 0){

            throw new Exception("Change ownership service: 005.Change ownership service - "+returnData.getPartialError(0).getMessages()[0]);

        }

    }
    public static ModelObject findGroup(String groupName)
    {

        ImanQuery query = null;

        SavedQueryService queryService = SavedQueryService.getService(AppXSession.getConnection());

        try
        {

            SavedQuery.GetSavedQueriesResponse savedQueries = queryService.getSavedQueries();

            if (savedQueries.queries.length == 0)
            {
                return null;
            }

            for (int i = 0; i < savedQueries.queries.length; i++)
            {
                //__WEB_group -> Query in Query builder to find the group

                if (savedQueries.queries[i].name.equals("__WEB_group"))
                {
                    query = savedQueries.queries[i].query;
                    break;
                }

            }

        }
        catch (ServiceException e)
        {

            System.out.println(e.getMessage());
            return null;
        }

        if (query == null)
        {
            System.out.println("__WEB_group query not found");
            return null;
        }
        try
        {

            com.teamcenter.services.strong.query._2007_06.SavedQuery.SavedQueryInput savedQueryInput[] = new com.teamcenter.services.strong.query._2007_06.SavedQuery.SavedQueryInput[1];
            savedQueryInput[0] = new com.teamcenter.services.strong.query._2007_06.SavedQuery.SavedQueryInput();
            savedQueryInput[0].query = query;
            savedQueryInput[0].maxNumToReturn = 25;
            savedQueryInput[0].limitListCount = 0;
            savedQueryInput[0].limitList = new ModelObject[0];
            savedQueryInput[0].entries = new String[]{"Name" };//Attribute in Query to search by
            savedQueryInput[0].values = new String[1];
            savedQueryInput[0].values[0] = groupName;//Value for the search attribute
            savedQueryInput[0].maxNumToInflate = 25;

            //Execute Query to find the Group

            com.teamcenter.services.strong.query._2007_06.SavedQuery.ExecuteSavedQueriesResponse savedQueryResult = queryService.executeSavedQueries(savedQueryInput);

            com.teamcenter.services.strong.query._2007_06.SavedQuery.SavedQueryResults found = savedQueryResult.arrayOfResults[0];

            // System.out.println("Found Users:");


            ModelObject[] modelObjs = found.objects;

            return modelObjs[0];//Group object

        }
        catch (Exception e)
        {

            System.out.println(e.getMessage());

            return null;

        }

    }
}
