package com.saye.hospitalgd.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;
import java.net.SocketException;

/**
 * @author thuang
 * @version 1.0
 * @description:
 * 下载ftp文件
 * @date 2021/8/6 14:17
 */
@Slf4j
public class DownloadFtpUtil {

    /**
     * 获取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.setConnectTimeout(30000); // 30秒连接超时
            ftpClient.setDataTimeout(60000); // 60秒数据传输超时

            log.info("正在连接FTP服务器: " + ftpHost + ":" + ftpPort);
            ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器

            // 检查连接是否成功
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                log.error("FTP连接失败，服务器响应码: " + ftpClient.getReplyCode());
                ftpClient.disconnect();
                return null;
            }

            log.info("正在登录FTP服务器，用户名: " + ftpUserName);
            boolean loginSuccess = ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
            if (!loginSuccess) {
                log.error("FTP登录失败，请检查用户名和密码");
                ftpClient.disconnect();
                return null;
            }

            log.info("FTP连接和登录成功");
            return ftpClient;

        } catch (SocketException e) {
            log.error("FTP连接Socket异常: " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            log.error("FTP连接IO异常: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            log.error("FTP连接未知异常: " + e.getMessage());
            e.printStackTrace();
        }

        // 如果连接失败，确保断开连接
        if (ftpClient != null && ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                log.error("断开FTP连接失败: " + e.getMessage());
            }
        }

        return null;
    }


    /*
     * 从FTP服务器下载文件
     *
     * @param ftpHost FTP IP地址
     *
     * @param ftpUserName FTP 用户名
     *
     * @param ftpPassword FTP用户名密码
     *
     * @param ftpPort FTP端口
     *
     * @param ftpPath FTP服务器中文件所在路径 格式： ftptest/aa
     *
     * @param localPath 下载到本地的位置 格式：H:/download
     *
     * @param fileName 文件名称
     */
    public static boolean downloadFtpFile(String ftpHost, String ftpUserName,
                                          String ftpPassword, int ftpPort, String ftpPath, String localPath,
                                          String fileName) {

        FTPClient ftpClient = null;
        OutputStream os = null;
        try {
            //先判断下载的路径是否存在 不存在创建
            File file = new File(localPath);
            if (!file.exists()) {
                file.mkdirs();
            }

            ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);

            // 检查FTP客户端是否为空
            if (ftpClient == null) {
                log.error("FTP客户端创建失败，请检查FTP连接参数");
                return false;
            }

            // 检查连接是否成功
            if (!ftpClient.isConnected()) {
                log.error("FTP连接失败，无法连接到服务器");
                return false;
            }

            ftpClient.setControlEncoding("UTF-8"); // 中文支持

            // 设置文件类型前检查连接状态
            if (ftpClient.isConnected()) {
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftpClient.enterLocalPassiveMode();

                // 切换到指定目录
                if (ftpPath != null && !ftpPath.trim().isEmpty()) {
                    ftpClient.changeWorkingDirectory(ftpPath);
                }

                File localFile = new File(localPath + File.separatorChar + fileName);
                os = new FileOutputStream(localFile);
                boolean b = ftpClient.retrieveFile(fileName, os);

                if (b) {
                    log.info("文件下载成功: " + fileName);
                } else {
                    log.error("文件下载失败: " + fileName);
                }

                return b;
            } else {
                log.error("FTP连接已断开");
                return false;
            }

        } catch (FileNotFoundException e) {
            log.error("没有找到文件: " + ftpPath + "/" + fileName);
            e.printStackTrace();
        } catch (SocketException e) {
            log.error("连接FTP失败: " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            log.error("文件读取错误: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // 确保资源正确关闭
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    log.error("关闭输出流失败: " + e.getMessage());
                }
            }
            if (ftpClient != null && ftpClient.isConnected()) {
                try {
                    ftpClient.logout();
                    ftpClient.disconnect();
                } catch (IOException e) {
                    log.error("关闭FTP连接失败: " + e.getMessage());
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {
        boolean b = downloadFtpFile("uisftp.chinaums.com", "100700-89836118062010A", "Aa111111", 21, "build", "d:\\1", "89836118062010A_20210909_68.xls");

    }
}
