package com.njcn.system.controller;


import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.web.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;


/**
 * Description:
 * Date: 2023/8/30  11:08【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */

@Slf4j
@Api(tags = "图片处理")
@RestController
@AllArgsConstructor
@RequestMapping("/image")
public class ImageToStreamController extends BaseController {
    private final FileStorageUtil fileStorageUtil;
    /**
     * 数据规模
     */
    @GetMapping("/toStream")
    @ApiImplicitParam(name = "bgImage", value = "图片路径", required = true)
    public void toStream(@RequestParam("bgImage") String bgImage,HttpServletResponse response) {

        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            //获取部分参数，用于从minIO上将文件下载到tmp（此步骤不是必须）
            InputStream fileStream = fileStorageUtil.getFileStream(bgImage);
            //获取文件格式
            String format = bgImage.substring(bgImage.lastIndexOf('.') + 1);
            response.setContentType("application/octet-stream");
            response.setHeader("content-type", "image/"+getFileFormat(format));
            response.setHeader("Content-Disposition", "inline;fileName=download" +System.currentTimeMillis() + "");// 设置文件名
            //返回流处理
            bis = new BufferedInputStream(fileStream);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        }catch (Exception e) {

        }finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException ignored) {
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ignored) {
                }
            }
        }
    }

    private String getFileFormat(String format){
        switch (format) {
            case "png":
                return "png";
            case "svg":
                return "svg+xml";
            case "jpg":
                return "jpeg";
            case "gif":
                return "gif";

            default:
                break;
        }
        return format;
    }
}
