package com.microservices.file.controller;

import com.microservices.common.core.domain.R;
import com.microservices.common.core.web.controller.BaseController;
import com.microservices.common.security.annotation.InnerAuth;
import com.microservices.file.service.ISysFileInfoService;
import com.microservices.system.api.domain.SysFile;
import com.microservices.system.api.domain.SysFileInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 文件请求处理
 *
 * @author microservices
 */
@RestController
@ApiIgnore
public class SysFileController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    @Autowired
    private ISysFileInfoService sysFileInfoService;

    /**
     * 文件上传请求
     */
    @InnerAuth
    @PostMapping("upload")
    public R<SysFile> upload(MultipartFile file,
                             @RequestParam("type") String type,
                             @RequestParam("hierarchy") String hierarchy) {
        try {
            // 上传并返回访问地址
            SysFileInfo fileInfo = sysFileInfoService.upload(file, type, hierarchy);
            SysFile sysFile = new SysFile();
            sysFile.setName(fileInfo.getFilePath());
            sysFile.setUrl(fileInfo.getDownloadUrl());
            sysFile.setFileIdentifier(fileInfo.getFileIdentifier());
            return R.ok(sysFile);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }
}