package com.neusoft.smart.pos.gateway.controller;

import com.neusoft.smart.pos.framework.dto.ResponseData;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
public class FileController {
	
	@Value("${smart.pos.constant.upload.path}")
	String uploadPath;
	
	@PostMapping("/file/{folder}")
	@ApiOperation(value = "文件上传接口", notes = "文件上传接口")
	public ResponseData<?> upload(final MultipartFile file, @PathVariable String folder, String key) throws IOException {
		String fileName = file.getOriginalFilename();
		if(null!=key && key.contains("/")){
			fileName = key.split("/")[1];
		}
		File folderFile = new File(uploadPath + File.separator + folder );
		if (!folderFile.exists()) {
			throw new BusinessCommonException("500", "上传目标文件夹不存在");
		}
		file.transferTo(new File(uploadPath + File.separator + folder + File.separator + fileName));
		return new ResponseData<>();
	}
	
	@GetMapping("/file/{folder}/{fileName:.+}")
	@ApiOperation(value = "文件下载接口", notes = "文件下载接口")
	public void upload(@PathVariable String folder, @PathVariable String fileName, HttpServletResponse response) throws IOException {
		File file = new File(uploadPath + File.separator + folder + File.separator + fileName);
		if (!file.exists()) {
			throw new BusinessCommonException("500", "下载文件不存在");
		}
		IOUtils.copy(new FileInputStream(file), response.getOutputStream());
	}
	
}
