package com.ruoyi.kkfileview.controller;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.kkfileview.config.KkFileViewConfig;
import com.ruoyi.kkfileview.service.FilePreviewService;

/**
 * kkFileView 在线预览控制器
 * 
 * @author jackeyhuang
 * @version 1.0.0
 * @date 2026-01-11
 */
@Controller
@RequestMapping("/kkfileview")
@Anonymous  // 允许匿名访问（因为预览接口会通过token参数进行认证）
public class OnlinePreviewController
{
    private static final Logger log = LoggerFactory.getLogger(OnlinePreviewController.class);

    @Autowired
    private KkFileViewConfig config;
    
    @Autowired(required = false)
    private FilePreviewService filePreviewService;

    /**
     * 在线预览接口
     * 
     * @param url 文件URL（Base64编码）
     * @param request HTTP请求
     * @param response HTTP响应
     */
    @RequestMapping("/onlinePreview")
    public void onlinePreview(@RequestParam(value = "url", required = false) String url,
                              HttpServletRequest request,
                              HttpServletResponse response)
    {
        // 允许在iframe中加载（kkFileView预览需要）
        response.setHeader("X-Frame-Options", "SAMEORIGIN");
        
        if (!config.isEnabled())
        {
            try
            {
                response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().write("kkFileView 服务未启用");
            }
            catch (IOException e)
            {
                log.error("写入响应失败", e);
            }
            return;
        }

        try
        {
            if (url == null || url.isEmpty())
            {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().write("文件URL参数不能为空");
                return;
            }

            // 解码Base64 URL
            String decodedUrl = new String(Base64.getDecoder().decode(url), StandardCharsets.UTF_8);
            log.info("预览文件URL: {}", decodedUrl);

            // 如果有预览服务，调用预览服务
            if (filePreviewService != null)
            {
                filePreviewService.previewFile(decodedUrl, request, response);
            }
            else
            {
                // 临时方案：重定向到文件URL（让浏览器处理）
                // 注意：这只是一个占位实现，实际需要集成 kkFileView 的完整功能
                // 或者使用其他预览方案（如前端直接预览）
                response.sendRedirect(decodedUrl);
            }
        }
        catch (Exception e)
        {
            log.error("文件预览失败", e);
            try
            {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().write("文件预览失败：" + e.getMessage());
            }
            catch (IOException ioException)
            {
                log.error("写入错误响应失败", ioException);
            }
        }
    }

    /**
     * 检查服务状态
     */
    @RequestMapping("/status")
    @ResponseBody
    public AjaxResult status()
    {
        return AjaxResult.success()
            .put("enabled", config.isEnabled())
            .put("status", config.isEnabled() ? "运行中" : "未启用")
            .put("fileSaveDir", config.getFileSaveDir())
            .put("previewTypes", config.getPreviewTypes());
    }
}
