package com.kym.admin.controller;

import cn.hutool.core.io.FileUtil;
import com.kym.common.R;
import com.kym.common.annotation.ApiLog;
import com.kym.common.controller.IController;
import com.kym.common.utils.CommUtil;
import com.kym.service.miniapp.AttachmentService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


/**
 * @author skyline
 * @description 文件上传
 * @date 2023-07-29 10:54
 */
@RestController
@RequestMapping("/file")
public class FileController extends IController {

    @Resource
    private AttachmentService attachmentService;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<?> upload(MultipartFile file) {
        var fileName = file.getOriginalFilename();
        CommUtil.asserts(!CommUtil.isExecutable(FileUtil.getSuffix(fileName)), "上传文件类型不支持");
        return resp(() -> {
            try {
                return attachmentService.upload(file);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }


    @ApiLog("文件删除")
    @PostMapping("/delete/{fileId}")
    public R<?> delete(@PathVariable String fileId) {
        CommUtil.asserts(!CommUtil.isEmptyOrNull(fileId), "删除文件不能为空");
        return resp((t) -> attachmentService.delete(fileId));
    }

}
