package com.haha.admin.controller;

import com.haha.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
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 java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传控制器
 */
@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController {

    @Value("${upload.path:./upload}")
    private String rawUploadPath;

    private Path uploadBasePath;

    /** 懒加载解析上传路径（避免 @PostConstruct 在 Spring Boot 4.x 的兼容问题） */
    private Path getUploadBasePath() {
        if (uploadBasePath == null) {
            synchronized (this) {
                if (uploadBasePath == null) {
                    Path path = Paths.get(rawUploadPath);
                    if (!path.isAbsolute()) {
                        path = Paths.get(System.getProperty("user.dir")).resolve(rawUploadPath).normalize();
                    }
                    uploadBasePath = path;
                    log.info("上传文件存储路径: {}", uploadBasePath.toAbsolutePath());
                }
            }
        }
        return uploadBasePath;
    }

    @PostMapping
    public Result<Map<String, Object>> upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("上传文件不能为空");
        }

        try {
            // 按日期分目录
            String dateDir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            Path uploadDir = getUploadBasePath().resolve("images").resolve(dateDir);
            Files.createDirectories(uploadDir);

            // 生成唯一文件名
            String originalName = file.getOriginalFilename();
            String ext = "";
            if (originalName != null && originalName.contains(".")) {
                ext = originalName.substring(originalName.lastIndexOf("."));
            }
            String fileName = UUID.randomUUID().toString().replace("-", "") + ext;

            // 保存文件
            Path targetPath = uploadDir.resolve(fileName);
            file.transferTo(targetPath.toFile());

            // 返回访问URL
            String url = "/upload/images/" + dateDir + "/" + fileName;

            Map<String, Object> data = new HashMap<>();
            data.put("url", url);

            log.info("文件上传成功: {} -> {}", originalName, targetPath);
            return Result.success("上传成功", data);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return Result.error("文件上传失败: " + e.getMessage());
        }
    }
}
