package cn.qinys.platform.mobile.controller;

import cn.qinys.platform.base.response.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.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/dgapi/mobile/upload")
public class FileUploadController {

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

    @Value("${wishing.upload.url-prefix:/uploads}")
    private String urlPrefix;

    @PostMapping("/image")
    public Result<Map<String, String>> uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new Result<>(400, "文件为空");
        }

        String originalName = file.getOriginalFilename();
        String suffix = "";
        if (originalName != null) {
            int i = originalName.lastIndexOf('.');
            if (i > 0) suffix = originalName.substring(i);
        }

        String ym = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMM")) + "/";
        String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
        File dest = new File(uploadPath + File.separator + ym + File.separator + fileName);

        try {
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
        } catch (IOException e) {
            log.error("upload error", e);
            return new Result<>(500, "上传失败");
        }

        String url = urlPrefix + "/" + ym + fileName;
        Map<String, String> data = new HashMap<>();
        data.put("url", url);
        return new Result<>(data);
    }
}
