package com.yd.oss.service.utils;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 文件工具类
 */
public class FileUtil {

    /**
     * 获取文件类型（扩展名）
     * @param fileName
     * @return
     */
    public static String getFileType(String fileName) {
        return fileName.contains(".") ?
                fileName.substring(fileName.lastIndexOf(".") + 1) : "";
    }

    /**
     * 重置输入流
     * @param originalStream
     * @param size
     * @return
     * @throws IOException
     */
    public static InputStream resetInputStream(InputStream originalStream, long size) throws IOException {
        if (originalStream instanceof ByteArrayInputStream) {
            // 如果是ByteArrayInputStream，可以直接重置
            ((ByteArrayInputStream) originalStream).reset();
            return originalStream;
        }

        // 对于其他类型的流，需要重新创建
        // 注意：这里简化处理，实际应用中可能需要更复杂的逻辑
        byte[] data = new byte[(int) size];
        try (ByteArrayInputStream bais = new ByteArrayInputStream(data)) {
            return bais;
        }
    }

    /**
     * 安静关闭资源
     * @param closeable
     */
    public static void closeQuietly(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                // 安静关闭，忽略异常
            }
        }
    }

    /**
     * 读取输入流到字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static byte[] readInputStreamToBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[1024];
        while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }
        buffer.flush();
        return buffer.toByteArray();
    }

    /**
     * 获取输入流大小
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static Long getInputStreamSize(InputStream inputStream) throws IOException {
        if (inputStream instanceof ByteArrayInputStream) {
            // 如果是ByteArrayInputStream，直接获取可用字节数
            return (long) inputStream.available();
        }

        // 对于其他类型的流，需要读取并计算大小
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        long size = 0;

        while ((len = inputStream.read(buffer)) > -1) {
            baos.write(buffer, 0, len);
            size += len;
        }

        return size;
    }

    /**
     * 生成文件key（唯一标识）
     * @param originalFileName 原始文件名
     * @param type oss文件夹分类目录类型，例：如果是.xls那就是excel/
     * @return
     */
    public static String generateFileKey(String originalFileName,String type) {
        // 提取文件扩展名
        String fileExtension = originalFileName.contains(".") ?
                originalFileName.substring(originalFileName.lastIndexOf(".")) : "";

        // 生成唯一文件key：日期目录 + UUID + 扩展名
        return type + "/" +LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd/")) +
                UUID.randomUUID().toString().replace("-", "") + fileExtension;
    }

    /**
     * 根据文件类型获取内容类型
     * @param fileType 文件扩展名（不含点）
     * @return MIME类型
     */
    public static String getContentType(String fileType) {
        if (fileType == null || fileType.trim().isEmpty()) {
            return "application/octet-stream";
        }

        String lowerFileType = fileType.toLowerCase();

        switch (lowerFileType) {
            // 图像类型
            case "jpg":
            case "jpeg":
                return "image/jpeg";
            case "png":
                return "image/png";
            case "gif":
                return "image/gif";
            case "bmp":
                return "image/bmp";
            case "webp":
                return "image/webp";
            case "svg":
                return "image/svg+xml";
            case "ico":
                return "image/x-icon";
            case "tiff":
            case "tif":
                return "image/tiff";
            case "psd":
                return "image/vnd.adobe.photoshop";

            // 文档类型
            case "pdf":
                return "application/pdf";
            case "doc":
                return "application/msword";
            case "docx":
                return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            case "xls":
                return "application/vnd.ms-excel";
            case "xlsx":
                return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            case "ppt":
                return "application/vnd.ms-powerpoint";
            case "pptx":
                return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
            case "csv":
                return "text/csv";
            case "rtf":
                return "application/rtf";
            case "odt":
                return "application/vnd.oasis.opendocument.text";
            case "ods":
                return "application/vnd.oasis.opendocument.spreadsheet";
            case "odp":
                return "application/vnd.oasis.opendocument.presentation";

            // 文本类型
            case "txt":
                return "text/plain";
            case "html":
            case "htm":
                return "text/html";
            case "css":
                return "text/css";
            case "xml":
                return "application/xml";
            case "json":
                return "application/json";
            case "js":
                return "application/javascript";
            case "md":
                return "text/markdown";
            case "log":
                return "text/plain";

            // 压缩文件类型
            case "zip":
                return "application/zip";
            case "rar":
                return "application/vnd.rar";
            case "7z":
                return "application/x-7z-compressed";
            case "tar":
                return "application/x-tar";
            case "gz":
                return "application/gzip";

            // 音频类型
            case "mp3":
                return "audio/mpeg";
            case "wav":
                return "audio/wav";
            case "ogg":
                return "audio/ogg";
            case "flac":
                return "audio/flac";
            case "aac":
                return "audio/aac";
            case "m4a":
                return "audio/mp4";
            case "wma":
                return "audio/x-ms-wma";

            // 视频类型
            case "mp4":
                return "video/mp4";
            case "avi":
                return "video/x-msvideo";
            case "mov":
                return "video/quicktime";
            case "wmv":
                return "video/x-ms-wmv";
            case "flv":
                return "video/x-flv";
            case "webm":
                return "video/webm";
            case "mkv":
                return "video/x-matroska";
            case "mpeg":
            case "mpg":
                return "video/mpeg";
            case "3gp":
                return "video/3gpp";

            // 字体类型
            case "ttf":
                return "font/ttf";
            case "otf":
                return "font/otf";
            case "woff":
                return "font/woff";
            case "woff2":
                return "font/woff2";
            case "eot":
                return "application/vnd.ms-fontobject";

            // 编程文件类型
            case "java":
                return "text/x-java-source";
            case "py":
                return "text/x-python";
            case "php":
                return "application/x-httpd-php";
            case "cpp":
            case "c++":
                return "text/x-c++";
            case "c":
                return "text/x-c";
            case "h":
                return "text/x-c-header";
            case "cs":
                return "text/x-csharp";
            case "go":
                return "text/x-go";
            case "rb":
                return "text/x-ruby";
            case "pl":
                return "text/x-perl";
            case "sh":
                return "application/x-sh";
            case "bat":
                return "application/x-msdownload";
            case "ps1":
                return "application/x-powershell";

            // 数据文件类型
            case "sql":
                return "application/sql";
            case "db":
            case "sqlite":
                return "application/x-sqlite3";
            case "dbf":
                return "application/x-dbf";

            // 电子书类型
            case "epub":
                return "application/epub+zip";
            case "mobi":
                return "application/x-mobipocket-ebook";
            case "azw":
                return "application/vnd.amazon.ebook";

            // CAD文件类型
            case "dwg":
                return "image/vnd.dwg";
            case "dxf":
                return "image/vnd.dxf";

            // 其他常见类型
            case "exe":
                return "application/x-msdownload";
            case "dll":
                return "application/x-msdownload";
            case "apk":
                return "application/vnd.android.package-archive";
            case "ipa":
                return "application/x-itunes-ipa";
            case "deb":
                return "application/x-deb";
            case "rpm":
                return "application/x-rpm";
            case "iso":
                return "application/x-iso9660-image";
            case "swf":
                return "application/x-shockwave-flash";
            case "ps":
                return "application/postscript";
            case "ai":
                return "application/postscript";
            case "eps":
                return "application/postscript";

            default:
                return "application/octet-stream";
        }
    }

}
