package com.connor.signoff.soa.handler;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.teamcenter.clientx.AppXSession;
import com.teamcenter.services.strong.administration.PreferenceManagementService;
import com.teamcenter.services.strong.administration._2012_09.PreferenceManagement;
//import com.teamcenter.services.strong.administration._2012_09.PreferenceManagement;
import com.teamcenter.services.strong.administration.*;
import com.teamcenter.services.strong.core.DataManagementService;
import com.teamcenter.services.strong.core.SessionService;
import com.teamcenter.services.strong.core._2006_03.DataManagement.CreateDatasetsResponse;
import com.teamcenter.services.loose.core._2006_03.FileManagement;
import com.teamcenter.soa.client.FileManagementUtility;
import com.teamcenter.soa.client.GetFileResponse;
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.ImanFile;
import com.teamcenter.soa.client.model.strong.Item;
import com.teamcenter.soa.client.model.strong.ItemRevision;
import com.teamcenter.soa.client.model.strong.POM_system_class;
import com.teamcenter.soa.client.model.strong.ReleaseStatus;
import com.teamcenter.soa.client.model.strong.User;
import com.teamcenter.soa.client.model.strong.WorkspaceObject;
import com.teamcenter.soa.exceptions.NotLoadedException;
import com.teamcenter.services.strong.workflow._2007_06.Workflow.ReleaseStatusInput;
import com.teamcenter.services.strong.workflow._2007_06.Workflow.ReleaseStatusOption;
import com.teamcenter.services.strong.workflow._2007_06.Workflow.SetReleaseStatusResponse;
import com.teamcenter.services.strong.workflow.WorkflowService;
import com.teamcenter.services.strong.core._2007_01.DataManagement;
public class caxaPropertyHandler {

	public static boolean debug = true;
	private static String fileName;
	private static FTPClient ftpClient = null;
	private static String exePath;//包内路径
	private static String[] refValues;//属性映射数组
	private static AppXSession session;
//	InterfaceAIFComponent[] targetComp;
	private static String caxaInfo = "";
	private static Logger logger = null;
	private static int waitPdf = 0;

	private static String releaseStatus;
	
	private static DataManagementService dmService;
	private static FileManagementUtility fmu;
	private static PreferenceManagementService tcp;
	
	private static boolean hasException = true;
	private static String companyName;
	private static String mainArgs[];
//	private static Stirng re
	/**
	 * strERR = "错误"
	 */
//	private static String strERR = "错误";
//
//	/**
//	 * 进度条工作次数
//	 */
//	private static int monitorWorkCount = 0;
//
//	public String traverseFolder(String path) {
//
//		File file = new File(path);
//		if (file.exists()) {
//			File[] files = file.listFiles();
//			if (null == files || files.length == 0) {
//				if (debug)
//					System.out.println("文件夹是空的!");
//
//			} else {
//				for (File file2 : files) {
//					if (file2.isDirectory()) {
//					} else {
//						if (file2.getAbsolutePath().toLowerCase().endsWith(".exb")) {
//							if (debug)
//								System.out.println("文件:" + file2.getAbsolutePath());
//							return file2.getAbsolutePath();
//						}
//
//					}
//				}
//			}
//		} else {
//			if (debug)
//				System.out.println("文件不存在!");
//		}
//		return "";
//
//	}
	/**
	 * 将GBK文件名转换为ISO编码格式
	 * 一般用于win系统上传文件到FTP
	 * @param fileNameGBK
	 * @return
	 */
	public static String convGBKtoISO(String fileNameGBK) {
		String filenameISO="";
		try {
			filenameISO = new String(fileNameGBK.getBytes("GBK"),"iso-8859-1");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return filenameISO;		
	}
//	
	/**
	 * 将ISO文件名转换为GBK编码格式
	 * 一般用于FTP下载文件到win系统
	 * @param fileNameGBK
	 * @return
	 */
	public static String convISOtoGBK(String fileNameISO) {
		String filenameGBK="";
		try {
			filenameGBK = new String(fileNameISO.getBytes("iso-8859-1"),"GBK");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return filenameGBK;		
	}
//
	/**
	 * 下载文件
	 * @param ref_list 
	 * @param fileOgiginName 
	 * 
	 * @param comps
	 * @return
	 * @throws TCException
	 * @throws IOException
	 */
	public static String downLoadCaxaFile(File ref_list, String fileOgiginName, Dataset comp, ItemRevision rev) {
		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 Dataset) {
//				ModelObject[] objects = {comp};
//	            dmService.refreshObjects(objects);
//	            dmService.getProperties(objects, new String[]{"ref_list"});
//	            objects = comp.get_ref_list();
//
//	            GetFileResponse getFileResponse = fmu.getFiles(objects);
//	            File[] tcFiles = getFileResponse.getFiles();
////				TCComponentTcFile[] tcFiles = ((TCComponentDataset) comp).getTcFiles();
//				File file = null;
////				if(debug)System.out.println("tcFiles:" + tcFiles.length);
//				if (tcFiles != null && tcFiles.length != 0) {
//					file = tcFiles[0];
					dmService.getProperties(new ModelObject[] {rev}, new String[] {"item_id","item_revision_id"});
					String fileName = fileOgiginName;
//					if(debug)System.out.println("fileName:" + fileName);
					String fileDix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
					String item_id = rev.getPropertyDisplayableValue("item_id");
					String item_revision_id = rev.getPropertyDisplayableValue("item_revision_id");
					String fileRealName =item_id + "-" + item_revision_id + sdf.format(new Date()) + fileDix;
					Pattern pattern = Pattern.compile("[\\s\\\\/:\\*\\?\\\"<>\\|]");
			        Matcher matcher = pattern.matcher(fileRealName);

			        fileRealName= matcher.replaceAll(""); // 将匹配到的非法字符以空替换
					
					fileName = tempPath +fileRealName;
					
					File newFile = new File(fileName);
					ref_list.renameTo(newFile);
//
//					File.copyFile(ref_list, dirFile);
//
//					if (debug)
//						System.out.println("111111111111");
					return fileName;
//				}
//			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		// }
		return value;
	}
//
//	/**
//	 * 下载文件
//	 * 
//	 * @param comps
//	 * @return
//	 * @throws TCException
//	 * @throws IOException
//	 */
//	public String downLoadFile(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(debug)System.out.println("tcFiles:" + tcFiles.length);
//				if (tcFiles != null && tcFiles.length != 0) {
//					file = tcFiles[0].getFmsFile();
//					String fileName = file.getName();
////					if(debug)System.out.println("fileName:" + fileName);
//					String fileDix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
//					fileName = tempPath + sdf.format(new Date()) + fileDix;
//					File dirFile = new File(fileName);
//
//					FileUtility.copyFile(file, dirFile);
//
//					if (debug)
//						System.out.println("11111111111");
//					return fileName;
//				}
//			}
//		} catch (TCException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		// }
//		return value;
//	}
//
	public static void caxaToPdf(Dataset component) throws Exception {
//		int messageCount=getMessage();
//		if(debug)System.out.println("当前排队数量===="+messageCount);
//		property(component);
	}

	public static void property(Dataset dataset,ItemRevision rev) {
		String workDir = System.getenv("TEMP") + File.separator + "caxaBatch";
		File workDirFile = new File(workDir);
		if (!workDirFile.exists()) {
			workDirFile.mkdirs();
		}

		try {
//			
				String fileOgiginName = "";
			    ModelObject[] objects = {dataset};
	            dmService.refreshObjects(objects);
	            dmService.getProperties(objects, new String[]{"ref_list"});
	            objects = dataset.get_ref_list();

	            GetFileResponse getFileResponse = fmu.getFiles(objects);
	            File[] ref_list = getFileResponse.getFiles();
			
//					TCComponent[] ref_list = dataset.getTCProperty("ref_list").getReferenceValueArray();
					if (ref_list.length == 0) {
//						logger.error("caxa命名引用下载失败,没有命名引用:id" + item_id + "  版本" + item_rev_id);
						caxaInfo = caxaInfo + ";" + "caxa命名引用下载失败,没有命名引用";//:id" + item_id + "  版本" + item_rev_id;
						return;
					}
					if (ref_list.length > 1) {
//						logger.error("caxa命名引用下载失败,命名引用数量大于1:id" + item_id + "  版本" + item_rev_id);
						caxaInfo = caxaInfo + ";" + "caxa命名引用下载失败,命名引用数量大于1";//:id" + item_id + "  版本" + item_rev_id;
						return;
					}
					if (ref_list.length == 1) {
//						fileOgiginName = ref_list[0].getProperty("original_file_name");
						dmService.getProperties(objects, new String[]{"original_file_name"});
						fileOgiginName = objects[0].getPropertyObject("original_file_name").getStringValue();
					}
//
					// object_name可能含有/等特殊字符，重命名为失败。还是以id+版本替换
					/*
					 * fileOgiginName=dataset.getProperty("object_name").endsWith(".exb")?dataset.
					 * getProperty("object_name"):dataset.getProperty("object_name")+".exb";
					 * fileOgiginName=dataset.getProperty("object_name").endsWith(".EXB")?dataset.
					 * getProperty("object_name"):dataset.getProperty("object_name")+".exb";
					 * fileOgiginName=dataset.getUid()+".exb";
					 */
					// TODO 先后上传caxa和xml文件到ftp，等转换后再下载下来
					String tempCaxaPath = "";
//					if (debug)
//						System.out.println("开始下载");
//					if (debug)
//						System.out.println(dataset.getProperty("object_name"));
					tempCaxaPath = downLoadCaxaFile(ref_list[0],fileOgiginName,dataset, rev);// 下载文件到temp路径下，命名为当前时间
//
					// 有可能命名引用为空，当网络不好的时候
					if (tempCaxaPath.trim().length() == 0) {
//						logger.error("caxa命名引用下载失败:id" + item_id + "  版本" + item_rev_id);
						caxaInfo = caxaInfo + ";" + "caxa命名引用下载失败";//:id" + item_id + "  版本" + item_rev_id;
						return;
					}
//					if (debug)
//						System.out.println(tempCaxaPath);
//					if (debug)
//						System.out.println("caxa下载完毕");
					File file = new File(tempCaxaPath);
//					if(file.exists()) {
//						//本地备份
//						String fileName2=dataset.getRelatedComponents("ref_list")[0].getProperty("original_file_name");
//						if(debug)System.out.println("fileName2===="+fileName2);
//						fileName2="D:\\caxaBackup\\"+fileName2;
//						SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//						fileName2=fileName2.substring(0,fileName2.lastIndexOf("."))+sdf.format(new Date())+fileName2.substring(fileName2.lastIndexOf("."));
//						File dirFile2 = new File(fileName2);
//						
//						try {
//							FileUtility.copyFile(file, dirFile2);
//						} catch (IOException e) {
//							e.printStackTrace();
//						}
//						//服务器备份
//						FileInputStream tempCaxaPathIn=null;
////						if(debug)System.out.println("desPathStr------------------"+desPathStr);
//							try {
//								tempCaxaPathIn = new FileInputStream(dirFile2);
////							in = new FileInputStream(new File(fileSS[0].getName()));
//							} catch (FileNotFoundException e) {
//								e.printStackTrace();
//							}
//							fileName2=fileName2.substring(fileName2.lastIndexOf("\\")+1);
//							boolean tempCaxa=uploadFile(ip,user,password,port,"\\caxaBackup",fileName2,tempCaxaPathIn);
//							if(tempCaxa==false) {
//								logger.error("caxa服务器备份上传失败:id"+item_id+"  版本"+item_rev_id);
//								if(debug)System.out.println("upload fail----------------");
//								return;
//							}
//					}

//				if(debug)System.out.println("下载到缓存路径完成-----------"+tempCaxaPath);
					String tempCaxaPathName = tempCaxaPath.substring(tempCaxaPath.lastIndexOf("\\") + 1);
					second(new File(tempCaxaPath));
					FileInputStream tempCaxaPathIn = null;
//				if(debug)System.out.println("desPathStr------------------"+desPathStr);
					try {
						tempCaxaPathIn = new FileInputStream(new File(tempCaxaPath));
//					in = new FileInputStream(new File(fileSS[0].getName()));
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					}
					if (debug)
						System.out.println("开始上传caxa");
					boolean tempCaxa = uploadFile(FTPUtils.ftpHost, FTPUtils.ftpUserName, FTPUtils.ftpPassword, FTPUtils.ftpPort, FTPUtils.ftpPath, tempCaxaPathName, tempCaxaPathIn);
					if (tempCaxa == false) {
//						logger.error("caxa上传失败:id" + item_id + "  版本" + item_rev_id);
						caxaInfo = caxaInfo + ";" + "caxa上传失败";//:id" + item_id + "  版本" + item_rev_id;
						if (debug)
							System.out.println("upload fail----------------");
						return;
					}
//
//					if (debug)
//						System.out.println("上传caxa完毕");
//					TCPreferenceService tcp = dataset.getSession().getPreferenceService();
					boolean jump = hx_SetCAXAFile(dataset,
							tempCaxaPathName.substring(0, tempCaxaPathName.length() - 4),fileOgiginName,rev);
					if (jump == false) {
						return;
					}
					second(new File(tempCaxaPath.replace(".exb", ".xml")));
					FileInputStream tempXmlPathIn = null;
					try {
						tempXmlPathIn = new FileInputStream(new File(tempCaxaPath.replace(".exb", ".xml")));
//					in = new FileInputStream(new File(fileSS[0].getName()));
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					}
					if (debug)
						System.out.println("上传xml");
					boolean tempXml = uploadFile(FTPUtils.ftpHost, FTPUtils.ftpUserName, FTPUtils.ftpPassword, FTPUtils.ftpPort, FTPUtils.ftpPath,
							tempCaxaPathName.replace(".exb", ".xml"), tempXmlPathIn);
					if (tempXml == false) {
//						logger.error("xml上传失败:id" + item_id + "  版本" + item_rev_id);
						caxaInfo = caxaInfo + ";" + "xml上传失败";//:id" + item_id + "  版本" + item_rev_id;
						return;
					}
//
					// 判断是否生成ok或err文件，生成说明属性映射完成，有了再下载
					if (debug)
						System.out.println("下载ok或err");
					waitOkOrErrFileCount = 0;
					boolean downResult = downOkOrErrFile(FTPUtils.ftpHost,FTPUtils.ftpPort, FTPUtils.ftpUserName, FTPUtils.ftpPassword,  FTPUtils.ftpPath, tempCaxaPathName, workDir);
					// 如果下载失败，一般ftp服务器电脑报错“请指定形文件txt。shx的位置（取消将使用设置的缺省字体）”，然后弹出资源管理器定位到“库\文档”
					if (downResult == false) {
						caxaInfo = caxaInfo + ";" + "属性映射失败";//:id" + item_id + "  版本" + item_rev_id;
						return;
					}
					// 如果成功 删除ftp上的同名txt 等待pdf生成
					if (debug)
						System.out.println("删除 ：" + tempCaxaPathName.replace(".exb", ".txt"));
					boolean getPdf = deleteTxt(FTPUtils.ftpHost,FTPUtils.ftpPort, FTPUtils.ftpUserName, FTPUtils.ftpPassword,  FTPUtils.ftpPath,tempCaxaPathName, workDir);
					if (!getPdf) {
						caxaInfo = caxaInfo + ";" + "txt删除失败";//:id" + item_id + "  版本" + item_rev_id;
						return;
					}
//
					// 替换caxa命名引用
					if (debug)
						System.out.println("下载caxa");
					count = 0;
					boolean downCaxa = downFile(FTPUtils.ftpHost,FTPUtils.ftpPort, FTPUtils.ftpUserName, FTPUtils.ftpPassword,  FTPUtils.ftpPath, tempCaxaPathName, workDir);
					if (downCaxa == false) {
						if (debug)
							System.out.println("下载caxa失败");
						caxaInfo = caxaInfo + ";" + "caxa下载失败";//:id" + item_id + "  版本" + item_rev_id;
//						logger.error("caxa下载失败:id" + item_id + "  版本" + item_rev_id);
						return;
					}

					if (new File(workDir + "\\" + fileOgiginName).exists()) {
						new File(workDir + "\\" + fileOgiginName).delete();
					}
					// 有可能包含特殊字符和重名
					boolean caxaFile = new File(workDir + "\\" + tempCaxaPathName)
							.renameTo(new File(workDir + "\\" + fileOgiginName));
					if (caxaFile == false) {
						caxaInfo = caxaInfo + ";" + "重命名失败";//:id" + item_id + "  版本" + item_rev_id;
//						logger.error("重命名失败:id" + item_id + "  版本" + item_rev_id);
						return;
					}
					if (debug)
						System.out.println("替换命名引用");
					// 替换命名引用
//					try {
//					TcUtils.
//						ChangeDbomUtil.setByPass(true);
//					} catch (TCException e2) {
//						e2.printStackTrace();
//					}
//					try {
//					if(debug)System.out.println(tempCaxaPath);
					TcUtils.setByPass(true);
					//2023-11-15 liujb 添加补偿机制 start
					File tcFileToFile = TCFileToFile(dataset);
					File exbFile = new File("D:\\TEMP\\fcc_tmp"+ "\\" + fileOgiginName);
					if (exbFile.exists()) {
						exbFile.delete();
					}
					boolean caxaFile2 = tcFileToFile.renameTo(exbFile);
					String fileName = exbFile.getPath()+"@"+rev.getUid()+"#"+dataset.getUid()+"#"+releaseStatus;
					File lockFile = new File(fileName);
					
					boolean createNewFile = lockFile.createNewFile();
					
//					if(checkFile("CaxaToPDF.lock",new File(exePath))) {
//						return true;
//					}
					updateDataSet(dataset, workDir + "\\" + fileOgiginName,"HX3_exb");
					exbFile.delete();
					lockFile.delete();
					TcUtils.setByPass(false);
					//dataset.setFiles(new String[] { workDir + "\\" + fileOgiginName }, new String[] { "HX3_exb" });
//						sendMail("成功",item_id);
//					} catch (Exception e) {
//						e.printStackTrace();
//
//						try {
//							if (debug)
//								System.out.println("替换caxa失败，关旁路");
//							ChangeDbomUtil.setByPass(false);
//						} catch (TCException e2) {
//							e2.printStackTrace();
//						}
//
//						sendMail("替换caxa失败:" + e.getLocalizedMessage() + e.getMessage(), item_id);
////					return;//如果用户签出了数据集就会替换失败
//					}
					if (debug)
						System.out.println("替换caxa成功，关旁路id");//" + item_id + "  版本" + item_rev_id);
//					logger.error("替换caxa成功，关旁路id" + item_id + "  版本" + item_rev_id);
//					try {
//						ChangeDbomUtil.setByPass(false);
//					} catch (TCException e2) {
//						e2.printStackTrace();
//					}
					// 替换pdf命名引用
					if (debug)
						System.out.println("开始下载pdf");
					boolean sucess = downFile(FTPUtils.ftpHost,FTPUtils.ftpPort, FTPUtils.ftpUserName, FTPUtils.ftpPassword,  FTPUtils.ftpPath,
							tempCaxaPathName.replace(".exb", ".pdf"), workDir);
					if (sucess == false) {
						// TODO 加入日志
						System.out.println();
//						logger.error("error:id:" + item_id + "版本:" + item_rev_id + "pdf下载异常，请重新处理");
//						continue;
					}
					
					
//						if (debug)
//							System.out.println("包内路径-----------------" + path);
	//					String exePath = path.substring(1, path.indexOf("com.connor.signoff")).replace("/", "\\");
						
					
//						if (debug)
//							System.out.println("受控章位置---------------》" + imgPath[0]);
						boolean action = false;
						String addPdfPath = "";
						try {
							// if(debug)System.out.println("designType--------"+designType);
							// if(debug)System.out.println(System.getenv("TEMP")+File.separator+fileName+".pdf");
							// if(debug)System.out.println(System.getenv("TEMP")+File.separator+oldName);
							// action=addPdfMark(arg1+File.separator+fileName.replace(".exb",
							// ".pdf"),arg1+File.separator+oldName+".pdf",imgPath, designType);
							
							// 先要签章
							String item_id = rev.get_item_id();
							String item_rev_id = rev.get_item_revision_id();
							if("HX".equals(FTPUtils.CompanyName)) {
								String designType = rev.getTypeObject().getName();
								String[] imgPath = new String[1];
								
								String path = caxaPropertyHandler.class.getProtectionDomain().getCodeSource().getLocation().getPath();
								path = path.replace("%20", " ");
								String exePath = new File(path).getParent() + "//";
								String qianzhang = rev.getPropertyDisplayableValue("hx3_qianzhang").trim();
								if(qianzhang.equals("受控") || qianzhang.equals("B") || qianzhang.isEmpty()) {
									
									exePath = exePath + "skz.png";
								}
								else {
									exePath = exePath + "syz.png";
								
							}
			
							imgPath[0] = exePath;
							item_id = newString(item_id);
							
								
							action = addPdfMark(workDir + File.separator + tempCaxaPathName.replace(".exb", ".pdf"),
										workDir + File.separator + item_id + item_rev_id + ".pdf", imgPath, designType);
							}
							// 由于pdf尺寸不合模板，可能添加受控章失败，这时就把原来的pdf替换上去
							if (action == false) {
								
								addPdfPath = workDir + File.separator+tempCaxaPathName.replace(".exb", ".pdf");//workDir + File.separator + fileName.replace(".exb", ".pdf");
							
							} else {
	
								addPdfPath = workDir + File.separator + item_id + item_rev_id + ".pdf";
							}
						} catch (Exception e) {
							// 3表示添加图片异常
							String HXC_STATUS = "3";
	//						refreshDataBase( HXC_STATUS,  item_id_origin, item_revision_id_origin, rs_get,  stmt, sdf0);
							e.printStackTrace();
							addPdfPath = workDir + File.separator+tempCaxaPathName.replace(".exb", ".pdf");
	//						continue;
						}
					
					// 先要签章
//					String designType = rev.getType();
//					String[] imgPath = new String[1];
//
//					String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
//					if (debug)
//						System.out.println("包内路径-----------------" + path);
//					String exePath = path.substring(1, path.indexOf("com.connor.signoff")).replace("/", "\\");
//					String qianzhang = rev.getProperty("hx3_qianzhang").trim();
//					if(qianzhang.equals("受控") || qianzhang.equals("B") || qianzhang.isEmpty()) {
//						
//						exePath = exePath + "skz.png";
//					}
//					else {
//						exePath = exePath + "syz.png";
//					
//					}
//
//					imgPath[0] = exePath;
//					if (debug)
//						System.out.println("受控章位置---------------》" + imgPath[0]);
//					boolean action = false;
					//String addPdfPath = "";
//					try {
//						// if(debug)System.out.println("designType--------"+designType);
//						// if(debug)System.out.println(System.getenv("TEMP")+File.separator+fileName+".pdf");
//						// if(debug)System.out.println(System.getenv("TEMP")+File.separator+oldName);
//						// action=addPdfMark(arg1+File.separator+fileName.replace(".exb",
//						// ".pdf"),arg1+File.separator+oldName+".pdf",imgPath, designType);
//
//						item_id = newString(item_id);
//						if("HX".equals(FTPUtils.CompanyName)) {
//							
//							action = addPdfMark(workDir + File.separator + tempCaxaPathName.replace(".exb", ".pdf"),
//									workDir + File.separator + item_id + item_rev_id + ".pdf", imgPath, designType);
//						}
//						// 由于pdf尺寸不合模板，可能添加受控章失败，这时就把原来的pdf替换上去
//						if (action == false) {
							//addPdfPath = workDir + File.separator+tempCaxaPathName.replace(".exb", ".pdf");//workDir + File.separator + fileName.replace(".exb", ".pdf");
//						} else {
//
//							addPdfPath = workDir + File.separator + item_id + item_rev_id + ".pdf";
//						}
//					} catch (Exception e) {
//						// 3表示添加图片异常
//						String HXC_STATUS = "3";
////						refreshDataBase( HXC_STATUS,  item_id_origin, item_revision_id_origin, rs_get,  stmt, sdf0);
//						e.printStackTrace();
//						continue;
//					}
					// 替换或者新建数据集
					replaceOrcreate(dataset, rev, addPdfPath);
					System.out.println("addPdfPath:"+addPdfPath);
					// 删除文件夹下的所有文件
//					deleteDirectory(workDir);
//				}
//			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
 //
	private static boolean deleteTxt(String url, // FTP服务器hostname
			int port, // FTP服务器端口
			String username, // FTP登录账号
			String password, // FTP登录密码
			String remotePath, // FTP服务器上的相对路径
			String fileName, // 要下载的文件名
			String localPath// 下载后保存到本地的路径

	) {

		boolean success = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(url, port);
			// 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(username, password);// 登录
//            ftp.login("anonymous", null);// 登陆FTP服务器
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			ftp.enterLocalPassiveMode();// 不用这句，有些电脑打开了防火墙就会在ftp.listFiles()这里卡住
//            if(debug)System.out.println("aaa");
			boolean ftpchange = ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
			fileName = fileName.replace(".exb", ".txt");
			ftp.setControlEncoding("GBK"); //FTP 中文支持
			fileName = convGBKtoISO(fileName);//FTP 中文支持
			int flag = ftp.dele(fileName);
			success = true;

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return success;

	}
static int count = 0;// 半秒
//
	public static FTPFile[] waitPdf(FTPClient ftp, String fileName, String errorName, String okName) {
		FTPFile[] fs = null;
		try {

			fs = ftp.listFiles();
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		for (FTPFile ff : fs) {
			//2023.04.06如果找到.ok即为成功，.error即为失败不用再找了
			//FTP中文支持
			String ffName = convISOtoGBK(ff.getName());
			if (ffName.equals(okName)) {
				System.out.println("find the pdf...");
				return fs;
			} else if (ffName.equals(errorName)) {
				System.out.println("转换异常");
				return null;
			}
		}
		System.out.println("waitPdf---count:" + count);
		System.out.println("waitPdf----waitPdf:" + waitPdf);
		try {
			Thread.sleep(1000);
			count++;
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		// 如果超时，退出
		if (count > waitPdf) {
			return null;
		}
		fs = waitPdf(ftp, fileName, errorName, okName);
		return fs;
	}
//
	public static boolean downOkOrErrFile(String url, // FTP服务器hostname
			int port, // FTP服务器端口
			String username, // FTP登录账号
			String password, // FTP登录密码
			String remotePath, // FTP服务器上的相对路径
			String fileName, // 要下载的文件名
			String localPath// 下载后保存到本地的路径

	) {
		boolean success = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(url, port);
			// 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(username, password);// 登录
//            ftp.login("anonymous", null);// 登陆FTP服务器
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			ftp.enterLocalPassiveMode();// 不用这句，有些电脑打开了防火墙就会在ftp.listFiles()这里卡住
//            if(debug)System.out.println("aaa");
			boolean ftpchange = ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
//            if(debug)System.out.println(ftpchange);
//            FTPFile[] fs = ftp.listFiles(); 
			String errorNamePrefix = "";
			if (fileName.toLowerCase().endsWith(".exb")) {
				errorNamePrefix = fileName;
			}

			FTPFile[] fs = waitOkOrErrFile(ftp, fileName, errorNamePrefix);
			if (fs != null) {
				success = true;
			} else {
				success = false;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return success;
	}

//
	public static FTPFile[] waitOkOrErrFile(FTPClient ftp, String fileName, String errorNamePrefix) {
		FTPFile[] fs = null;
		try {

			fs = ftp.listFiles();
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		for (FTPFile ff : fs) {
			// 2023.04.06如果找到.ok即为成功，.error即为失败不用再找了
			// FTP中文支持
			String ffName = convISOtoGBK(ff.getName());
			if (ffName.equals(errorNamePrefix + ".ok")) {
				System.out.println("映射成功...");
				return fs;
			} else if (ffName.equals(errorNamePrefix + ".err")) {
				System.out.println("映射异常");
				return null;
			}
		}
		if (debug)
			System.out.println("waitOkOrErrFile---" + errorNamePrefix);
		try {
			Thread.sleep(1000);
			waitOkOrErrFileCount++;
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		// 如果超时，退出
		if (waitOkOrErrFileCount > waitPdf) {
			return null;
		}
		fs = waitOkOrErrFile(ftp, fileName, errorNamePrefix);
		return fs;
	}
//
	static	int waitOkOrErrFileCount = 0;
//
	/**
	 * 获取属性
	 * 
	 * @param comp
	 * @return
	 */
	public static String hx_GetProp(ModelObject comp, String refInfo) {
		if (comp == null) {
			return null;
		}
		if (refInfo == null) {
			return null;
		}
		try {
			dmService.getProperties(new ModelObject[] {comp}, new String[] {refInfo});
			return comp.getPropertyDisplayableValue(refInfo);
//			return comp.getProperty(refInfo);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}
	
    public static String toUpperCase(String input) {
        if (input == null) {
            return null;
        }

        int length = input.length();
        StringBuilder result = new StringBuilder(length);

        for (int i = 0; i < length; i++) {
            char c = input.charAt(i);
            if (c >= 'a' && c <= 'z') {
                // 将小写字母转换为大写字母
                c = (char) (c - 32);
            }
            result.append(c);
        }

        return result.toString();
    }
//
	/**
	 * 处理宏协的CAXA数据集打开前操作
	 * 
	 * @param caxaDataset
	 * @param rev 
	 * @throws TCException
	 */
	public static boolean hx_SetCAXAFile(Dataset caxaDataset, String xmlName,String datasetName, ItemRevision rev)
			throws Exception {
		try {
			StringBuffer infoSB = new StringBuffer();
//			TCComponentItemRevision rev = null;
//			TCComponentItem item = null;
//			TCComponentForm revForm = null;
//			TCComponentForm itemForm = null;
			String path = caxaPropertyHandler.class.getProtectionDomain().getCodeSource().getLocation().getPath();
			path = path.replace("%20", " ");
			String exePath = new File(path).getParent() + "//";

			SAXReader reader = new SAXReader();
			Document doc = reader.read(new File(exePath + "sign.xml"));
			Element root = doc.getRootElement();
			Element title = root.element("SignInfo").element("Title");
			Element files = root.element("SignInfo").element("Files").element("File");
//			files.attribute("Path").setValue("D:\\CAXAPROPERTY\\" + xmlName + ".exb");
			files.attribute("Path").setValue(FTPUtils.ftpPath + "\\" + xmlName + ".exb");
			String blockName = files.attributeValue("BlockName");
			Map<String, String> valueMap = getECNValueMap(rev);
//			String datasetName = null;
//			if (caxaDataset == null) {
//				return false;
//			}
//			TCComponentTcFile[] tcFiles = caxaDataset.getTcFiles();
//			// File file = null;
//			if (tcFiles != null && tcFiles.length != 0) {
//
//				datasetName = tcFiles[0].getStringProperty("object_string");
//			}
			datasetName = datasetName.substring(0, datasetName.indexOf('.'));
			File file = new File(System.getenv("TEMP") + "\\" + xmlName + ".xml");
//			rev = (TCComponentItemRevision) caxaDataset.getReferenceProperty("item_revision");// 获得当前数据集所在版本对象
//
//			if (rev == null) {
//				return false;
//			}
//			try {
			dmService.getProperties(new ModelObject[] {rev}, new String[] {"IMAN_master_form_rev"});
				ModelObject revForm = rev.get_IMAN_master_form_rev()[0];
//				revForm = (TCComponentForm) (rev.getReferenceListProperty("IMAN_master_form_rev"))[0];
//			} catch (Exception e1) {
//				e1.printStackTrace();
//				return false;
//			}
			Item item = rev.get_items_tag();
			
			String[] refValues = null;//tcp.getStringArray(TCPreferenceService.TC_preference_site, "HxCaxaMapping");
			
			PreferenceManagement.GetPreferencesResponse getAttrMappingPreferencesResponse = tcp.getPreferences(new String[] {"HxCaxaMapping"}, true);
			for(PreferenceManagement.CompletePreference completePreference : getAttrMappingPreferencesResponse.response) {

	            if(completePreference.definition.name.equals("HxCaxaMapping")){
	            	refValues = completePreference.values.values;
	            }
	        }
			
			if (refValues == null || refValues.length == 0) {

				return false;
			}
//			if(debug)System.out.println("rev:" + rev);
			String propName;
			int index;
//			Map<TCComponent, List<String>> map = new HashMap<>();// 存放对象和对象属性集合

			
			List<String> itemPropList = new ArrayList<String>();
			List<String> itemRevPropList = new ArrayList<String>();
			List<String> itemRevMasterPropList = new ArrayList<String>();
			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;
				}
				index = valueS[0].indexOf(':');
				propName = valueS[0].substring(index + 1).trim();
//				switch (toUpperCase(propNameS[0])) {
//				case "ITEM":
//					if(!itemPropList.contains(propNameS[1])) {
//						
//						itemPropList.add(propNameS[1]);
//					}
////					value = hx_GetProp(item, propNameS[1]);
////					map = addToMap(map, item, propNameS[1]);
//
//					break;
//				case "REV":
//					if(!itemRevPropList.contains(propNameS[1])) {
//						
//						itemRevPropList.add(propNameS[1]);
//					}
////					value = hx_GetProp(rev, propNameS[1]);
////					map = addToMap(map, rev, propNameS[1]);
//					break;
//				case "REVMASTER":
//					if(!itemRevMasterPropList.contains(propNameS[1])) {
//						
//						itemRevMasterPropList.add(propNameS[1]);
//					}
////					value = hx_GetProp(revForm, propNameS[1]);
////					map = addToMap(map, revForm, propNameS[1]);
//					break;
//				case "ITEMMASTER":
//					break;
//				default:
//					break;
//				}
				String propNameS0Upper = toUpperCase(propNameS[0]);

				if ("ITEM".equals(propNameS0Upper)) {
				    if (!itemPropList.contains(propNameS[1])) {
				        itemPropList.add(propNameS[1]);
				    }
				    // value = hx_GetProp(item, propNameS[1]);
				    // map = addToMap(map, item, propNameS[1]);
				} else if ("REV".equals(propNameS0Upper)) {
				    if (!itemRevPropList.contains(propNameS[1])) {
				        itemRevPropList.add(propNameS[1]);
				    }
				    // value = hx_GetProp(rev, propNameS[1]);
				    // map = addToMap(map, rev, propNameS[1]);
				} else if ("REVMASTER".equals(propNameS0Upper)) {
				    if (!itemRevMasterPropList.contains(propNameS[1])) {
				        itemRevMasterPropList.add(propNameS[1]);
				    }
				    // value = hx_GetProp(revForm, propNameS[1]);
				    // map = addToMap(map, revForm, propNameS[1]);
				} else if ("ITEMMASTER".equals(propNameS0Upper)) {
				    // No action needed for "ITEMMASTER"
				} else {
				    // Default case
				}
//				infoSB.append(valueS[0]).append("=").append(value).append("|");
				
			}
			if(itemPropList.size()!=0) {
				String[] itemProps = itemPropList.toArray(new String[itemPropList.size()]);
				dmService.getProperties(new ModelObject[] {item}, itemProps);
			}
			if(itemRevPropList.size()!=0) {
				String[] itemRevProps = itemRevPropList.toArray(new String[itemRevPropList.size()]);
				dmService.getProperties(new ModelObject[] {rev}, itemRevProps);
			}
			if(itemRevMasterPropList.size()!=0) {
				String[] itemRevMasterProps = itemRevMasterPropList.toArray(new String[itemRevMasterPropList.size()]);
				dmService.getProperties(new ModelObject[] {revForm}, itemRevMasterProps);
			}
			dmService.refreshObjects(new ModelObject[] {item,rev,revForm});
			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;
				}
				index = valueS[0].indexOf(':');
				propName = valueS[0].substring(index + 1).trim();
				if(propName.equals("设计人员")) {
					System.out.println();
				}
				if(valueMap.containsKey(propName)) {
					continue;
				}
				String propNameS0Upper = toUpperCase(propNameS[0]);

				if ("ITEM".equals(propNameS0Upper)) {
				    value = hx_GetProp(item, propNameS[1]);
				    // map = addToMap(map, item, propNameS[1]);
				} else if ("REV".equals(propNameS0Upper)) {
				    boolean flag = false;
				    String[] propertyNames = rev.getPropertyNames();
				    for (String prop : propertyNames) {
				        if (prop.equals(propNameS[1]) && !valueMap.containsKey(prop)) {
				            flag = true;
				            break;
				        }
				    }
				    if (flag) {
				        value = hx_GetProp(rev, propNameS[1]);
				    }
				    // map = addToMap(map, rev, propNameS[1]);
				} else if ("REVMASTER".equals(propNameS0Upper)) {
				    boolean flag2 = false;
				    String[] propertyNames2 = revForm.getPropertyNames();
				    for (String prop : propertyNames2) {
				        if (prop.equals(propNameS[1]) && !valueMap.containsKey(prop)) {
				            flag2 = true;
				            break;
				        }
				    }
				    if (flag2) {
				        value = hx_GetProp(revForm, propNameS[1]);
				    }
				    // map = addToMap(map, revForm, propNameS[1]);
				} else if ("ITEMMASTER".equals(propNameS0Upper)) {
				    // No action needed for "ITEMMASTER"
				} else {
				    // Default case
				}
//				switch (toUpperCase(propNameS[0])) {
//				case "ITEM":
//					value = hx_GetProp(item, propNameS[1]);
////					map = addToMap(map, item, propNameS[1]);
//
//					break;
//				case "REV":
//					boolean flag = false;
//					String[] propertyNames = rev.getPropertyNames();
//					for(String prop : propertyNames) {
//						if(prop.equals(propNameS[1]) && !valueMap.containsKey(prop)) {
//							flag = true;
//						}
//					}
//					if(flag) {
//						
////						value = hx_GetProp(revForm, propNameS[1]);
//						value = hx_GetProp(rev, propNameS[1]);
//					}
////					map = addToMap(map, rev, propNameS[1]);
//					break;
//				case "REVMASTER":
//					boolean flag2 = false;
//					String[] propertyNames2 = revForm.getPropertyNames();
//					for(String prop : propertyNames2) {
//						if(prop.equals(propNameS[1]) && !valueMap.containsKey(prop)) {
//							flag2 = true;
//						}
//					}
//					if(flag2) {
//						
//						value = hx_GetProp(revForm, propNameS[1]);
//					}
////					map = addToMap(map, revForm, propNameS[1]);
//					break;
//				case "ITEMMASTER":
//					break;
//				default:
//					break;
//				}
				if (value == null  || value.length() == 0)
					continue;
				valueMap.put(propName, value);
			}
//			for (Map.Entry<TCComponent, List<String>> me : map.entrySet()) {
//				TCComponent component = me.getKey();
//				List<String> propList = me.getValue();
//				String[] proptring = propList.toArray(new String[propList.size()]);
//				String[] values = component.getProperties(proptring);
//				for (int i = 0; i < proptring.length; i++) {
//					valueMap.put(proptring[i], values[i]);
//				}
//
//			}

			// files.attribute("Path").setValue(dir+"\\"+fileName);
//			if(debug)System.out.println("valueMap:" + valueMap);
			Element e;
			Iterator it = title.elementIterator();
			while (it.hasNext()) {
				e = (Element) it.next();
				String val = valueMap.get(e.attribute("Name").getValue());
//				if(debug)System.out.println("name:" + e.attribute("Name").getValue());
//				if(debug)System.out.println("val:" + val);
				if (val != null)
					e.attribute("Value").setValue(val);
			}
			PrintWriter pw = new PrintWriter(file, "UTF-8");
			doc.write(pw);
			pw.close();
//			if(debug)System.out.println("222");
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return true;

	}
//
//	private Map<TCComponent, List<String>> addToMap(Map<TCComponent, List<String>> map, TCComponent item,
//			String propName) {
//		if (map.containsKey(item)) {
//			List<String> list = map.get(item);
//			list.add(propName);
//			map.put(item, list);
//		} else {
//			List<String> list = new ArrayList<>();
//			list.add(propName);
//			map.put(item, list);
//		}
//		return map;
//	}
//
	public static void second(File file) {
		if (!file.exists()) {
			if (debug)
				System.out.println("second");
			try {
				Thread.sleep(200);
				second(file);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		} else {
			if (debug)
				System.out.println("cunzai");
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
//
	/**
	 * 删除单个文件
	 *
	 * @param fileName 要删除的文件的文件名
	 * @return 单个文件删除成功返回true，否则返回false
	 */
	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		// 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
		if (file.exists() && file.isFile()) {
			if (file.delete()) {
//				if(debug)System.out.println("删除单个文件" + fileName + "成功！");
				return true;
			} else {
//				if(debug)System.out.println("删除单个文件" + fileName + "失败！");
				return false;
			}
		} else {
//			if(debug)System.out.println("删除单个文件失败：" + fileName + "不存在！");
			return false;
		}
	}
//	
//
	/**
	 * 删除目录及目录下的文件
	 *
	 * @param dir 要删除的目录的文件路径
	 * @return 目录删除成功返回true，否则返回false
	 */
	public static boolean deleteDirectory(String dir) {
		// 如果dir不以文件分隔符结尾，自动添加文件分隔符
		if (!dir.endsWith(File.separator))
			dir = dir + File.separator;
		File dirFile = new File(dir);
		// 如果dir对应的文件不存在，或者不是一个目录，则退出
		if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
//			if(debug)System.out.println("删除目录失败：" + dir + "不存在！");
			return false;
		}
		boolean flag = true;
		// 删除文件夹中的所有文件包括子目录
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			// 删除子文件
			if (files[i].isFile()) {
				flag = deleteFile(files[i].getAbsolutePath());
				if (!flag)
					break;
			}
			// 删除子目录
			else if (files[i].isDirectory()) {
				flag = deleteDirectory(files[i].getAbsolutePath());
				if (!flag)
					break;
			}
		}
		if (!flag) {
//			if(debug)System.out.println("删除目录失败！");
			return false;
		}
		return true;
	}
//
	// 获取配置中等待pdf转换超时的时间
	private static void loadWaitPdf() {
		Properties properties = new Properties();
		InputStream is = null;
//		is = this.getClass().getResourceAsStream("PDFInfo.properties");
		is =  caxaPropertyHandler.class.getResourceAsStream("PDFInfo.properties");
		try {
			properties.load(is);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		waitPdf = Integer.valueOf(properties.getProperty("WAITPDF"));
		System.out.println();
	}
//
//	private void dealWithFolder(TCComponent tcComponent) throws TCException {
//		if (tcComponent instanceof TCComponentFolder) {
//			TCComponentFolder folder = (TCComponentFolder) tcComponent;
//			TCComponent[] contents = null;
//			try {
//				contents = folder.getRelatedComponents("contents");
//			} catch (TCException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			for (int j = 0; j < contents.length; j++) {
//				TCComponent content = contents[j];
//				if (content instanceof TCComponentFolder) {
//					dealWithFolder(content);
//				} else if (content instanceof TCComponentItem) {
//					TCComponentItemRevision rev = ((TCComponentItem) content).getLatestItemRevision();
//					caxaToPdf(rev, logger);
//				} else if (content instanceof TCComponentItemRevision) {
//					caxaToPdf((TCComponentItemRevision) content, logger);
//				}
//			}
//		}
//
//	}
//
	/**
	 * 获取FTPClient对象
	 *
	 * @param ftpHost     FTP主机服务器
	 * @param ftpPassword FTP 登录密码
	 * @param ftpUserName FTP登录用户名
	 * @param ftpPort     FTP端口 默认为21
	 * @return
	 */
	public static FTPClient getFTPClient(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort) {
		FTPClient ftpClient = new FTPClient();
		try {
			ftpClient = new FTPClient();
			ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
			ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
//            ftpClient.login("anonymous", null);// 登陆FTP服务器
			if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
				if (debug)
					System.out.println("未连接到FTP，用户名或密码错误。");
				ftpClient.disconnect();
			} else {
//                if(debug)System.out.println("FTP连接成功。");
			}
		} catch (SocketException e) {
			e.printStackTrace();
			if (debug)
				System.out.println("FTP的IP地址可能错误，请正确配置。");
		} catch (IOException e) {
			e.printStackTrace();
			if (debug)
				System.out.println("FTP的端口错误,请正确配置。");
		}
		return ftpClient;
	}
//
	/**
	 * Description: 向FTP服务器上传文件
	 * 
	 * @param ftpHost     FTP服务器hostname
	 * @param ftpUserName 账号
	 * @param ftpPassword 密码
	 * @param ftpPort     端口
	 * @param ftpPath     FTP服务器中文件所在路径 格式： ftptest/aa
	 * @param fileName    ftp文件名称
	 * @param in          文件流
	 * @return 成功返回true，否则返回false
	 */
	public static boolean uploadFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, String ftpPath,
			String fileName, FileInputStream in) {
		boolean success = false;
		FTPClient ftpClient = null;
		try {
			int reply;
			ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
			reply = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect();
				return success;
			}
			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftpClient.enterLocalPassiveMode();
			ftpClient.changeWorkingDirectory(ftpPath);
			
			ftpClient.setControlEncoding("GBK"); // FTP中文支持
			fileName = convGBKtoISO(fileName);// FTP中文支持
			////fileName = convISOtoGBK(fileName);// FTP中文支持
			
			boolean ff = ftpClient.storeFile(fileName, in);	
			String str = ftpClient.getReplyString();
			in.close();
			ftpClient.logout();
			success = true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
//        if(debug)System.out.println("上传完成");
		return success;
	}
//
//	public String GetNowDate() {
//		String temp_str = "";
//		Date dt = new Date();
//		// 最后的aa表示“上午”或“下午” HH表示24小时制 如果换成hh表示12小时制 "yyyy-MM-ddHH:mm:ss aa"
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
//		temp_str = sdf.format(dt);
//		return temp_str;
//	}
//
//	/*
//	 * 实现文件的拷贝
//	 * 
//	 * @param srcPathStr 源文件的地址信息
//	 * 
//	 * @param desPathStr 目标文件的地址信息
//	 */
//	private String copyFile(String srcPathStr, String desPathStr, String newName) {
//		// 1.获取源文件的名称
//		String newFileName = newName + srcPathStr.substring(srcPathStr.lastIndexOf(".")); // 目标文件地址
////        if(debug)System.out.println(newFileName);
////        if(debug)System.out.println(File.separator);
//		desPathStr = desPathStr + File.separator + newFileName; // 源文件地址
////        if(debug)System.out.println(desPathStr);
//
//		try {
//			// 2.创建输入输出流对象
//			FileInputStream fis = new FileInputStream(srcPathStr);
//			FileOutputStream fos = new FileOutputStream(desPathStr);
//
//			// 创建搬运工具
//			byte datas[] = new byte[1024 * 8];
//			// 创建长度
//			int len = 0;
//			// 循环读取数据
//			while ((len = fis.read(datas)) != -1) {
//				fos.write(datas, 0, len);
//			}
//			// 3.释放资源
//			fis.close();
//			fis.close();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return desPathStr;
//	}
//
	public static boolean downFile(String url, // FTP服务器hostname
			int port, // FTP服务器端口
			String username, // FTP登录账号
			String password, // FTP登录密码
			String remotePath, // FTP服务器上的相对路径
			String fileName, // 要下载的文件名
			String localPath// 下载后保存到本地的路径

	) {
		if (debug)
			System.out.println("下载");
		boolean success = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(url, port);
			// 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(username, password);// 登录
//            ftp.login("anonymous", null);// 登陆FTP服务器
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				if (debug)
					System.out.println("断开");
				ftp.disconnect();
				return success;
			}
//            if(debug)System.out.println("aaa");
			ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
//            FTPFile[] fs = ftp.listFiles();  
			int x = 0;
			if (debug)
				System.out.println("等待pdf");
			String errorName = fileName + ".err";
			String okName = fileName + ".ok";
			FTPFile[] fs = waitPdf(ftp, fileName, errorName, okName);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (fs == null) {
				return false;
			}
			ftp.setControlEncoding("GBK");
			for (FTPFile ff : fs) {
				// FTP中文支持
				String ffName = convISOtoGBK(ff.getName());
				if (ffName.equals(fileName)) {
					if (debug)
						System.out.println("有文件----------" + fileName);
//                 if(debug)System.out.println("dd");
					File localFile = new File(localPath + "/" + ffName);
					OutputStream is = new FileOutputStream(localFile);
					ftp.retrieveFile(ff.getName(), is);
//                    if(debug)System.out.println("ccc" +ff.getName()+fileName);
					is.close();
					success = true;
					break;//2023-04-12跳出循环
				}
			}
			ftp.logout();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return success;
	}
//
	/**
	 * 获取PDF的尺寸和图框的匹配并返回需要插入图片的位置
	 * 
	 * @param rectangle
	 * @return
	 */
	public static Float[] getSize(Rectangle rectangle) {
		Float[] sizef = new Float[2];
		float toleft = rectangle.getLeft();
		float tobottom = rectangle.getBottom();
		float toright = rectangle.getRight();
		float totop = rectangle.getTop();

		JFomPdfBean bean = new JFomPdfBean();
		bean.setH(toright - toleft);// PDF的宽
		bean.setW(totop - tobottom);// PDF的高
		sizef[0] = bean.getH();
		sizef[1] = bean.getW();
//		if(debug)System.out.println("bean.getH------------>" + bean.getH());
//		if(debug)System.out.println("bean.getW------------>" + bean.getW());

		return sizef;
	}

	public static boolean addPdfMark(String InPdfFile, String temp, String[] markImagePath, String designType)
			throws Exception {
		File pdffile = new File(temp);
		if (pdffile.exists()) {
			pdffile.delete();
		}
		// 插入坐标
		Properties properties = new Properties();
		InputStream is = null;
		is = caxaPropertyHandler.class.getResourceAsStream("PDFInfo.properties");
		properties.load(is);
		System.out.println(2);
		// PDF 输入文件
		PdfReader reader = new PdfReader(InPdfFile, "PDF".getBytes());
		// PDF 输出文件
		PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(temp));
		// 水印图片
		Image[] img = null;
		for (int j = 0; j < markImagePath.length; j++) {
//			img.scaleAbsolute(35, 20);// 缩放图片
//			float imgW = img.getScaledWidth();// 获取图片的宽度
//			float imgH = img.getScaledHeight();// 获取图片的高度
			// 获取PDF的页数
			int pageSize = reader.getNumberOfPages();// 获取输入文件的页数
			for (int i = 1; i <= pageSize; i++) {
				Rectangle rectangle = reader.getPageSize(i);
				Float[] fposition = getSize(rectangle);
//				if(debug)System.out.println("fposition[0]======="+fposition[0]);
//				if(debug)System.out.println("fposition[1]======="+fposition[1]);
				boolean isSizeOk = false;
				// 设置水印的插入位置A0
				if ((fposition[0] > 3300 && fposition[1] > 2300)) {
					isSizeOk = true;
					// 通过pdf所在的版本类型判断坐标参数
//					if(debug)System.out.println("进入设置水印的插入位置A0");
					String[] sizeType = selectType("A0", designType);
					if (sizeType == null || sizeType.length == 0) {
						return false;
					}
					img = setPic(img, sizeType, properties, markImagePath[j]);
				}
				// TODO 设置水印的插入位置A1
				if ((fposition[0] > 2300 && fposition[1] > 1600) && isSizeOk == false) {
					isSizeOk = true;
//					if(debug)System.out.println("进入设置水印的插入位置A1");
					String[] sizeType = selectType("A1", designType);
					if (sizeType == null || sizeType.length == 0) {
						return false;
					}
					
					img = setPic(img, sizeType, properties, markImagePath[j]);
					
				}

				// TODO 设置水印的插入位置A2
				if ((fposition[1] > 1100 && fposition[0] > 1600) && isSizeOk == false) {
					isSizeOk = true;
//					if(debug)System.out.println("进入设置水印的插入位置A2");
					String[] sizeType = selectType("A2", designType);
					if (sizeType == null || sizeType.length == 0) {
						return false;
					}
					img = setPic(img, sizeType, properties, markImagePath[j]);
				}
				// TODO 设置水印的插入位置A2
				if ((fposition[0] > 1100 && fposition[1] > 1600) && isSizeOk == false) {
					isSizeOk = true;
//					if(debug)System.out.println("进入设置水印的插入位置A2_GY");
					String[] sizeType = selectType("A2", designType);
					if (sizeType == null || sizeType.length == 0) {
						return false;
					}
					img = setPic(img, sizeType, properties, markImagePath[j]);
				}
				// TODO 设置水印的插入位置A3
				if ((fposition[0] > 1100 && fposition[1] > 800) && isSizeOk == false) {
					isSizeOk = true;
//					if(debug)System.out.println("进入设置水印的插入位置A3");
					String[] sizeType = selectType("A3", designType);
					if (sizeType == null || sizeType.length == 0) {
						return false;
					}
					img = setPic(img, sizeType, properties, markImagePath[j]);
				}
				// TODO 设置水印的插入位置A3H 
				if ((fposition[1] > 1100 && fposition[0] > 800) && isSizeOk == false) {
					isSizeOk = true;
//					if(debug)System.out.println("进入设置水印的插入位置A3");
					String[] sizeType = selectType("A3H", designType);
					if (sizeType == null || sizeType.length == 0) {
						return false;
					}
					img = setPic(img, sizeType, properties, markImagePath[j]);
				}
				// TODO 设置水印的插入位置A4 竖版
				if ((fposition[1] > 800 && fposition[0] > 500) && isSizeOk == false) {
					isSizeOk = true;
//					if(debug)System.out.println("进入设置水印的插入位置A4");
					String[] sizeType = selectType("A4", designType);
					if (sizeType == null || sizeType.length == 0) {
						return false;
					}
					img = setPic(img, sizeType, properties, markImagePath[j]);
				}
				// 设置水印的插入位置A4 横版
				if ((fposition[0] > 800 && fposition[1] > 500) && isSizeOk == false) {
					isSizeOk = true;
//					if(debug)System.out.println("进入设置水印的插入位置A4");
					String[] sizeType = selectType("A4H", designType);
					if (sizeType == null || sizeType.length == 0) {
						return false;
					}
					
					img = setPic(img, sizeType, properties, markImagePath[j]);
					System.out.println();
				}
//				
//				if (sizeType != null) {
//
//					img = setPic(img, sizeType, properties, markImagePath[j]);
//				}
				if (img == null ) {
					img = new Image[1];
					img[0] = Image.getInstance(markImagePath[j]);// 获取图片实例
					img[0].setAbsolutePosition(Float.valueOf(10), Float.valueOf(10));
					/*
					 * isModel=false; continue;
					 */
				}
				if (img == null) {
					return false;
				}

				// 向PDF输出文件中插入水印
				PdfContentByte under = stamp.getOverContent(i);// stamp.getUnderContent(i);
				PdfGState gs = new PdfGState();
				gs.setFillOpacity(1.0f);// 设置透明度为0.2
				under.setGState(gs);
				for (int k = 0; k < img.length; k++) {
					under.addImage(img[k]);

				}
			}
		}
		stamp.close();// 关闭
		reader.close();// 关闭
		File tempfile = new File(InPdfFile);
		if (tempfile.exists()) {
			// 删除原文件
			tempfile.delete();
		}
		return true;
	}


//	public static String[] selectType(String Ax, String designType) {
//		String[] type = null;
//		switch (designType) {
//
//		case "HX3_GYTRevision":// 工艺图
//			if (Ax.equals("A3")) {
//				type = new String[1];
//				type[0] = Ax + "_GY";
//			} else if (Ax.equals("A2")) {
//				type = new String[2];
//				type[0] = Ax + "_GY1";
//				type[1] = Ax + "_GY2";
//			}
//			break;
//		case "HX3_TYGY1Revision":// 通用工艺
//			if (Ax.equals("A3")) {
//				type = new String[1];
//				type[0] = Ax + "_TYGY";
//			} else if (Ax.equals("A2")) {
//				type = new String[2];
//				type[0] = Ax + "_TYGY1";
//				type[1] = Ax + "_TYGY2";
//			}
//			break;
//		case "HX3_WXTRevision":// 产品图：外协加工图HX3_WXTRevision ，零件图HX3_LJTRevision 装配图HX3_ZPTRevision
//			type = new String[1];
//			type[0] = Ax + "_PRODUCT";
//			break;
//		case "HX3_DJTRevision":// 产品图：外协加工图HX3_WXTRevision ，零件图HX3_LJTRevision
//								// 装配图HX3_ZPTRevision，锻件图HX3_DJTRevision
//			type = new String[1];
//			type[0] = Ax + "_PRODUCT";
//			break;
//		case "HX3_LJTRevision":// 产品图：外协加工图HX3_WXTRevision ，零件图HX3_LJTRevision 装配图HX3_ZPTRevision
//			type = new String[1];
//			type[0] = Ax + "_PRODUCT";
//			break;
//		case "HX3_ZPTRevision":// 产品图：外协加工图HX3_WXTRevision ，零件图HX3_LJTRevision 装配图HX3_ZPTRevision
//			type = new String[1];
//			type[0] = Ax + "_PRODUCT";
//			break;
//		case "HX3_GCGGTZDRevision":// 工程更改通知单
//			type = new String[1];
//			type[0] = Ax + "_ECN";
//			break;
//		case "HX3_GZTRevision":// 工装图
//			type = new String[2];
//			type[0] = Ax + "_GZT1";
//			type[1] = Ax + "_GZT2";
//			break;
//		default:
//			break;
//		}
//
//		return type;
//	}
	public static String[] selectType(String Ax, String designType) {
	    String[] type = null;

	    if ("HX3_GYTRevision".equals(designType)) { // 工艺图
	        if (Ax.equals("A3")) {
	            type = new String[1];
	            type[0] = Ax + "_GY";
	        } else if (Ax.equals("A2")) {
	            type = new String[2];
	            type[0] = Ax + "_GY1";
	            type[1] = Ax + "_GY2";
	        }
	    } else if ("HX3_TYGY1Revision".equals(designType)) { // 通用工艺
	        if (Ax.equals("A3")) {
	            type = new String[1];
	            type[0] = Ax + "_TYGY";
	        } else if (Ax.equals("A2")) {
	            type = new String[2];
	            type[0] = Ax + "_TYGY1";
	            type[1] = Ax + "_TYGY2";
	        }
	    } else if ("HX3_WXTRevision".equals(designType)) { // 产品图：外协加工图HX3_WXTRevision ，零件图HX3_LJTRevision 装配图HX3_ZPTRevision
	        type = new String[1];
	        type[0] = Ax + "_PRODUCT";
	    } else if ("HX3_DJTRevision".equals(designType)) { // 产品图：外协加工图HX3_WXTRevision ，零件图HX3_LJTRevision
	                                                        // 装配图HX3_ZPTRevision，锻件图HX3_DJTRevision
	        type = new String[1];
	        type[0] = Ax + "_PRODUCT";
	    } else if ("HX3_LJTRevision".equals(designType)) { // 产品图：外协加工图HX3_WXTRevision ，零件图HX3_LJTRevision 装配图HX3_ZPTRevision
	        type = new String[1];
	        type[0] = Ax + "_PRODUCT";
	    } else if ("HX3_ZPTRevision".equals(designType)) { // 产品图：外协加工图HX3_WXTRevision ，零件图HX3_LJTRevision 装配图HX3_ZPTRevision
	        type = new String[1];
	        type[0] = Ax + "_PRODUCT";
	    } else if ("HX3_GCGGTZDRevision".equals(designType)) { // 工程更改通知单
	        type = new String[1];
	        type[0] = Ax + "_ECN";
	    } else if ("HX3_GZTRevision".equals(designType)) { // 工装图
	        type = new String[2];
	        type[0] = Ax + "_GZT1";
	        type[1] = Ax + "_GZT2";
	    }

	    return type;
	}

	public static Image[] setPic(Image[] img, String[] sizeType, Properties properties, String markImagePath)
			throws BadElementException, MalformedURLException, IOException {
		// 转成String路径
		img = new Image[sizeType.length];
		for (int k = 0; k < sizeType.length; k++) {

			img[k] = Image.getInstance(markImagePath);// 获取图片实例
			String str = properties.getProperty(sizeType[k]);
			if (str == null) {
				return null;
			}
			String[] values = str.split(",");
			img[k].setAbsolutePosition(Float.valueOf(values[0]), Float.valueOf(values[1]));// 设置水印左下角的坐标
		}
		return img;
	}
//
	public static void replaceOrcreate(Dataset arg0, ItemRevision rev,String addPdfPath) {
		// 判断版本下有无pdf数据集，并且名称和caxa相同，有就替换，没有就新建
		ModelObject[] datasets = null;
		Dataset dataset = null;
		try {
			dmService.getProperties(new ModelObject[] {rev}, new String[] {"IMAN_specification"});
			datasets =  rev.getPropertyObject("IMAN_specification").getModelObjectArrayValue();;
			dmService.getProperties(datasets, new String[] {"object_name"});
//			datasets = TcUtils.getWhereReference(new WorkspaceObject[] {arg0});
//			datasets = (TCComponent[]) rev.getTCProperty("IMAN_specification").getReferenceValueArray();
			String pdfName = "";
			String caxaName = "";
			for (int i = 0; i < datasets.length; i++) {
				if (datasets[i].getTypeObject().getName().equals("PDF")) {
					pdfName = datasets[i].getPropertyDisplayableValue("object_name");
					caxaName = arg0.getPropertyDisplayableValue("object_name");
					if (pdfName.contains(".pdf") && caxaName.contains(".exb")) {
						pdfName = pdfName.substring(0, pdfName.lastIndexOf(".pdf"));
						if (debug)
							System.out.println(pdfName);
						caxaName = caxaName.substring(0, caxaName.lastIndexOf(".exb"));
						if (debug)
							System.out.println(pdfName);
					}
				}
				if (datasets[i].getTypeObject().getName().equals("PDF") && caxaName.equals(pdfName)) {
					dataset = (Dataset) datasets[i];
				}
			}
			System.out.println();
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		if (dataset == null) {
			try {
//				if(debug)System.out.println("开旁路0");
				TcUtils.setByPass(true);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
			try {
				dataset = createDataSet(rev,arg0.getPropertyDisplayableValue("object_name").replace(".exb", ".pdf"));//PDF_Reference
				POM_system_class get_owning_user = rev.get_owning_user();//rev.getPropertyObject("").getModelObjectValue();
				TcUtils.changeOwnershipModelObject(get_owning_user, "",new ModelObject[] {dataset});
//				TCComponentDatasetType datasetType = (TCComponentDatasetType) session.getTypeComponent("Dataset");
//				dataset = datasetType.create(arg0.getProperty("object_name").replace(".exb", ".pdf"), "", "PDF");
//				rev.add("IMAN_specification", dataset);
				
			} catch (Exception e) {
				e.printStackTrace();
				try {
//					if(debug)System.out.println("关旁路");
					TcUtils.setByPass(false);
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
//		if (dataset == null) {
////			MessageBox.post("创建失败", "错误", MessageBox.ERROR);
////			return null;
//		}

		try {
			try {
//				if(debug)System.out.println("开旁路1");
				TcUtils.setByPass(true);
			} catch (Exception e2) {
				e2.printStackTrace();
			}

			try {
				updateDataSet(dataset, addPdfPath, "PDF_Reference");
				//添加发布状态
				ReleaseStatus[] get_release_status_list = dataset.get_release_status_list();
				if(get_release_status_list.length == 0) {
					ReleaseStatusInput releaseStatusInput = new ReleaseStatusInput();
					ReleaseStatusOption releaseStatusOption = new ReleaseStatusOption();
					releaseStatusOption.newReleaseStatusTypeName = releaseStatus; 
					 releaseStatusOption.operation = "Append"; 
					 releaseStatusInput.objects = new WorkspaceObject[]{ (WorkspaceObject)dataset }; 
					 releaseStatusInput.operations = new ReleaseStatusOption[] {releaseStatusOption};
					 WorkflowService workflowService = WorkflowService.getService(AppXSession.getConnection());
					 SetReleaseStatusResponse setReleaseStatus = workflowService.setReleaseStatus(new ReleaseStatusInput[] {releaseStatusInput});
					 System.out.println();
				}
				if(mainArgs.length >=5) {
					//设置identiy标识
					if(mainArgs[4].contains(";")){
						String[] splitIdentity = mainArgs[4].split(";");
						Map<String, DataManagement.VecStruct>  propValueMap = new  HashMap<String, DataManagement.VecStruct>();
						DataManagement.VecStruct vec = new DataManagement.VecStruct();
						vec.stringVec = new String[] { splitIdentity[1]};
						propValueMap.put(splitIdentity[0], vec) ;
						dmService.setProperties(new ModelObject[] {rev}, propValueMap);
					}
					
				}
				
				//判断所有者
				POM_system_class rev_owning = rev.get_owning_user();
				POM_system_class dataset_owning = dataset.get_owning_user();
				if(!rev_owning.getUid().equals(dataset_owning.getUid())) {
					TcUtils.changeOwnershipModelObject(rev_owning, "",new ModelObject[] {dataset});
				}
//				dataset.setFiles(new String[] { addPdfPath }, new String[] { "PDF_Reference" });
			} catch (Exception e) {
				e.printStackTrace();
				try {
					if (debug)
						System.out.println("替换pdf失败，关旁路");
					TcUtils.setByPass(false);
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}

			try {
//				if(debug)System.out.println("替换pdf成功，关旁路");
				TcUtils.setByPass(false);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
//		if(debug)System.out.println("end");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
//
//	// 清空pdf数据集的命名引用
//	public void RecreatePdf(TCComponentDataset arg0, TCComponentItemRevision rev) {
//		// 判断版本下有无pdf数据集，并且名称和caxa相同，有就替换，没有就新建
//		TCComponent[] datasets = null;
//		TCComponentDataset dataset = null;
//		try {
//			datasets = (TCComponent[]) rev.getTCProperty("IMAN_specification").getReferenceValueArray();
//			String pdfName = "";
//			String caxaName = "";
//			for (int i = 0; i < datasets.length; i++) {
//				if (datasets[i].getProperty("object_type").equals("PDF")) {
//					pdfName = datasets[i].getProperty("object_name");
//					caxaName = arg0.getProperty("object_name");
//					if (pdfName.contains(".pdf") && caxaName.contains(".exb")) {
//						pdfName = pdfName.substring(0, pdfName.lastIndexOf(".pdf"));
//						if (debug)
//							System.out.println(pdfName);
//						caxaName = caxaName.substring(0, caxaName.lastIndexOf(".exb"));
//						if (debug)
//							System.out.println(pdfName);
//					}
//				}
//				if (datasets[i].getProperty("object_type").equals("PDF") && caxaName.equals(pdfName)) {
//					dataset = (TCComponentDataset) datasets[i];
//				}
//			}
//		} catch (TCException e1) {
//			e1.printStackTrace();
//		}
//
//		if (dataset == null) {
//			return;
//		} else {
//
//			try {
//				try {
////				if(debug)System.out.println("开旁路1");
//					ChangeDbomUtil.setByPass(true);
//				} catch (TCException e2) {
//					e2.printStackTrace();
//				}
//
//				try {
//					dataset.removeFiles("PDF_Reference");
//					if (debug)
//						System.out.println("PDF原命名引用删除完毕");
////					dataset.setFiles(new String[] { addPdfPath}, new String[] { "PDF_Reference" });
//				} catch (Exception e) {
//					e.printStackTrace();
//					try {
//						if (debug)
//							System.out.println("删除pdf引用失败，关旁路");
//						ChangeDbomUtil.setByPass(false);
//					} catch (TCException e2) {
//						e2.printStackTrace();
//					}
//				}
//
//				try {
////				if(debug)System.out.println("替换pdf成功，关旁路");
//					ChangeDbomUtil.setByPass(false);
//				} catch (TCException e2) {
//					e2.printStackTrace();
//				}
////		if(debug)System.out.println("end");
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
//
//	}
//
	public static String newString(String oldName) {
//		String newName=oldName;
		if (oldName.contains("/")) {
			if (debug)
				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 void sendMail(String message, String title) throws TCException {
//		TCComponentUserType userType = (TCComponentUserType) session.getTypeComponent("User");
//		TCComponentUser user = userType.find("admin");
//		TCComponent[] targetUser = new TCComponent[] { user };
//		try {
//			TCComponentEnvelopeType type = (TCComponentEnvelopeType) session.getTypeComponent("Envelope");
//			TCComponentEnvelope envelope = type.create(title, message, "");
//			envelope.setProperty("object_name", "caxa批量处理：" + title);
//			envelope.addReceivers(targetUser);
//			envelope.send();
//		} catch (TCException e) {
//			e.printStackTrace();
//		}
//	}
	public static void main(String[] args) throws Exception {
		mainArgs = args;
		String serverHost = "http://10.10.10.35:8080/tc";
		String host = System.getProperty("host");
		if (host != null && host.length() > 0) {
			serverHost = host;
		}

		session = new AppXSession(serverHost);
		User user = session.login();

		dmService = DataManagementService.getService(AppXSession.getConnection());
		fmu = new FileManagementUtility(AppXSession.getConnection(),
				null,
				new String[] { "http://10.10.10.35:4544" },
				new String[] { "http://10.10.10.35:4544" },
				"D://TEMP//fcc_tmp");
		tcp = PreferenceManagementService.getService(AppXSession.getConnection());
		if(args.length!=5) {
			tryAgain();
		}
		         
		try {
				while(write()) {
					try {
						int sec = new java.util.Random().nextInt(30);
						System.out.println("休眠"+sec+"s");
						Thread.sleep(1000*sec); // 随机休眠1~10秒
					} catch (Exception e) {
						
					}
				}
			
			FTPUtils.getConfigureInfomationg(tcp,args[3]);
			
			//获取数据集
//			DataManagementService dataManagementService = DataManagementService.getService(AppXSession.getConnection());
			
 			
			String revPuids[] = args[0].split(",");
			String puidss[] = args[1].split("\\|");
			for(int i = 0 ; i < revPuids.length ; i++) {
				ItemRevision rev = null;
				try {
					 rev = (ItemRevision) dmService.loadObjects(new String[] {revPuids[i]}).getPlainObject(0);
				}catch(Exception for1) {
					continue;
				}
//				dmService.getProperties(new ModelObject[] {rev}, new String[] {"hx3_identity"});
//				String identity = rev.getPropertyDisplayableValue("hx3_identity");
		//		if(identity != null && "Y".equals(identity)) {
		//			System.out.println("转图标识："+identity);
		//			return;
		//		}
				String puids[] = puidss[i].split(",");
				for(String puid : puids) {
					try {
						
						Dataset dataset = (Dataset) dmService.loadObjects(new String[] {puid}).getPlainObject(0);
						releaseStatus = args[2];
						companyName = args[3];
						loadWaitPdf();
						property(dataset,rev);
					}catch(Exception for2) {
						continue;
					}
				}
			}
			
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			//删除锁定文件
			String path = caxaPropertyHandler.class.getProtectionDomain().getCodeSource().getLocation().getPath();
			path = path.replace("%20", " ");
			String exePath = new File(path).getParent() + "//";
			if(checkFile("CaxaToPDF.lock",new File(exePath))) {
				String fileName = "CaxaToPDF.lock";
				File lockFile = new File(exePath+ fileName);
				lockFile.delete();
			}
			//有异常重试
			if(hasException) {
				tryAgain();
			}
		}
		
	}
	public static String consumeInputStream(InputStream is) throws IOException {
		         BufferedReader br = new BufferedReader(new InputStreamReader(is,"GBK"));
		         String s;
		         StringBuilder sb = new StringBuilder();
		         while ((s = br.readLine()) != null) {
		             System.out.println(s);
		             sb.append(s);
		         }
		         return sb.toString();
		     }

	private static void tryAgain() {
		checkDir("D://TEMP//fcc_tmp");
	
	}
	private static void checkDir(String dir) {
		
		File[]files= new File(dir).listFiles();
		List<File> exbFileList = new ArrayList<File>();
		Map<String,String> exbPuidMap = new HashMap<String,String>();
		for(File file:files)
		{
			String fileName = file.getName();
			if(fileName.contains("@")) {
				exbPuidMap.put(fileName.split("@")[0], fileName.split("@")[1]);
			}
			if(fileName.substring(fileName.length()-3, fileName.length()).equals("exb")) {
				exbFileList.add(file);
			}
			System.out.println(fileName);
		} 
		for(File exbFile : exbFileList) {
			if(exbPuidMap.containsKey(exbFile.getName())) {
				 //执行命令
				  String puid = exbPuidMap.get(exbFile.getName());
				  File deleteFile = new File(exbFile.getPath()+"@"+puid);
		          try {
		        	  deleteFile.delete();
		        	  ModelObject plainObject = dmService.loadObjects(new String[] {puid.split("#")[1]}).getPlainObject(0);
		        	  updateDataSet((Dataset) plainObject,exbFile.getPath(),"HX3_exb");
		        	  
//		        	  Runtime runtime = Runtime.getRuntime();  //获取Runtime实例
//		              String[] command = {"cmd", "/c", "start java -jar D:\\Siemens\\Teamcenter11\\portal\\plugins\\CaxaToPDF.jar \""+puid.split("#")[0]+"\" \""+puid.split("#")[1]+"\" \""+puid.split("#")[2]+"\" \""+puid.split("#")[3]+"\" \"Y\""};
//		              Process process = runtime.exec(command);
		        	  String main_args[] = new String[] {puid.split("#")[0],puid.split("#")[1],puid.split("#")[2],puid.split("#")[3],"Y"};
		        	  new caxaPropertyHandler().main(main_args);
		        } catch (Exception e) {
		        	try {
						deleteFile.createNewFile();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
		             e.printStackTrace();
		         }
				
			}
		}
		System.out.println();
	}
	/**
	 * 是否等待执行
	 * @return
	 * @throws IOException 
	 */
	private static boolean write() throws IOException {
		String path = caxaPropertyHandler.class.getProtectionDomain().getCodeSource().getLocation().getPath();
		path = path.replace("%20", " ");
		String exePath = new File(path).getParent() + "//";
		if(checkFile("CaxaToPDF.lock",new File(exePath))) {
			return true;
		}
		
		String fileName = "CaxaToPDF.lock";
		File lockFile = new File(exePath+ fileName);
		if (!lockFile.exists()) {
			lockFile.createNewFile();
		}
		System.out.println();
		return false;
	}
	
	private static boolean checkFile(String filename,File dir)
	{
		
		File[]files=dir.listFiles();
		for(File file:files)
		{
			
			if(file.isFile() && filename.equals(file.getName()))  //file时文件且文件名相同时，输出;
			{			
					return true;
			}
		} 
		return false;
	}
	
	private static void writeTime() {
		try {
			int sec = new java.util.Random().nextInt(30);
			System.out.println("休眠"+sec+"s");
			Thread.sleep(1000*sec); // 随机休眠1~10秒
		} catch (Exception e) {
			System.out.println("Got an exception!");
		}
		
	
}
	private static void updateDataSet(Dataset dataset, String filePath,String namedRef) throws Exception{
      
//        try {
            
			

            //获取命名的引用（物理文件）
            dmService.getProperties(new ModelObject[]{dataset},new String[]{"ref_list"});
            int refListNum = dataset.get_ref_list().length;
            ServiceData removeNamedReferenceFromDatasetServiceDate = null;
            if(refListNum == 0 ){
                System.out.println("数据集无命名的引用！");
            }
            else {
            	//命名的引用配置
                com.teamcenter.services.strong.core._2007_09.DataManagement.NamedReferenceInfo[] namedReferenceInfos = new com.teamcenter.services.strong.core._2007_09.DataManagement.NamedReferenceInfo[refListNum];
                for(int i = 0 ; i < refListNum ; i++ ){
                	ModelObject[] get_ref_list = dataset.get_ref_list();
                	ImanFile namedRefMobj = (ImanFile) dataset.get_ref_list()[i];
                	dmService.refreshObjects(new ModelObject[] {namedRefMobj});
                	dmService.getProperties(new ModelObject[]{namedRefMobj},new String[]{"file_ext"});
                	String get_file_ext = namedRefMobj.get_file_ext();
                    com.teamcenter.services.strong.core._2007_09.DataManagement.NamedReferenceInfo namedReferenceInfo= new com.teamcenter.services.strong.core._2007_09.DataManagement.NamedReferenceInfo();
                    namedReferenceInfo.type = namedRef;
                    namedReferenceInfo.deleteTarget = true;
                    namedReferenceInfo.targetObject = namedRefMobj;
                    namedReferenceInfos[i] = namedReferenceInfo;
                }

                //删除命名的引用
                com.teamcenter.services.strong.core._2007_09.DataManagement.RemoveNamedReferenceFromDatasetInfo[] removeNamedReferenceFromDatasets = new com.teamcenter.services.strong.core._2007_09.DataManagement.RemoveNamedReferenceFromDatasetInfo[1];
                com.teamcenter.services.strong.core._2007_09.DataManagement.RemoveNamedReferenceFromDatasetInfo removeNamedReferenceFromDataset = new com.teamcenter.services.strong.core._2007_09.DataManagement.RemoveNamedReferenceFromDatasetInfo();
                removeNamedReferenceFromDataset.dataset = dataset;
                removeNamedReferenceFromDataset.nrInfo = namedReferenceInfos;
                removeNamedReferenceFromDatasets[0] = removeNamedReferenceFromDataset;
                removeNamedReferenceFromDatasetServiceDate = dmService.removeNamedReferenceFromDataset(removeNamedReferenceFromDatasets);
            }
            
            if((removeNamedReferenceFromDatasetServiceDate != null 
            		&& removeNamedReferenceFromDatasetServiceDate.sizeOfDeletedObjects() > 0 )
            		|| refListNum == 0){
                System.out.println("命名的引用删除成功！");
                //配置新的命名引用
                FileManagement.DatasetFileInfo fileInfo = new FileManagement.DatasetFileInfo();

                fileInfo.allowReplace = false;
//                fileInfo.clientId = fileInfo.toString();
                fileInfo.fileName = filePath;
                fileInfo.isText = false;
                fileInfo.namedReferencedName = namedRef;

                FileManagement.DatasetFileInfo[] fileInfos = { fileInfo };

                FileManagement.GetDatasetWriteTicketsInputData inputData = new FileManagement.GetDatasetWriteTicketsInputData();
                inputData.dataset = dataset;
                inputData.createNewVersion = false;
                inputData.datasetFileInfos = fileInfos;

                FileManagement.GetDatasetWriteTicketsInputData[] inputs = { inputData };
                ServiceData putFilesServiceData = fmu.putFiles(inputs);
//                fileManagementUtility.putFiles(inputs);
                if(putFilesServiceData.sizeOfUpdatedObjects() > 0){
                    System.out.println("");
                }
                fmu.term();


            } else{
                String[] errMsg = removeNamedReferenceFromDatasetServiceDate.getPartialError(0).getMessages();
                System.out.println("命名的引用删除失败！");
            }
//            throw new Exception("1");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

    }
	//TCFMS中的文件转换到本地
    public static File TCFileToFile(Dataset dataset) throws Exception{
        if(dataset == null){
            return null;
        }
        File outFile = null;
        String filename = "";
        
        dmService.getProperties(new ModelObject[] { dataset}, new String[]{"ref_list"});
        ModelObject[] objects = dataset.get_ref_list();
        dmService.getProperties( objects, new String[]{"original_file_name"});
        filename = objects[0].getPropertyObject("original_file_name").getStringValue();
//        filename = CommonlyUtils.getNowDate()+ filename;
        GetFileResponse getFileResponse = fmu.getFiles(objects);
        File[] fileinfovec = getFileResponse.getFiles();
        outFile = fileinfovec[0];
//        nameMap.put(outFile.getName(),filename);
        
        return outFile;
    }
	 /***
     * 创建数据集 API
     * @param targetMobj 目标数据集
     * @param datasetName 数据集名称
     * @param filePath 文件路径
     */
    private static Dataset createDataSet(ModelObject targetMobj,String datasetName) {
       
        //创建数据集
        com.teamcenter.services.strong.core._2008_06.DataManagement.DatasetProperties2 datasetProperties2 = new com.teamcenter.services.strong.core._2008_06.DataManagement.DatasetProperties2();
        datasetProperties2.name = datasetName;
        datasetProperties2.type ="PDF";
        datasetProperties2.clientId="PDF_1";
        datasetProperties2.container = targetMobj;
        datasetProperties2.relationType = "IMAN_specification";
        CreateDatasetsResponse ceateDatasetsResponse = dmService.createDatasets2(new com.teamcenter.services.strong.core._2008_06.DataManagement.DatasetProperties2[]{datasetProperties2});
        Dataset dt = ceateDatasetsResponse.output[0].dataset;
        return dt;
//        //配置命名的引用
//        FileManagement.DatasetFileInfo fileInfo = new FileManagement.DatasetFileInfo();
//        fileInfo.allowReplace = false;
//        fileInfo.fileName = filePath;
//        fileInfo.isText = false;
//        fileInfo.namedReferencedName = "HG8_dwg";
//        FileManagement.DatasetFileInfo[] fileInfos = { fileInfo };
//
//        //绑定数据集
//        FileManagement.GetDatasetWriteTicketsInputData inputData = new FileManagement.GetDatasetWriteTicketsInputData();
//        inputData.dataset = dt;
//        inputData.createNewVersion = false;
//        inputData.datasetFileInfos = fileInfos;
//        FileManagement.GetDatasetWriteTicketsInputData[] inputs = { inputData };
//        ServiceData response = fmu.putFiles(inputs);
//        fmu.term();

//       
    }
    // 影响分析向上获取对象
    public static List<ModelObject> getWhereReference(WorkspaceObject[] obj ,int number){
        List<ModelObject> list = new ArrayList<ModelObject>();
        DataManagement.WhereReferencedResponse response =  dmService.whereReferenced(obj,number);
        DataManagement.WhereReferencedInfo[] info =  response.output[0].info;
        for (int i = 0; i < info.length; i++) {
        	if(info[i].relation.equals("HX3_ggh")) {
        		list.add(info[i].referencer);
        	}
        }
        return list;
    }
    private static Map<String, String> getECNValueMap(ItemRevision rev) throws Exception {
		// 2019.11.25增加4个属性映射：更改版次（版本号）、更改文件号（更改通知单的编号）、签字（“资料管理员”）和日期（更改通知单创建日期：年月日）
		// 只保留最近一次更改记录
		String dateString = "";
		Map<String, String> valueMap = new HashMap<String,String>();
		List<ModelObject> ecr = getWhereReference(new WorkspaceObject[] {rev}, 1);
//		AIFComponentContext[] ecr = rev.whereReferenced();
		for (int i = 0; i < ecr.size(); i++) {
			if(ecr.get(i) instanceof ItemRevision) {
				ItemRevision ecrRev = (ItemRevision) ecr.get(i);
				dmService.getProperties(new ModelObject[] {ecrRev}, new String[] {"creation_date","item_id"});
				System.out.println("ecrRev.getProperty:" + ecrRev.getTypeObject().getName());
				System.out.println();
				if (ecrRev.getTypeObject().getName().equals("HX3_GCGGTZDRevision")) {
					
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
						String dateString2 =  format.format(ecrRev.get_creation_date().getTime()) ;
						String revType = rev.getTypeObject().getName();
						System.out.println("revType:" + revType);
						if (dateString.length() == 0) {
							dateString = dateString2;
							if (revType.equals("HX3_ZPTRevision") || revType.equals("HX3_LJTRevision")
									|| revType.equals("HX3_WXTRevision") || revType.equals("HX3_DJTRevision") || revType.equals("HX3_TYGY1Revision")) {
	
								valueMap.put("更改版次1", rev.get_item_revision_id());
								valueMap.put("更改文件名1", ecrRev.get_item_id());
								valueMap.put("签字1", "资料管理员");
								valueMap.put("日期1", format.format(ecrRev.get_creation_date().getTime()));
							} else if (revType.equals("HX3_GYTRevision")) {
								valueMap.put("更改版次", rev.get_item_revision_id());
								valueMap.put("更改文件号", ecrRev.get_item_id());
								valueMap.put("签字", "资料管理员");
								valueMap.put("日期", format.format(ecrRev.get_creation_date().getTime()));
	
							}
						} else {
							if (dateString.compareTo(dateString2) < 0) {
								dateString = dateString2;
								if (revType.equals("HX3_ZPTRevision") || revType.equals("HX3_LJTRevision")
										|| revType.equals("HX3_WXTRevision")|| revType.equals("HX3_DJTRevision")|| revType.equals("HX3_TYGY1Revision")) {
	
									valueMap.put("更改版次1", rev.get_item_revision_id());
									valueMap.put("更改文件名1", ecrRev.get_item_id());
									valueMap.put("签字1", "资料管理员");
									valueMap.put("日期1", format.format(ecrRev.get_creation_date().getTime()));
								} else if (revType.equals("HX3_GYTRevision")) {
									valueMap.put("更改版次", rev.get_item_revision_id());
									valueMap.put("更改文件号", ecrRev.get_item_id());
									valueMap.put("签字", "资料管理员");
									valueMap.put("日期", format.format(ecrRev.get_creation_date().getTime()));
	
								}
							}
						}
					}

				
			}
			
		}
		return valueMap;
		
	}
}
