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.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
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 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 fileName = file.getOriginalFilename();
        AssertUtil.notBlank(fileName, "文件名为空");

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

        // 文件路径
        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();

        OSS ossClient = getOssClient();

        // 上传文件
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(obsConfig.getBucketName(), objectKey, file.getInputStream());
            ossClient.putObject(putObjectRequest);
        } catch (Exception e) {
            throw new ServiceException("上传失败");
        } finally {
            ossClient.shutdown();
        }

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

    private OSS getOssClient() {
        return new OSSClientBuilder().build(obsConfig.getEndPoint(), obsConfig.getAk(), obsConfig.getSk());
    }

    private String getUrl() {
        return "https://" + obsConfig.getBucketName() + "." + obsConfig.getEndPoint() + "/";
    }

}
