package com.huatek.busi.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Vector;

import org.apache.commons.io.FilenameUtils;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

/**
 * SSH工具类
 * 
 * @author edward
 *
 */
public class SSHUtil {
	
	/**
	 * 连接SSH上传文件
	 */
	public static boolean sshSftp(String ip, String user, String psw, int port,String sPath, String dPath) {
		boolean flag = false;
        Session session = null;
        JSch jsch = new JSch();
        try {
            if (port <= 0) {
                session = jsch.getSession(user, ip);
            } else {
                session = jsch.getSession(user, ip, port);
            }
            if (session == null) {
                throw new Exception("session is null");
            }
            session.setPassword(psw);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect(300000);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
	
	/**
	 * 上传文件
	 * @param session
	 * @param sPath
	 * @param dPath
	 */
	public static void upLoadFile(Session session, String sPath, String dPath) {
		 
        Channel channel = null;
        try {
            channel = (Channel) session.openChannel("sftp");
            channel.connect(10000000);
            ChannelSftp sftp = (ChannelSftp) channel;
            try {
            	//上传
                sftp.cd(dPath);
            } catch (SftpException e) {
                sftp.mkdir(dPath);
                sftp.cd(dPath);
 
            }
            File file = new File(sPath);
            copyFile(sftp, file, sftp.pwd());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.disconnect();
            channel.disconnect();
        }
    }
	
	public static void copyFile(ChannelSftp sftp, File file, String pwd) {
		 
        if (file.isDirectory()) {
            File[] list = file.listFiles();
            try {
                try {
                    String fileName = file.getName();
                    sftp.cd(pwd);
                    System.out.println("正在创建目录:" + sftp.pwd() + "/" + fileName);
                    sftp.mkdir(fileName);
                    System.out.println("目录创建成功:" + sftp.pwd() + "/" + fileName);
                } catch (Exception e) {
                    // TODO: handle exception
                }
                pwd = pwd + "/" + file.getName();
                try {
 
                    sftp.cd(file.getName());
                } catch (SftpException e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            for (int i = 0; i < list.length; i++) {
                copyFile(sftp, list[i], pwd);
            }
        } else {
            try {
                sftp.cd(pwd);
            } catch (SftpException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            System.out.println("正在复制文件:" + file.getAbsolutePath());
            InputStream instream = null;
            OutputStream outstream = null;
            try {
                outstream = sftp.put(file.getName());
                instream = new FileInputStream(file);
 
                byte b[] = new byte[1024];
                int n;
                try {
                    while ((n = instream.read(b)) != -1) {
                        outstream.write(b, 0, n);
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
 
            } catch (SftpException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                try {
                    outstream.flush();
                    outstream.close();
                    instream.close();
 
                } catch (Exception e2) {
                    // TODO: handle exception
                    e2.printStackTrace();
                }
            }
        }
    }
	

	/**
	 * sftp下载文件（夹）
	 * @param directory 下载文件上级目录
	 * @param srcFile 下载文件完全路径
	 * @param saveFile 保存文件路径
	 * @param sftp ChannelSftp
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("unchecked")
	public static void download(String directory,String srcFile, String saveFile, ChannelSftp sftp) throws UnsupportedEncodingException {
		Vector<LsEntry> conts = null;
		try{
			conts = sftp.ls(srcFile);
		} catch (SftpException e) {
			e.printStackTrace();
		}
		File file = new File(saveFile);
		if (!file.exists()) {
			file.mkdir();
		};
		if (srcFile.indexOf(".") > -1){
			try {
				sftp.get(srcFile, saveFile);
			} catch (SftpException e) {
				e.printStackTrace();
			}
		} else {
			for (Iterator<LsEntry> iterator = conts.iterator(); iterator.hasNext();) {
				LsEntry obj =  (LsEntry) iterator.next();
				String filename = new String(obj.getFilename().getBytes(),"UTF-8");
				if (!(filename.indexOf(".") > -1)) {
					directory = FilenameUtils.normalize(directory + System.getProperty("file.separator") + filename);
					srcFile = directory;
					saveFile = FilenameUtils.normalize(saveFile + System.getProperty("file.separator") + filename);
				} else {
					String[] arrs = filename.split("\\.");
					if ((arrs.length > 0) && (arrs[0].length() > 0)) {
						srcFile = FilenameUtils.normalize(directory + System.getProperty("file.separator") + filename);
					} else {
						continue;
					}
			   }
			  download(directory, srcFile, saveFile, sftp);
		    }
	   }
	}

}
