package com.ruoyi.web.controller.flood;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.file.FileUploadUtils;
import org.apache.commons.io.FilenameUtils;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.system.domain.FloodKnowledgeBase;
import com.ruoyi.system.domain.FloodKnowledgeFile;
import com.ruoyi.system.service.IFloodKnowledgeBaseService;
import com.ruoyi.system.service.IFloodKnowledgeFileService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 洪水知识库Controller
 *
 * @author jackeyhuang
 * @version 1.0.0
 * @date 2025-01-27
 */
@RestController
@RequestMapping("/flood/knowledge")
public class FloodKnowledgeBaseController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(FloodKnowledgeBaseController.class);
    
    /** kkFileView 服务地址（内部集成，使用相对路径） */
    @Value("${ruoyi.kkfileview.server-url:/kkfileview}")
    private String kkFileViewServerUrl;
    
    /** 是否启用 kkFileView */
    @Value("${ruoyi.kkfileview.enabled:true}")
    private boolean kkFileViewEnabled;

    @Autowired
    private IFloodKnowledgeBaseService floodKnowledgeBaseService;

    @Autowired
    private IFloodKnowledgeFileService floodKnowledgeFileService;

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 查询洪水知识库列表
     */
    @PreAuthorize("@ss.hasPermi('flood:knowledge:list')")
    @GetMapping("/list")
    public TableDataInfo list(FloodKnowledgeBase floodKnowledgeBase)
    {
        startPage();
        List<FloodKnowledgeBase> list = floodKnowledgeBaseService.selectFloodKnowledgeBaseList(floodKnowledgeBase);
        return getDataTable(list);
    }

    /**
     * 获取洪水知识库详细信息
     */
    @PreAuthorize("@ss.hasPermi('flood:knowledge:query')")
    @GetMapping(value = "/{knowledgeId}")
    public AjaxResult getInfo(@PathVariable("knowledgeId") Long knowledgeId)
    {
        return success(floodKnowledgeBaseService.selectFloodKnowledgeBaseByKnowledgeId(knowledgeId));
    }

    /**
     * 新增洪水知识库
     */
    @PreAuthorize("@ss.hasPermi('flood:knowledge:add')")
    @Log(title = "洪水知识库", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FloodKnowledgeBase floodKnowledgeBase)
    {
        if (!floodKnowledgeBaseService.checkKnowledgeNameUnique(floodKnowledgeBase))
        {
            return error("新增知识库'" + floodKnowledgeBase.getKnowledgeName() + "'失败，知识库名称已存在");
        }
        floodKnowledgeBase.setCreateBy(getUsername());
        int rows = floodKnowledgeBaseService.insertFloodKnowledgeBase(floodKnowledgeBase);
        if (rows > 0)
        {
            // 返回创建的知识库对象（包含knowledgeId）
            return success(floodKnowledgeBase);
        }
        return error("新增知识库失败");
    }

    /**
     * 修改洪水知识库
     */
    @PreAuthorize("@ss.hasPermi('flood:knowledge:edit')")
    @Log(title = "洪水知识库", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FloodKnowledgeBase floodKnowledgeBase)
    {
        if (!floodKnowledgeBaseService.checkKnowledgeNameUnique(floodKnowledgeBase))
        {
            return error("修改知识库'" + floodKnowledgeBase.getKnowledgeName() + "'失败，知识库名称已存在");
        }
        floodKnowledgeBase.setUpdateBy(getUsername());
        return toAjax(floodKnowledgeBaseService.updateFloodKnowledgeBase(floodKnowledgeBase));
    }

    /**
     * 删除洪水知识库
     */
    @PreAuthorize("@ss.hasPermi('flood:knowledge:remove')")
    @Log(title = "洪水知识库", businessType = BusinessType.DELETE)
    @DeleteMapping("/{knowledgeIds}")
    public AjaxResult remove(@PathVariable Long[] knowledgeIds)
    {
        return toAjax(floodKnowledgeBaseService.deleteFloodKnowledgeBaseByKnowledgeIds(knowledgeIds));
    }

    /**
     * 查询知识库文件列表
     */
    @PreAuthorize("@ss.hasPermi('flood:knowledge:list')")
    @GetMapping("/files/{knowledgeId}")
    public AjaxResult getFiles(@PathVariable("knowledgeId") Long knowledgeId)
    {
        List<FloodKnowledgeFile> list = floodKnowledgeFileService.selectFloodKnowledgeFileListByKnowledgeId(knowledgeId);
        return success(list);
    }

    /**
     * 上传知识库文件（临时上传，不关联知识库）
     */
    @PreAuthorize("@ss.hasPermi('flood:knowledge:add')")
    @Log(title = "知识库文件临时上传", businessType = BusinessType.INSERT)
    @PostMapping("/uploadTemp")
    public AjaxResult uploadTempFiles(MultipartFile[] files)
    {
        try
        {
            if (files == null || files.length == 0)
            {
                return error("上传文件不能为空");
            }

            // 允许的文件类型：图片、PDF、Word、PPT等
            String[] allowedExtensions = new String[]{"jpg", "jpeg", "png", "gif", "bmp", "pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "txt"};
            
            String uploadPath = RuoYiConfig.getUploadPath();
            List<Map<String, Object>> fileInfoList = new ArrayList<>();
            StringBuilder errorMsg = new StringBuilder();

            for (MultipartFile file : files)
            {
                try
                {
                    // 上传文件
                    String fileName = FileUploadUtils.upload(uploadPath, file, allowedExtensions);
                    String fileUrl = serverConfig.getUrl() + fileName;
                    
                    // 获取文件扩展名
                    String fileType = FilenameUtils.getExtension(fileName).toLowerCase();
                    
                    // 构建文件路径：FileUploadUtils.upload返回的是 /profile/upload/2026/01/11/xxx.pdf 格式
                    // 需要转换为实际文件路径存储：profile + /upload/2026/01/11/xxx.pdf
                    String actualFilePath;
                    if (fileName.startsWith("/profile/"))
                    {
                        // fileName是 /profile/upload/... 格式，去掉 /profile/ 前缀得到 upload/...
                        String relativePath = fileName.substring("/profile/".length()); // 去掉 /profile/ 前缀
                        // 使用profile路径拼接（profile = upload，所以结果是 upload/upload/2026/01/11/xxx.pdf）
                        actualFilePath = RuoYiConfig.getProfile() + java.io.File.separator + relativePath;
                    }
                    else if (fileName.startsWith("/"))
                    {
                        // 以 / 开头但不是 /profile/，去掉开头的 /
                        actualFilePath = RuoYiConfig.getProfile() + java.io.File.separator + fileName.substring(1);
                    }
                    else
                    {
                        // 直接使用fileName
                        actualFilePath = RuoYiConfig.getProfile() + java.io.File.separator + fileName;
                    }
                    
                    // 保存文件信息（不关联知识库，knowledgeId为null）
                    FloodKnowledgeFile knowledgeFile = new FloodKnowledgeFile();
                    knowledgeFile.setKnowledgeId(null); // 临时文件，不关联知识库
                    knowledgeFile.setFileName(fileName);
                    knowledgeFile.setOriginalName(file.getOriginalFilename());
                    knowledgeFile.setFilePath(actualFilePath);
                    knowledgeFile.setFileType(fileType);
                    knowledgeFile.setFileSize(file.getSize());
                    knowledgeFile.setFileUrl(fileUrl);
                    knowledgeFile.setStatus("0");
                    knowledgeFile.setCreateBy(getUsername());
                    
                    floodKnowledgeFileService.insertFloodKnowledgeFile(knowledgeFile);
                    
                    // 返回文件信息
                    Map<String, Object> fileInfo = new HashMap<>();
                    fileInfo.put("fileId", knowledgeFile.getFileId());
                    fileInfo.put("fileName", fileName);
                    fileInfo.put("originalName", file.getOriginalFilename());
                    fileInfo.put("fileType", fileType);
                    fileInfo.put("fileSize", file.getSize());
                    fileInfo.put("fileUrl", fileUrl);
                    fileInfoList.add(fileInfo);
                }
                catch (Exception e)
                {
                    errorMsg.append(file.getOriginalFilename()).append("上传失败：").append(e.getMessage()).append("; ");
                }
            }

            if (!fileInfoList.isEmpty())
            {
                Map<String, Object> result = new HashMap<>();
                result.put("files", fileInfoList);
                result.put("successCount", fileInfoList.size());
                if (errorMsg.length() > 0)
                {
                    result.put("errorMsg", errorMsg.toString());
                }
                return success(result);
            }
            else
            {
                return error("所有文件上传失败：" + errorMsg.toString());
            }
        }
        catch (Exception e)
        {
            return error("上传文件异常：" + e.getMessage());
        }
    }

    /**
     * 关联文件到知识库
     */
    @PreAuthorize("@ss.hasPermi('flood:knowledge:add')")
    @Log(title = "关联文件到知识库", businessType = BusinessType.UPDATE)
    @PutMapping("/associateFiles")
    public AjaxResult associateFiles(@RequestBody Map<String, Object> params)
    {
        try
        {
            // 处理knowledgeId（可能是Integer或Long）
            Object knowledgeIdObj = params.get("knowledgeId");
            Long knowledgeId = null;
            if (knowledgeIdObj != null)
            {
                if (knowledgeIdObj instanceof Long)
                {
                    knowledgeId = (Long) knowledgeIdObj;
                }
                else if (knowledgeIdObj instanceof Integer)
                {
                    knowledgeId = ((Integer) knowledgeIdObj).longValue();
                }
                else
                {
                    knowledgeId = Long.valueOf(knowledgeIdObj.toString());
                }
            }
            
            if (knowledgeId == null)
            {
                return error("知识库ID不能为空");
            }
            
            // 处理fileIds（可能是Integer或Long的列表）
            @SuppressWarnings("unchecked")
            List<Object> fileIdsObj = (List<Object>) params.get("fileIds");
            
            if (fileIdsObj == null || fileIdsObj.isEmpty())
            {
                return error("文件ID列表不能为空");
            }
            
            // 转换为Long列表
            List<Long> fileIds = new ArrayList<>();
            for (Object fileIdObj : fileIdsObj)
            {
                if (fileIdObj instanceof Long)
                {
                    fileIds.add((Long) fileIdObj);
                }
                else if (fileIdObj instanceof Integer)
                {
                    fileIds.add(((Integer) fileIdObj).longValue());
                }
                else
                {
                    fileIds.add(Long.valueOf(fileIdObj.toString()));
                }
            }
            
            int successCount = 0;
            for (Long fileId : fileIds)
            {
                FloodKnowledgeFile file = floodKnowledgeFileService.selectFloodKnowledgeFileByFileId(fileId);
                if (file != null && file.getKnowledgeId() == null)
                {
                    file.setKnowledgeId(knowledgeId);
                    floodKnowledgeFileService.updateFloodKnowledgeFile(file);
                    successCount++;
                }
            }
            
            // 更新知识库的文件数量
            FloodKnowledgeBase knowledgeBase = floodKnowledgeBaseService.selectFloodKnowledgeBaseByKnowledgeId(knowledgeId);
            if (knowledgeBase != null)
            {
                List<FloodKnowledgeFile> fileList = floodKnowledgeFileService.selectFloodKnowledgeFileListByKnowledgeId(knowledgeId);
                knowledgeBase.setFileCount(fileList != null ? fileList.size() : 0);
                floodKnowledgeBaseService.updateFloodKnowledgeBase(knowledgeBase);
            }
            
            return success("成功关联 " + successCount + " 个文件到知识库");
        }
        catch (Exception e)
        {
            return error("关联文件失败：" + e.getMessage());
        }
    }

    /**
     * 上传知识库文件
     */
    @PreAuthorize("@ss.hasPermi('flood:knowledge:add')")
    @Log(title = "知识库文件上传", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    public AjaxResult uploadFile(Long knowledgeId, MultipartFile[] files)
    {
        try
        {
            if (files == null || files.length == 0)
            {
                return error("上传文件不能为空");
            }
            if (knowledgeId == null)
            {
                return error("知识库ID不能为空");
            }

            // 允许的文件类型：图片、PDF、Word、PPT等
            String[] allowedExtensions = new String[]{"jpg", "jpeg", "png", "gif", "bmp", "pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "txt"};
            
            String uploadPath = RuoYiConfig.getUploadPath();
            int successCount = 0;
            StringBuilder errorMsg = new StringBuilder();

            for (MultipartFile file : files)
            {
                try
                {
                    // 上传文件
                    String fileName = FileUploadUtils.upload(uploadPath, file, allowedExtensions);
                    String fileUrl = serverConfig.getUrl() + fileName;
                    
                    // 获取文件扩展名
                    String fileType = FilenameUtils.getExtension(fileName).toLowerCase();
                    
                    // 构建文件路径：FileUploadUtils.upload返回的是 /profile/upload/2026/01/11/xxx.pdf 格式
                    // 需要转换为实际文件路径存储：uploadPath + /upload/2026/01/11/xxx.pdf
                    String actualFilePath;
                    if (fileName.startsWith("/profile/"))
                    {
                        // fileName是 /profile/upload/... 格式，去掉 /profile/ 前缀得到 upload/...
                        String relativePath = fileName.substring("/profile/".length());
                        // uploadPath 已经是完整路径（如 upload/upload），直接拼接相对路径
                        actualFilePath = RuoYiConfig.getProfile() + java.io.File.separator + relativePath;
                    }
                    else if (fileName.startsWith("/"))
                    {
                        // 以 / 开头但不是 /profile/，去掉开头的 /
                        actualFilePath = RuoYiConfig.getProfile() + java.io.File.separator + fileName.substring(1);
                    }
                    else
                    {
                        // 直接使用fileName
                        actualFilePath = RuoYiConfig.getProfile() + java.io.File.separator + fileName;
                    }
                    
                    // 保存文件信息
                    FloodKnowledgeFile knowledgeFile = new FloodKnowledgeFile();
                    knowledgeFile.setKnowledgeId(knowledgeId);
                    knowledgeFile.setFileName(fileName);
                    knowledgeFile.setOriginalName(file.getOriginalFilename());
                    knowledgeFile.setFilePath(actualFilePath);
                    knowledgeFile.setFileType(fileType);
                    knowledgeFile.setFileSize(file.getSize());
                    knowledgeFile.setFileUrl(fileUrl);
                    knowledgeFile.setStatus("0");
                    knowledgeFile.setCreateBy(getUsername());
                    
                    floodKnowledgeFileService.insertFloodKnowledgeFile(knowledgeFile);
                    successCount++;
                }
                catch (Exception e)
                {
                    errorMsg.append(file.getOriginalFilename()).append("上传失败：").append(e.getMessage()).append("; ");
                }
            }

            if (successCount > 0)
            {
                return success("成功上传 " + successCount + " 个文件" + (errorMsg.length() > 0 ? "，" + errorMsg.toString() : ""));
            }
            else
            {
                return error("所有文件上传失败：" + errorMsg.toString());
            }
        }
        catch (Exception e)
        {
            return error("上传文件异常：" + e.getMessage());
        }
    }

    /**
     * 删除知识库文件
     */
    @PreAuthorize("@ss.hasPermi('flood:knowledge:remove')")
    @Log(title = "知识库文件", businessType = BusinessType.DELETE)
    @DeleteMapping("/files/{fileIds}")
    public AjaxResult removeFiles(@PathVariable Long[] fileIds)
    {
        return toAjax(floodKnowledgeFileService.deleteFloodKnowledgeFileByFileIds(fileIds));
    }

    /**
     * 获取文件信息（返回文件信息的JSON）
     */
    @PreAuthorize("@ss.hasPermi('flood:knowledge:query')")
    @GetMapping("/fileInfo/{fileId}")
    public AjaxResult getFileInfo(@PathVariable("fileId") Long fileId)
    {
        FloodKnowledgeFile file = floodKnowledgeFileService.selectFloodKnowledgeFileByFileId(fileId);
        if (file == null)
        {
            return error("文件不存在");
        }
        return success(file);
    }

    /**
     * 预览文件（通用接口，支持PDF、Word、Excel、PPT等）
     * 注意：此接口允许通过token参数进行认证，以支持Office Online Viewer等在线预览服务
     */
    @com.ruoyi.common.annotation.Anonymous  // 允许匿名访问（通过token参数进行认证）
    @GetMapping("/preview/{fileId}")
    public void previewFile(@PathVariable("fileId") Long fileId, 
                           @RequestParam(value = "token", required = false) String token,
                           HttpServletRequest request,
                           HttpServletResponse response)
    {
        try
        {
            FloodKnowledgeFile file = floodKnowledgeFileService.selectFloodKnowledgeFileByFileId(fileId);
            if (file == null)
            {
                log.warn("文件不存在，fileId: {}", fileId);
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            // 读取文件
            String filePath = file.getFilePath();
            if (filePath == null || filePath.trim().isEmpty())
            {
                log.error("文件路径为空，fileId: {}, fileName: {}", fileId, file.getFileName());
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            // 构建文件路径
            // filePath可能存储的是相对路径（如 upload/upload/2026/01/11/xxx.pdf）或绝对路径
            // 也可能存储的是错误的路径（如 upload/upload//profile/upload/...），需要修复
            java.io.File targetFile;
            if (new java.io.File(filePath).isAbsolute())
            {
                // 绝对路径，直接使用
                targetFile = new java.io.File(filePath);
            }
            else
            {
                // 相对路径，需要处理
                String normalizedPath = filePath;
                
                // 修复错误的路径格式：upload/upload//profile/upload/... -> upload/upload/...
                if (normalizedPath.contains("//profile/"))
                {
                    // 去掉 //profile/ 部分，保留后面的路径
                    normalizedPath = normalizedPath.substring(normalizedPath.indexOf("//profile/") + "//profile/".length());
                    // 如果前面还有 upload/upload，去掉重复的
                    if (normalizedPath.startsWith("upload/"))
                    {
                        normalizedPath = normalizedPath.substring("upload/".length());
                    }
                    normalizedPath = "upload/" + normalizedPath;
                }
                else if (normalizedPath.startsWith("upload/upload/"))
                {
                    // 去掉重复的upload
                    normalizedPath = normalizedPath.substring("upload/".length());
                }
                
                // 使用profile路径拼接
                String profilePath = RuoYiConfig.getProfile();
                targetFile = new java.io.File(profilePath + java.io.File.separator + normalizedPath);
            }
            
            if (!targetFile.exists())
            {
                log.error("文件不存在于磁盘，fileId: {}, filePath: {}, normalizedPath: {}, absolutePath: {}, profilePath: {}", 
                    fileId, filePath, targetFile.getAbsolutePath(), RuoYiConfig.getProfile());
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            // 根据文件类型设置Content-Type
            String contentType = getContentType(file.getFileType());
            response.setContentType(contentType);
            response.setHeader("Content-Disposition", "inline; filename=\"" + 
                java.net.URLEncoder.encode(file.getOriginalName(), "UTF-8") + "\"");
            response.setHeader("Cache-Control", "public, max-age=3600");
            response.setHeader("X-Frame-Options", "SAMEORIGIN"); // 允许同源iframe嵌入
            
            // 设置文件大小
            response.setContentLengthLong(targetFile.length());

            // 读取文件并写入响应
            try (java.io.FileInputStream fis = new java.io.FileInputStream(targetFile);
                 java.io.OutputStream os = response.getOutputStream())
            {
                byte[] buffer = new byte[8192];
                int bytesRead;
                while ((bytesRead = fis.read(buffer)) != -1)
                {
                    os.write(buffer, 0, bytesRead);
                }
                os.flush();
            }
        }
        catch (Exception e)
        {
            log.error("预览文件失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 预览PDF文件（代理文件流，支持认证）- 保持向后兼容
     */
    @PreAuthorize("@ss.hasPermi('flood:knowledge:query')")
    @GetMapping("/previewPdf/{fileId}")
    public void previewPdfFile(@PathVariable("fileId") Long fileId, 
                               @RequestParam(value = "token", required = false) String token,
                               HttpServletRequest request,
                               HttpServletResponse response)
    {
        // 重定向到通用预览接口
        previewFile(fileId, token, request, response);
    }

    /**
     * 获取 kkFileView 预览URL
     * 
     * @param fileId 文件ID
     * @param token 认证token（可选）
     * @return kkFileView 预览URL
     */
    @PreAuthorize("@ss.hasPermi('flood:knowledge:query')")
    @GetMapping("/previewKkFileView/{fileId}")
    public AjaxResult getKkFileViewUrl(@PathVariable("fileId") Long fileId,
                                       @RequestParam(value = "token", required = false) String token)
    {
        if (!kkFileViewEnabled)
        {
            return error("kkFileView 服务未启用");
        }
        
        try
        {
            FloodKnowledgeFile file = floodKnowledgeFileService.selectFloodKnowledgeFileByFileId(fileId);
            if (file == null)
            {
                return error("文件不存在");
            }
            
            // 构建文件访问URL（包含token认证）
            String fileUrl = serverConfig.getUrl() + "/flood/knowledge/preview/" + fileId;
            if (token != null && !token.isEmpty())
            {
                fileUrl += "?token=" + java.net.URLEncoder.encode(token, "UTF-8");
            }
            
            // kkFileView 需要 Base64 编码的 URL
            String base64Url = java.util.Base64.getEncoder().encodeToString(fileUrl.getBytes("UTF-8"));
            // 构建预览URL
            String previewUrl;
            if (kkFileViewServerUrl.startsWith("http://") || kkFileViewServerUrl.startsWith("https://"))
            {
                // 外部服务，直接使用完整URL
                previewUrl = kkFileViewServerUrl + "/onlinePreview?url=" + java.net.URLEncoder.encode(base64Url, "UTF-8");
            }
            else
            {
                // 内部集成，需要转换为完整URL（前端iframe需要完整URL）
                String baseUrl = serverConfig.getUrl();
                previewUrl = baseUrl + kkFileViewServerUrl + "/onlinePreview?url=" + java.net.URLEncoder.encode(base64Url, "UTF-8");
            }
            
            return success().put("previewUrl", previewUrl).put("fileUrl", fileUrl);
        }
        catch (Exception e)
        {
            log.error("获取 kkFileView 预览URL失败", e);
            return error("获取预览URL失败：" + e.getMessage());
        }
    }

    /**
     * 获取文件的Content-Type
     */
    private String getContentType(String fileType)
    {
        if (fileType == null)
        {
            return "application/octet-stream";
        }
        
        String lowerType = fileType.toLowerCase();
        switch (lowerType)
        {
            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 "jpg":
            case "jpeg":
                return "image/jpeg";
            case "png":
                return "image/png";
            case "gif":
                return "image/gif";
            case "bmp":
                return "image/bmp";
            default:
                return "application/octet-stream";
        }
    }
}
