package com.connor.signoff.soa.handler;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.util.Properties;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import com.teamcenter.services.strong.administration.*;

public class FTPUtils {

	public static final boolean debug = true;
	public static String ftpUserName = "";// plm
	public static String ftpPassword = "";// 本地：hxgs888hzq 宏协：hxgs888
	public static String ftpHost = "";// 本地：192.168.0.139 宏协192.168.2.240
	public static String ftpPath = "";
	public static String CompanyName = "";
	public static String FTPLinkInfo = "";
	public static int ftpPort = 0;// 2122这是转pdf的port；2121才是属性映射的port
//	public static TCSession session = RACUIUtil.getTCSession();
	public static int count = 0;// 半秒
	public static int waitOkOrErrFileCount = 0;
	public static int waitPdf = 0;
	/**
	 * 读取配置文件及首选项
	 * @param tcp 
	 * @param args 
	 */
	public static void getConfigureInfomationg(PreferenceManagementService tcp, String args) {

//		String tcRoot = getTCPlugin() + "\\" + "sign.config";
//		Properties properties = getProperties(tcRoot);
//		try {
//			CompanyName = args;
//			waitPdf = Integer.valueOf(properties.getProperty("WAITPDF"));
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		Properties prop2 = new Properties();
		InputStream resourceAsStream = FTPUtils.class.getResourceAsStream("PDFInfo.properties");
        if (resourceAsStream != null) {
        	try {
				prop2.load(resourceAsStream);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	waitPdf = Integer.valueOf(prop2.getProperty("WAITPDF"));
        	System.out.println("waitPdf:"+waitPdf);
        } else {
            System.err.println("无法找到配置文件 ftp.properties");
        }
        
		if (debug)
			System.out.println(CompanyName);
		
		FTPLinkInfo = args;
		System.out.println("FTPLinkInfo:" + FTPLinkInfo);
		String[] ftpValues = new String[5];
		// TODO Auto-generated method stub
        System.out.println("开始远程连接数据库\n开始读取配置文件");

        // 加载配置文件
        Properties prop = new Properties();
        InputStream  fis = null;
        try {
            // 获取当前类的类加载器，用于找到资源文件
            fis = FTPUtils.class.getResourceAsStream("ftp.properties");
            
            
            if (fis != null) {
                prop.load(fis);
            } else {
                System.err.println("无法找到配置文件 ftp.properties");
            }

            // 读取配置
            String ip = prop.getProperty("ip");
            System.out.println("ip:"+ip);
            ftpValues[0] = ip;
            
            String port = prop.getProperty("port");
            System.out.println("port:"+port);
            ftpValues[1] = port;
            
            String username = prop.getProperty("username");
            System.out.println("username:"+username);
            ftpValues[2] = username;
            
            String password = prop.getProperty("password");
            System.out.println("password:"+password);
            ftpValues[3] = password;
            
            String path = prop.getProperty("path");
            System.out.println("path:"+path);
            ftpValues[4] = path;
        }catch (Exception e) {
            e.printStackTrace();
        }
//		 = session.getPreferenceService().getStringValues(FTPLinkInfo);
		ftpHost = ftpValues[0];
		ftpPort = Integer.valueOf(ftpValues[1]);
		ftpUserName = ftpValues[2];
		ftpPassword = ftpValues[3];
		ftpPath = ftpValues[4];
		if (debug) {
			System.out.println("ip:" + ftpHost);
			System.out.println("port:" + ftpPort);
			System.out.println("user:" + ftpUserName);
			System.out.println("password:" + ftpPassword);
			System.out.println("caxadir:" + ftpPath);
		}

	}
	
	/**
	 * 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
	 */
	//FTPUtils.uploadFile(ip, user, password, port, caxadir, tempCaxaPathName, tempCaxaPathIn);
	public static boolean uploadFile(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.setControlEncoding("GBK"); // 中文支持
//			fileName = new String(fileName.getBytes("GBK"),"iso-8859-1");//TODO 
			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftpClient.enterLocalPassiveMode();
			ftpClient.changeWorkingDirectory(ftpPath);
			ftpClient.storeFile(convGBKToISO(fileName), in);//中文支持
			
			//ftpClient.storeFile(fileName, in);//默认方法，可能不支持中文
			in.close();
			ftpClient.logout();
			success = true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return success;
	}
	
	
	public static boolean downOkOrErrFile(
			String fileName, // 要下载的文件名
			String localPath// 下载后保存到本地的路径

	) {
		boolean success = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
//            ftp.login("anonymous", null);// 登陆FTP服务器
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			ftp.enterLocalPassiveMode();// 不用这句，有些电脑打开了防火墙就会在ftp.listFiles()这里卡住
//            System.out.println("aaa");
			boolean ftpchange = ftp.changeWorkingDirectory(ftpPath);// 转移到FTP服务器目录
//            System.out.println(ftpchange);
//            FTPFile[] fs = ftp.listFiles(); 
			String errorNamePrefix = "";
			 if (fileName.toLowerCase().endsWith(".exb")) {
				 errorNamePrefix = fileName  ;
			}
			waitOkOrErrFileCount = 0 ;
			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();
		}
		System.out.println("errorNamePrefix:"+errorNamePrefix);
		for (FTPFile ff : fs) {
			//2023.04.06如果找到.ok即为成功，.error即为失败不用再找了
			// FTP中文支持
			String ffName = convISOtoGBK(ff.getName());
			System.out.println("ffName:"+ffName);
			if (ffName.equals(errorNamePrefix + ".ok")) {
				System.out.println("映射成功...");
				return fs;
			} else if (ffName.equals(errorNamePrefix + ".err")) {
				System.out.println("映射异常");
				return null;
			}
		}
		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;
	}
	/**
	 * 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 deleteTxt(
			String fileName, // 要下载的文件名
			String localPath// 下载后保存到本地的路径

	) {

		boolean success = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;

			ftp = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
//            ftp.login("anonymous", null);// 登陆FTP服务器
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			ftp.enterLocalPassiveMode();// 不用这句，有些电脑打开了防火墙就会在ftp.listFiles()这里卡住
//            System.out.println("aaa");
			boolean ftpchange = ftp.changeWorkingDirectory(ftpPath);// 转移到FTP服务器目录
			fileName = fileName.replace(".exb", ".txt");
			ftp.setControlEncoding("GBK"); //FTP 中文支持
			fileName = convGBKToISO(fileName);//FTP 中文支持
			ftp.dele(fileName);
			success=true;
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return success;
	
	}
	public static boolean downFile(
			String fileName, // 要下载的文件名
			String localPath// 下载后保存到本地的路径

	) {
		boolean success = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			ftp.enterLocalPassiveMode();// 不用这句，有些电脑打开了防火墙就会在ftp.listFiles()这里卡住
//            System.out.println("aaa");
			boolean ftpchange = ftp.changeWorkingDirectory(ftpPath);// 转移到FTP服务器目录
//            System.out.println(ftpchange);
//            FTPFile[] fs = ftp.listFiles(); 
			String errorName = "";
			if (fileName.toLowerCase().endsWith(".pdf")) {
				errorName = fileName + ".err";
			} else if (fileName.toLowerCase().endsWith(".exb")) {
				errorName = fileName + ".err";
			}
			String okName= fileName + ".ok";
			File localFile = new File(localPath + "/" + fileName);
			count = 0;
			FTPFile[] fs = waitPdf(ftp, fileName, errorName,okName);
			if (fs != null) {

				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				ftp.setControlEncoding("GBK");
				for (FTPFile ff : fs) {
					// FTP中文支持
					String ffName = convISOtoGBK(ff.getName());
					if (ffName.equals(fileName)) {
						OutputStream is = new FileOutputStream(localFile);
						ftp.retrieveFile(ff.getName(), is);
//            			System.out.println("ccc" +ff.getName()+fileName);
						is.close();
						break;
					}
				}
				ftp.logout();
				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[] 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;
	}
	/**
	 * 将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;		
	}
	 /**
	  * 将GBK文件名转换为ISO编码格式
	  *  将本地文件名转换为FTP识别的编码
	  * @param fileNameGBK
	  * @return
	  */
	 public static String convGBKToISO(String fileNameISO) {
	  String filenameISO="";
	  try {
		  filenameISO = new String(fileNameISO.getBytes("GBK"),"iso-8859-1");
	  } catch (UnsupportedEncodingException e) {
	   // TODO Auto-generated catch block
	   e.printStackTrace();
	  }
	  return filenameISO;  
	 }
	/**
	 * 获取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())) {
				System.out.println("未连接到FTP，用户名或密码错误。");
				ftpClient.disconnect();
			} else {
				System.out.println("FTP连接成功。");
			}
		} catch (SocketException e) {
			e.printStackTrace();
			System.out.println("FTP的IP地址可能错误，请正确配置。");
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("FTP的端口错误,请正确配置。");
		}
		return ftpClient;
	}
	/**
	 * 获取本jar所在的plugin路径
	 * 
	 * @param
	 * @return
	 */
	public static String getTCPlugin() {
		String path2 = "";
		path2 = OpenDatasetSignoff.class.getProtectionDomain().getCodeSource().getLocation().getPath();// 获得tc的plugins下的jar包的绝对路径
		path2 = path2.replace("%20", " ");
		System.out.println("plugin路径:" + path2);
		File file = new File(path2);
		try {
			System.out.println("file.getParent:" + file.getParent());
		} catch (Exception e) {
			e.printStackTrace();
		}
		path2 = file.getParent() + "//";
		System.out.println("plugin路径:" + path2);
		return path2;
	}
	/**
	 * 获取配置文件所有信息
	 * 
	 * @param 配置文件路径
	 * @return
	 */
	public static Properties getProperties(String fileName) {
		Properties properties = new Properties();
		try {
			InputStream inputStream = new FileInputStream(fileName);
			properties.load(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return properties;
	}
}
