package cd.casic.ci.process.process.service.sftpFile.impl;


import cd.casic.ci.commons.sftp.SftpClientUtils;
import cd.casic.ci.process.process.service.sftpFile.SftpFileService;
import cd.casic.ci.commons.properties.TargetFileUploadProperties;
import com.amazonaws.util.IOUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author HopeLi
 * @version v1.0
 * @ClassName SftpFileServiceImpl
 * @Date: 2025/5/17 15:19
 * @Description:
 */
@Service
@Slf4j
public class SftpFileServiceImpl implements SftpFileService {

    @Resource
    private TargetFileUploadProperties fileUploadProperties;


    @Override
    public String uploadFile(MultipartFile file, String remoteDir, String remoteFileName) {
        String localFilePath = saveTempFile(file);
        try (SftpClientUtils client = new SftpClientUtils(fileUploadProperties.getRemoteHost(),
                fileUploadProperties.getRemotePort(),
                fileUploadProperties.getUsername(),
                fileUploadProperties.getPassword(),
                fileUploadProperties.getSshKeyPath())) {
            return client.uploadFile(localFilePath, remoteDir, remoteFileName);
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败: " + e.getMessage(), e);
        }
    }

    @Override
    public void downloadFile(String remoteFilePath, HttpServletResponse response) {
        try (SftpClientUtils client = new SftpClientUtils(fileUploadProperties.getRemoteHost(),
                fileUploadProperties.getRemotePort(),
                fileUploadProperties.getUsername(),
                fileUploadProperties.getPassword(),
                fileUploadProperties.getSshKeyPath())) {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + new File(remoteFilePath).getName() + "\"");

            try (OutputStream out = response.getOutputStream()) {
                client.downloadFile(remoteFilePath, out);
            }
        } catch (Exception e) {
            throw new RuntimeException("文件下载失败: " + e.getMessage(), e);
        }
    }

    @Override
    public void downloadFilesAsZip(List<String> remoteFilePaths, String zipFileName, HttpServletResponse response) {
        try (SftpClientUtils client = new SftpClientUtils(fileUploadProperties.getRemoteHost(),
                fileUploadProperties.getRemotePort(),
                fileUploadProperties.getUsername(),
                fileUploadProperties.getPassword(),
                fileUploadProperties.getSshKeyPath())) {
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName + "\"");

            try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
                for (String remoteFilePath : remoteFilePaths) {
                    String fileName = remoteFilePath.substring(remoteFilePath.lastIndexOf("/") + 1);
                    try (InputStream in = client.downloadFileToStream(remoteFilePath)) {
                        zipOut.putNextEntry(new ZipEntry(fileName));
                        byte[] buffer = new byte[1024];
                        int bytesRead;
                        while ((bytesRead = in.read(buffer)) > 0) {
                            zipOut.write(buffer, 0, bytesRead);
                        }
                        zipOut.closeEntry();
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("批量下载并打包 ZIP 失败: " + e.getMessage(), e);
        }
    }

    @Override
    public void downloadFilesAsZip(List<String> remoteFilePaths, OutputStream outputStream) {
        try (SftpClientUtils client = new SftpClientUtils(fileUploadProperties.getRemoteHost(),
                fileUploadProperties.getRemotePort(),
                fileUploadProperties.getUsername(),
                fileUploadProperties.getPassword(),
                fileUploadProperties.getSshKeyPath())) {

            try (ZipOutputStream zipOut = new ZipOutputStream(outputStream)) {
                for (String remoteFilePath : remoteFilePaths) {
                    String fileName = remoteFilePath.substring(remoteFilePath.lastIndexOf("/") + 1);
                    try (InputStream in = client.downloadFileToStream(remoteFilePath)) {
                        zipOut.putNextEntry(new ZipEntry(fileName));
//                        byte[] buffer = new byte[1024];
//                        int bytesRead;
//                        while ((bytesRead = in.read(buffer)) > 0) {
//                            zipOut.write(buffer, 0, bytesRead);
//                        }
                        IOUtils.copy(in,zipOut);
                        in.close();
                        zipOut.closeEntry();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
//            throw new RuntimeException("批量下载并打包 ZIP 失败: " + e.getMessage(), e);
        }
    }

    private String saveTempFile(MultipartFile file) {
        try {
            File tempFile = File.createTempFile("upload-", ".tmp");
            file.transferTo(tempFile);
            return tempFile.getAbsolutePath();
        } catch (IOException e) {
            throw new RuntimeException("保存临时文件失败", e);
        }
    }
}
