package com.ruoyi.xq.controller.app;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.vo.SysOssVo;
import com.ruoyi.system.service.ISysOssService;
import com.ruoyi.xq.dto.app.common.FileResp;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/file")
@Tag(name = "文件接口")
@Slf4j
public class FileController {

    @Autowired
    private ISysOssService iSysOssService;

    @Log(title = "OSS对象存储", businessType = BusinessType.INSERT)
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "上传文件",
            parameters = {
                    @Parameter(name = "file", description = "文件", required = true),
                    @Parameter(name = "type", description = "业务类型，dynamic=动态图片，user=用户相关，im=聊天，common=其他", required = false)
            })
    public R<FileResp> upload(@RequestPart("file") MultipartFile file,
                              String type) {
        log.error("上传文件图片类型 type={}",type);
        if (ObjectUtil.isNull(file)) {
            return R.fail("上传文件不能为空");
        }
        SysOssVo oss = iSysOssService.upload(file);
        FileResp resp = new FileResp();
        resp.setUrl(oss.getUrl());
        resp.setPath(oss.getFileName());
        resp.setOriginalName(oss.getOriginalName());
        return R.ok(resp);
    }


    @Log(title = "OSS对象存储", businessType = BusinessType.INSERT)
    @PostMapping(value = "/uploadImage", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "上传图片类型的文件",
            parameters = {
                    @Parameter(name = "file", description = "文件", required = true),
                    @Parameter(name = "type", description = "业务类型，dynamic=动态图片，user=用户相关，im=聊天，common=其他", required = false)
            })
    public R<FileResp> uploadImage(@RequestPart("file") MultipartFile file,
                              String type) {
        log.error("上传文件图片类型 type={}",type);
        if (ObjectUtil.isNull(file)) {
            return R.fail("上传文件不能为空");
        }
        SysOssVo oss = iSysOssService.upload(file);
        FileResp resp = new FileResp();
        resp.setUrl(oss.getUrl());
        resp.setPath(oss.getFileName());
        resp.setOriginalName(oss.getOriginalName());
        return R.ok(resp);
    }

}
