package com.jy.system.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.jy.framework.config.JyConfig;
import com.jy.framework.config.ObsConfig;
import com.jy.framework.exception.ServiceException;
import com.jy.framework.utils.AssertUtil;
import com.obs.services.ObsClient;
import jakarta.annotation.Resource;
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.util.Date;
import java.util.Map;
import java.util.StringJoiner;

@RestController
@RequestMapping("/file")
public class FileConfig {

    @Resource
    private ObsConfig obsConfig;

    @Resource
    private JyConfig jsonConfig;

    @Value("${spring.profiles.active}")
    private String active;

    @PostMapping("/upload")
    public Map<String, String> uploadFile(@RequestParam("file") MultipartFile file) {
        AssertUtil.notEmpty(file, "文件不存在");

        String oriName = file.getOriginalFilename();
        AssertUtil.notBlank(oriName, "文件名为空");

        // 文件后缀名
        String suffix = FileUtil.getSuffix(oriName);

        // 文件路径
        String objectKey = new StringJoiner("/")
                .add(jsonConfig.getProjectName())
                .add(active)
                .add(DateUtil.format(new Date(), "yyyy/MM/dd"))
                .add(IdUtil.fastSimpleUUID() + (ObjectUtil.isEmpty(suffix) ? "" : "." + suffix))
                .toString();

        // 上传文件
        try (ObsClient obsClient = new ObsClient(obsConfig.getAk(), obsConfig.getSk(), obsConfig.getEndPoint())) {
            obsClient.putObject(obsConfig.getBucketName(), objectKey, file.getInputStream());
        } catch (Exception e) {
            throw new ServiceException("上传失败");
        }

        // 返回文件路径
        return Map.of("name", oriName, "url", obsConfig.getUrl() + objectKey);
    }

}
