package com.jsc.dsp.utils;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

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

@Component
public class FTPConnector {

    Logger log = LoggerFactory.getLogger(this.getClass().getName());

    @Value("${ftp.host}")
    String host;

    @Value("${ftp.port}")
    Integer port;

    @Value("${ftp.username}")
    String username;

    @Value("${ftp.password}")
    String password;

    @Value("${ftp.timeout}")
    Integer timeout;

    public boolean uploadFile(InputStream inputStream, String remotePath) {
        FTPClient ftpClient = new FTPClient();
        try {
            // 连接 FTP 服务器
            ftpClient.connect(host, port);
            ftpClient.login(username, password);
            ftpClient.setConnectTimeout(timeout);
            ftpClient.setSoTimeout(timeout);

            // 设置文件类型为二进制（避免文本模式损坏文件）
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            // 启用被动模式（适用于 NAT/防火墙环境）
            ftpClient.enterLocalPassiveMode();

            // 检查登录是否成功
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                ftpClient.disconnect();
                log.error("FTP 登录失败");
                return false;
            }

            // 创建目录（如果路径包含子目录）
            createDirectories(ftpClient, remotePath);

            // 上传文件
            boolean success = ftpClient.storeFile(remotePath, inputStream);
            if (success) {
                log.info("文件上传成功: {}", remotePath);
            } else {
                log.error("FTP 上传失败，错误码: {}", ftpClient.getReplyCode());
            }
            return success;

        } catch (IOException e) {
            log.error("FTP 上传异常: {}", e.getMessage(), e);
            return false;
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (ftpClient.isConnected()) {
                    ftpClient.logout();
                    ftpClient.disconnect();
                }
            } catch (IOException e) {
                log.warn("关闭 FTP 连接时出错", e);
            }
        }
    }

    /**
     * 递归创建远程目录（如果路径中包含目录）
     */
    private void createDirectories(FTPClient ftpClient, String remoteFilePath) throws IOException {
        String[] pathParts = remoteFilePath.split("/");
        StringBuilder currentPath = new StringBuilder();

        for (int i = 0; i < pathParts.length - 1; i++) {
            if (!pathParts[i].isEmpty()) {
                currentPath.append("/").append(pathParts[i]);
                // 尝试切换目录，如果失败则创建
                if (!ftpClient.changeWorkingDirectory(currentPath.toString())) {
                    boolean made = ftpClient.makeDirectory(currentPath.toString());
                    if (made) {
                        log.debug("创建 FTP 目录: {}", currentPath);
                    }
                    ftpClient.changeWorkingDirectory(currentPath.toString());
                }
            }
        }
    }

}
