package com.eitc.patient.controller;

import com.eitc.common.config.EitcConfig;
import com.eitc.common.core.domain.AjaxResult;
import com.eitc.common.utils.MinioUtils;
import com.eitc.common.utils.file.FileUploadUtils;
import com.eitc.common.utils.file.FileUtils;
import com.eitc.framework.config.ServerConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
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 javax.annotation.Resource;

import static com.eitc.common.core.domain.AjaxResult.success;










/**
 * 通用请求处理
 *
 * @author eitc
 */
@RestController
@RequestMapping("/app/common")
@Api(tags = "APP通用接口")
public class AppCommonController {

    @Resource
    private ServerConfig serverConfig;
    @Autowired
    private MinioUtils minioUtils;

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    @ApiOperation("上传文件")
    public AjaxResult uploadFile(MultipartFile file) {
        try {
            // 上传文件路径
            String filePath = EitcConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * minio文件上传上传
     * @param file 文件
     * @param path 按照需求区分文件路径
     * @return
     * @throws Exception
     */
    @PostMapping("/minioUploadImage")
    public AjaxResult minioUploadImage(MultipartFile file, String path) throws Exception
    {
        try
        {
            return success(minioUtils.uploadFile("eitc", path, file, file.getOriginalFilename(), "application/octet-stream"));
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
}
