package com.xunhong.erp.turbo.base.utils;

import cn.hutool.core.date.LocalDateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 文件上传工具类
 *
 * @author system
 */
@Slf4j
public class FileUploadUtil {

    /**
     * 安全获取文件名（处理后缀问题）
     *
     * @param file 上传的文件
     * @return 处理后的安全文件名
     */
    public static String getSafeFileName(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();

        log.debug("原始文件名: {}, Content-Type: {}", originalFilename, file.getContentType());

        // 如果原始文件名为空或无效，生成默认文件名
        if (StringUtils.isBlank(originalFilename)) {
            String generatedName = generateDefaultFileName(file);
            log.warn("原始文件名为空，生成文件名: {}", generatedName);
            return generatedName;
        }

        // 检查文件名是否包含后缀
        if (!containsFileExtension(originalFilename)) {
            // 尝试从Content-Type推断文件类型
            String extension = getExtensionFromContentType(file.getContentType());
            if (extension != null) {
                String fileNameWithExt = originalFilename + "." + extension;
                log.info("文件名缺少后缀，从Content-Type推断: {} -> {}", originalFilename, fileNameWithExt);
                return fileNameWithExt;
            } else {
                log.warn("无法推断文件后缀，使用原始文件名: {}", originalFilename);
            }
        }

        return originalFilename;
    }

    /**
     * 生成唯一的文件对象名
     *
     * @param file 上传的文件
     * @return 生成的对象名
     */
    public static String generateObjectName(MultipartFile file) {
        String safeFileName = getSafeFileName(file);
        String datePath = LocalDateTimeUtil.format(LocalDateTime.now(), "yyMM/dd");
        return "uploads/" + datePath + "/" + safeFileName;
    }

    /**
     * 检查文件名是否包含后缀
     *
     * @param filename 文件名
     * @return 是否包含后缀
     */
    private static boolean containsFileExtension(String filename) {
        if (filename == null) return false;
        int lastDotIndex = filename.lastIndexOf('.');
        return lastDotIndex > 0 && lastDotIndex < filename.length() - 1;
    }

    /**
     * 从Content-Type推断文件扩展名
     *
     * @param contentType MIME类型
     * @return 文件扩展名，如果无法推断则返回null
     */
    private static String getExtensionFromContentType(String contentType) {
        if (contentType == null) return null;

        switch (contentType.toLowerCase()) {
            // 图片类型
            case "image/jpeg":
                return "jpeg";
            case "image/jpg":
                return "jpg";
            case "image/png":
                return "png";
            case "image/gif":
                return "gif";
            case "image/webp":
                return "webp";
            case "image/bmp":
                return "bmp";
            case "image/svg+xml":
                return "svg";

            // 文档类型
            case "application/pdf":
                return "pdf";
            case "application/msword":
                return "doc";
            case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
                return "docx";
            case "application/vnd.ms-excel":
                return "xls";
            case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
                return "xlsx";

            // 文本类型
            case "text/plain":
                return "txt";
            case "text/csv":
                return "csv";
            case "application/json":
                return "json";
            case "application/xml":
                return "xml";

            // 压缩文件
            case "application/zip":
                return "zip";
            case "application/x-rar-compressed":
                return "rar";

            default:
                log.debug("未知的Content-Type: {}", contentType);
                return null;
        }
    }

    /**
     * 生成默认文件名
     *
     * @param file 上传的文件
     * @return 生成的文件名
     */
    private static String generateDefaultFileName(MultipartFile file) {
        String timestamp = LocalDateTimeUtil.format(LocalDateTime.now(), "yyyyMMddHHmmss");
        String randomId = UUID.randomUUID().toString().substring(0, 8);
        String extension = getExtensionFromContentType(file.getContentType());

        return extension != null ?
            "file_" + timestamp + "_" + randomId + "." + extension :
            "file_" + timestamp + "_" + randomId;
    }

    /**
     * 验证文件类型是否允许上传
     *
     * @param file 上传的文件
     * @param allowedExtensions 允许的文件扩展名数组
     * @return 是否允许上传
     */
    public static boolean isAllowedFileType(MultipartFile file, String[] allowedExtensions) {
        String fileName = getSafeFileName(file);
        if (fileName == null) return false;

        int lastDotIndex = fileName.lastIndexOf('.');
        if (lastDotIndex == -1) return false;

        String extension = fileName.substring(lastDotIndex + 1).toLowerCase();

        for (String allowedExt : allowedExtensions) {
            if (allowedExt.toLowerCase().equals(extension)) {
                return true;
            }
        }

        return false;
    }
}
