package com.casic.missiles.modular.system.controller;

import com.casic.missiles.model.response.ResponseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Controller
public class ImageUploadController {

    private static final Logger logger = LoggerFactory.getLogger(ImageUploadController.class);

    @Value("${smartcity.config.image-path}")
    private String imagePath;

    /**
     * 图片上传接口，将上传图片路径返回
     */
    @RequestMapping("/imageUpload")
    @ResponseBody
    public Object imageUpload(@RequestParam("file") MultipartFile file) throws IOException {

        if(!file.isEmpty()){
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            String contentType=file.getContentType();
            String imageName = uuid + "." + contentType.substring(contentType.indexOf("/")+1);//图片格式后缀

            String fileName = new SimpleDateFormat("yyyy-MM").format(new Date());
            File dir = new File(imagePath + fileName);
            if (!dir.exists()){//若此目录不存在，则创建之
                dir.mkdirs();
                System.out.println("创建文件夹路径为："+ dir.getPath());
            }

            String pathName = dir.getPath()+ File.separator + imageName;
            file.transferTo(new File(pathName));

            return ResponseData.success(fileName + File.separator + imageName);
        }

        return ResponseData.error("文件为空");
    }

    @RequestMapping(value = "/imageGet/{filename}/{imagename:.+}",method=RequestMethod.GET,produces = "image/*")
    @ResponseBody
    public byte[] imageGet(@PathVariable String filename,@PathVariable String imagename) throws IOException {

        File file = new File(imagePath + File.separator + filename + File.separator + imagename);
        FileInputStream inputStream = new FileInputStream(file);
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes, 0, inputStream.available());
        return bytes;
    }
}
