package cn.com.qmth.stmms.common.utils;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPConnectionClosedException;
import org.apache.commons.net.ftp.FTPReply;

public class FtpUploadUtil {

    String hostName;

    String userName;

    String password;

    String remoteDirs;

    String port;

    public FtpUploadUtil(String hostName, String userName, String password, String remoteDirs, String port) {
        if (remoteDirs == null || remoteDirs.equalsIgnoreCase("")) {
            remoteDirs = null;
        }
        this.hostName = hostName;
        this.userName = userName;
        this.password = password;
        this.remoteDirs = remoteDirs;
        this.port = port;
    }

    public boolean uploadFile(InputStream input, String remotefilename, String dir, String remoteDir) {
        FTPClient ftp = new FTPClient();
        int reply;
        try {
            ftp.connect(hostName, Integer.parseInt(port));
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return false;
            }
        } catch (IOException e) {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException f) {
                    return false;
                }
            }
        }
        try {
            if (!ftp.login(userName, password)) {
                ftp.logout();
                return false;
            }
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.enterLocalPassiveMode();
            ftp.changeWorkingDirectory(dir);
            ftp.makeDirectory(remoteDir);
            ftp.changeWorkingDirectory(remoteDir);
            ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftp.storeFile(remotefilename, input);
            input.close();
            ftp.logout();
        } catch (FTPConnectionClosedException e) {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException f) {
                    return false;
                }
            }
            return false;
        } catch (IOException e) {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException f) {
                    return false;
                }
            }
            return false;
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException f) {
                    return false;
                }
            }
        }
        return true;
    }

    public boolean uploadFile(InputStream input, String remotefilename, String remoteDir) {
        FTPClient ftp = new FTPClient();
        int reply;
        try {
            ftp.connect(hostName, Integer.parseInt(port));
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return false;
            }
        } catch (IOException e) {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException f) {
                    return false;
                }
            }
        }

        try {
            if (!ftp.login(userName, password)) {
                ftp.logout();
                return false;
            }

            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.enterLocalPassiveMode();

            /**
             * 创建文件夹
             */
            createDirecroty(remoteDirs + remoteDir, ftp);
            ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);

            if (input == null) {
                System.out.println("本地文件不存在");
            }
            ftp.storeFile(remotefilename, input);
            input.close();
            ftp.logout();
        } catch (FTPConnectionClosedException e) {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException f) {
                    return false;
                }
            }
            return false;
        } catch (IOException e) {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException f) {
                    return false;
                }
            }
            return false;
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException f) {
                    return false;
                }
            }
        }
        return true;
    }

    /** */
    /**
     * 递归创建远程服务器目录
     * 
     * @param remote
     *            远程服务器文件绝对路径
     * @param ftpClient
     *            FTPClient对象
     * @return 目录创建是否成功
     * @throws IOException
     */
    public String createDirecroty(String remote, FTPClient ftpClient) throws IOException {
        String status = "1";
        String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
        if (!directory.equalsIgnoreCase("/") && !ftpClient.changeWorkingDirectory(directory)) {
            // 如果远程目录不存在，则递归创建远程服务器目录
            int start = 0;
            int end = 0;
            if (directory.startsWith("/")) {
                start = 1;
            } else {
                start = 0;
            }
            end = directory.indexOf("/", start);
            while (true) {
                String subDirectory = new String(remote.substring(start, end));
                if (!ftpClient.changeWorkingDirectory(subDirectory)) {
                    if (ftpClient.makeDirectory(subDirectory)) {
                        ftpClient.changeWorkingDirectory(subDirectory);
                    } else {
                        System.out.println("创建目录失败");
                        return "0";
                    }
                } else {
                    ftpClient.changeWorkingDirectory(subDirectory);
                }

                start = end + 1;
                end = directory.indexOf("/", start);

                // 检查所有目录是否创建完毕
                if (end <= start) {
                    break;
                }
            }
        } else {
            ftpClient.changeWorkingDirectory(directory);
        }
        return status;
    }
}
