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.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删除图片")
    @PostMapping("/{id}")
    public R<Void> deleteImage(@PathVariable Long id) {
        if (!SecurityUtil.isUserAuthenticated()) {
            return R.fail("请先登录");
        }
        // 修复：添加权限验证，确保用户只能删除自己的图片
        if (!canModifyImage(id)) {
            return R.fail("无权删除此图片");
        }
        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 {
        // 修复：使用 try-with-resources 确保 PrintWriter 关闭
        try (PrintWriter writer = resp.getWriter()) {
            if (StrUtil.isBlank(url)) {
                resp.setStatus(404);
                writer.write("{\"code\":404,\"msg\":\"文件不存在\",\"data\":null}");
                return;
            }
            
            String sanitizedUrl = sanitizeFileName(url);
            if (sanitizedUrl == null) {
                resp.setStatus(403);
                writer.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);
                writer.write("{\"code\":403,\"msg\":\"非法文件路径\",\"data\":null}");
                return;
            }
            
            File file = filePath.toFile();
            if (!file.exists() || !file.isFile()) {
                resp.setStatus(404);
                writer.write("{\"code\":404,\"msg\":\"文件不存在\",\"data\":null}");
                return;
            }
            
            String contentTypeFromFileExtension = getContentTypeFromFileExtension(url);
            resp.setContentType(contentTypeFromFileExtension);
            resp.setContentLengthLong(file.length());
            try (FileInputStream in = new FileInputStream(file)) {
                StreamUtils.copy(in, resp.getOutputStream());
            }
        }
    }
    
    private String sanitizeFileName(String fileName) {
        if (StrUtil.isBlank(fileName)) {
            return null;
        }
        if (fileName.contains("..") || fileName.contains("/") || fileName.contains("\\") || fileName.contains(":")) {
            return null;
        }
        return fileName;
    }


    @Operation(summary = "根据url删除图片")
    @PostMapping("/deleteByUrl")
    public R<Void> deleteImageByUrl(@RequestParam String url) {
        if (!SecurityUtil.isUserAuthenticated()) {
            return R.fail("请先登录");
        }
        // 修复：添加权限验证
        if (!canModifyImageByUrl(url)) {
            return R.fail("无权删除此图片");
        }
        boolean result = imageService.deleteImageByUrl(url);
        if (result) {
            return R.success();
        } else {
            return R.fail("删除失败");
        }
    }

    @Operation(summary = "根据url批量删除图片")
    @PostMapping("/batch")
    public R<Void> deleteImageByUrls(@RequestBody List<String> urls) {
        if (!SecurityUtil.isUserAuthenticated()) {
            return R.fail("请先登录");
        }
        // 修复：添加权限验证
        for (String url : urls) {
            if (!canModifyImageByUrl(url)) {
                return R.fail("无权删除部分图片");
            }
        }
        boolean result = imageService.deleteImageByUrls(urls);
        if (result) {
            return R.success();
        } else {
            return R.fail("删除失败");
        }
    }

    /**
     * 检查当前用户是否有权限操作图片
     */
    private boolean canModifyImage(Long imageId) {
        // 从数据库查询图片所属用户
        Image image = imageService.getById(imageId);
        if (image == null) {
            return false;
        }
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (!(principal instanceof UserDetails)) {
            return false;
        }
        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 false;
        }
        return user.getId().equals(image.getUserId());
    }

    /**
     * 检查当前用户是否有权限操作图片（通过URL）
     */
    private boolean canModifyImageByUrl(String url) {
        // 从数据库查询图片所属用户
        Image image = imageService.getOne(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Image>().eq("stored_name", url));
        if (image == null) {
            return false;
        }
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (!(principal instanceof UserDetails)) {
            return false;
        }
        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 false;
        }
        return user.getId().equals(image.getUserId());
    }


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

        String extension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
        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";
        }
    }

}
