package com.liang.common.utils;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.apache.http.entity.mime.MultipartEntityBuilder;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author ly
 * @Date 2025/2/5 10:03
 * @Version 1.0
 */
public class FileUtil {
    // 此处是一个公共方法，旨在获取绝对/相对路径 文件夹下所有文件名
    public List<String> getFileName(String path){
        List<String>FileNamelist = new ArrayList<>();
        Path rootDirectory = Paths.get(path);
        try(Stream<Path> paths = Files.walk(rootDirectory)){
           FileNamelist =  paths.filter(Files::isRegularFile)
                    .map(Path::getFileName)
                    .map(Path::toString)
                    .collect(Collectors.toList());

        }catch (IOException a){
            a.printStackTrace();
        }
        return FileNamelist;
    }

    // 文件转发服务

    /**
     * @param file
     * @param webpath
     * @return
     * @throws IOException
     *  由于http问题 暂无法 实现
     */
    public Integer uploadfile(MultipartFile file,String webpath) throws  IOException{
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(webpath);

        HttpEntity entity = MultipartEntityBuilder.create()
                .addBinaryBody("file", file.getInputStream(),
                        org.apache.http.entity.ContentType.APPLICATION_OCTET_STREAM, file.getOriginalFilename())
                .build();
        httpPost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * ftp服务器传输
     * @param file
     * @param server
     * @param port
     * @param user
     * @param password
     * @return
     */
    public boolean uploadToFtp(MultipartFile file, String server, int port, String user,
                               String password, String remoteDirPath) {
        FTPClient ftpClient = new FTPClient();
        try {
            // 1. 连接到服务器
            ftpClient.connect(server, port);
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                System.err.println("连接失败: " + ftpClient.getReplyString());
                return false;
            }

            // 2. 登录
            boolean loggedIn = ftpClient.login(user, password);
            if (!loggedIn) {
                System.err.println("登录失败: " + ftpClient.getReplyString());
                return false;
            }

            // 3. 配置传输模式和编码
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();  // 被动模式（避免防火墙问题）

            // 4. 创建目标目录（如果不存在）
            String[] dirs = remoteDirPath.split("/");
            StringBuilder dirPath = new StringBuilder();
            for (String dir : dirs) {
                if (dir.isEmpty()) continue;
                dirPath.append("/").append(dir);
                if (!ftpClient.changeWorkingDirectory(dirPath.toString())) {
                    if (ftpClient.makeDirectory(dirPath.toString())) {
                        System.out.println("创建目录: " + dirPath);
                    } else {
                        System.err.println("目录创建失败: " + dirPath);
                        return false;
                    }
                }
            }

            // 5. 拼接完整远程路径（目录 + 文件名）
            String remoteFileName = file.getOriginalFilename();
            String remoteFilePath = remoteDirPath.endsWith("/")
                    ? remoteDirPath + remoteFileName
                    : remoteDirPath + "/" + remoteFileName;

            // 6. 上传文件
            try (InputStream inputStream = file.getInputStream()) {
                boolean uploaded = ftpClient.storeFile(remoteFilePath, inputStream);
                System.out.println("上传结果: " + uploaded + ", 响应: " + ftpClient.getReplyString());
                return uploaded;
            }

        } catch (IOException e) {
            System.err.println("上传异常: " + e.getMessage());
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
