package com.test.bijihoudaun.controller;


import cn.hutool.core.util.StrUtil;
import com.test.bijihoudaun.common.response.R;
import com.test.bijihoudaun.entity.Image;
import com.test.bijihoudaun.entity.User;
import com.test.bijihoudaun.service.ImageService;
import com.test.bijihoudaun.service.UserService;
import com.test.bijihoudaun.util.SecurityUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@Tag(name = "图片接口")
@RestController
@RequestMapping("/api/images")
public class ImageController {

    @Value("${file.upload-dir}")
    private String rootPath;

    @Autowired
    private ImageService imageService;

    @Autowired
    private UserService userService;

    @Operation(summary = "上传图片")
    @PostMapping
    public R<Image> uploadImage(
            @RequestPart("file") MultipartFile file,
            @RequestParam(value = "markdownId", required = false) Long markdownId) {
        // 修复：从SecurityContext获取当前用户，不接受客户端传入的userId
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (!(principal instanceof UserDetails)) {
            return R.fail("请先登录");
        }
        String username = ((UserDetails) principal).getUsername();
        User user = userService.getOne(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<User>().eq("username", username));
        if (user == null) {
            return R.fail("用户不存在");
        }

        try {
            Image image = imageService.uploadImage(file, user.getId(), markdownId);
            return R.success(image);
        } catch (IOException e) {
            return R.fail("上传失败：" + e.getMessage());
        }
    }

    @Operation(summary = "根据id删除图片")
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/{id}")
    public R<Void> deleteImage(@PathVariable Long id) {
        boolean result = imageService.deleteImage(id);
        if (result) {
            return R.success();
        } else {
            return R.fail("删除失败");
        }
    }

    @Operation(summary = "在线预览", description = "浏览器直接打开文件流")
    @GetMapping("/preview/{url}")
    public void preview(@PathVariable String url, HttpServletResponse resp) throws IOException {
        // 注意：不能同时调用 resp.getWriter() 和 resp.getOutputStream()
        
        if (StrUtil.isBlank(url)) {
            resp.setStatus(404);
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write("{\"code\":404,\"msg\":\"文件不存在\",\"data\":null}");
            return;
        }
        
        String sanitizedUrl = sanitizeFileName(url);
        if (sanitizedUrl == null) {
            resp.setStatus(403);
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write("{\"code\":403,\"msg\":\"非法文件路径\",\"data\":null}");
            return;
        }
        
        Path basePath = Paths.get(rootPath).normalize().toAbsolutePath();
        Path filePath = basePath.resolve(sanitizedUrl).normalize();
        
        if (!filePath.startsWith(basePath)) {
            resp.setStatus(403);
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write("{\"code\":403,\"msg\":\"非法文件路径\",\"data\":null}");
            return;
        }
        
        File file = filePath.toFile();
        if (!file.exists() || !file.isFile()) {
            resp.setStatus(404);
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write("{\"code\":404,\"msg\":\"文件不存在\",\"data\":null}");
            return;
        }
        
        String contentTypeFromFileExtension = getContentTypeFromFileExtension(url);
        resp.setContentType(contentTypeFromFileExtension);
        resp.setContentLengthLong(file.length());
        // 文件流直接输出，不使用 try-with-resources 包装整个方法
        try (FileInputStream in = new FileInputStream(file)) {
            StreamUtils.copy(in, resp.getOutputStream());
            resp.getOutputStream().flush();
        }
    }
    
    private String sanitizeFileName(String fileName) {
        if (StrUtil.isBlank(fileName)) {
            return null;
        }
        // 修复：使用白名单验证文件名格式（只允许 UUID 格式）
        // 例如：550e8400-e29b-41d4-a716-446655440000.jpg
        if (!fileName.matches("^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\\.[a-zA-Z0-9]+$")) {
            return null;
        }
        return fileName;
    }


    @Operation(summary = "根据url删除图片")
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/deleteByUrl")
    public R<Void> deleteImageByUrl(@RequestParam String url) {
        boolean result = imageService.deleteImageByUrl(url);
        if (result) {
            return R.success();
        } else {
            return R.fail("删除失败");
        }
    }

    @Operation(summary = "根据url批量删除图片")
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/batch")
    public R<Void> deleteImageByUrls(@RequestBody List<String> urls) {
        boolean result = imageService.deleteImageByUrls(urls);
        if (result) {
            return R.success();
        } else {
            return R.fail("删除失败");
        }
    }

    private String getContentTypeFromFileExtension(String fileName) {
        if (StrUtil.isBlank(fileName) || !StrUtil.contains(fileName, '.')) {
            return "application/octet-stream";
        }

        String extension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
        // 使用更安全的 MIME 类型映射，只允许图片类型
        switch (extension) {
            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";
            default:
                // 对于未知的扩展名，返回通用的二进制流类型，避免执行风险
                return "application/octet-stream";
        }
    }
    
    /**
     * 验证文件是否为允许的图片类型
     * @param contentType 文件内容类型
     * @return 是否允许
     */
    private boolean isAllowedImageType(String contentType) {
        if (StrUtil.isBlank(contentType)) {
            return false;
        }
        // 只允许标准的图片 MIME 类型
        return contentType.equals("image/jpeg") ||
               contentType.equals("image/png") ||
               contentType.equals("image/gif") ||
               contentType.equals("image/bmp") ||
               contentType.equals("image/webp") ||
               contentType.equals("image/svg+xml");
    }

}
