package com.ff.weijinxiao.controller;

import com.ff.weijinxiao.util.FileUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("api/file")
public class FileController {



    @PostMapping("/uploadfile")
    @ApiOperation(value = "上传图片", notes = "上传文件，格式jpg/gif/png，不大于2M")
    public Map<String, Object> uploadFile(MultipartFile file) {

        Map<String, Object> result = new HashMap<>();

        String oFileName = file.getOriginalFilename();
        String fileSuffix = oFileName.substring(oFileName.lastIndexOf("."));

        if (!fileSuffix.equalsIgnoreCase(".jpg") &&
                !fileSuffix.equalsIgnoreCase(".jpeg") &&
                !fileSuffix.equalsIgnoreCase(".bmp") &&
                !fileSuffix.equalsIgnoreCase(".png")) {
            result.put("code", 10001);
            result.put("message", "只能上传jpg/jpeg/bmp/png类型的图片");
            return result;
        }

        if (file.getSize() > 1024 * 1000 * 2) {
            result.put("code", 10002);
            result.put("message", "图片不得大于2M");
            return result;
        }

        String tempFileName = FileUtil.gerenalFileName() + fileSuffix;

        File f = new File("/home/uploadfile/" + tempFileName);
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), f);
        } catch (IOException e) {
            e.printStackTrace();
        }

        result.put("code", 10000);
        result.put("imageUrl", "/home/uploadfile/" + tempFileName);
        return result;
    }


    @GetMapping("/getimg")
    @ApiOperation(value = "获取图片", notes = "获取图片")
    public Object getLoanImg(@ApiParam(required = true, value = "fileUrl") @RequestParam String fileUrl,
                             HttpServletRequest request, HttpServletResponse response) throws IOException {

        if (null != fileUrl && fileUrl.length() > 0) {
            response.setContentType("image/png");
            OutputStream output = response.getOutputStream();
            byte[] bytes = FileUtil.readByteFromFilePath(fileUrl);
            if (null == bytes) {
                output.close();
                return null;
            }
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            int len;
            byte[] buf = new byte[1024];
            while ((len = in.read(buf)) != -1) {
                output.write(buf, 0, len);
            }
            output.flush();
            output.close();
        }
        return null;
    }

}
