package org.springblade.ship;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.io.FilenameUtils;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.boot.props.BladeFileProperties;
import org.springblade.core.tool.api.R;
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.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@AllArgsConstructor
@RequestMapping("file")
@Api(value = "", tags = "接口")
public class FileController  extends BladeController {

	private final BladeFileProperties bladeFileProperties;

	/**
	 * 详情
	 */
	@GetMapping("/download/{filePath}")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入device")
	public R download(@PathVariable("filePath") String filePath, HttpServletRequest request, HttpServletResponse response){
		/*String fileUrl = bladeFileProperties.getRemotePath() + filePath;
		File dest = new File(fileUrl);*/
//		String filePath = "";
		String fileUrl = bladeFileProperties.getRemotePath() + "\\" + filePath;
		File file = new File(fileUrl);
		String fileName = file.getName();
		fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();

		try{
			BufferedInputStream fis = new BufferedInputStream(new FileInputStream(fileUrl));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			response.reset();
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes()));

			response.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();

		}catch (Exception e){
			e.printStackTrace();
		}

		return R.data(file);
	}

	/**
	 * 上传文件
	 *
	 * @param file 文件
	 * @return ObjectStat
	 */
	@SneakyThrows
	@PostMapping("/upload")
	public R putFile(HttpServletRequest request, @RequestParam MultipartFile file) {
		//获取文件名
		String name = file.getOriginalFilename();
		//获取文件后缀名,如果需要重新命名就需用拼接，原样保存直接用name
		String ext = FilenameUtils.getExtension(file.getOriginalFilename());
		String filename = System.currentTimeMillis() + "." + ext;
		//设置文件上传路径

		//以绝对路径保存文件
		String remotePath = bladeFileProperties.getRemotePath();
//		String url = request.getSession().getServletContext().getRealPath("/file");
		File dest = new File(remotePath);
		// 检测是否存在目录，没有就创建
		if (!dest.exists()) {
			dest.mkdirs();
		}

		String upStr = remotePath + "/" + filename;
		file.transferTo(new File(upStr));
		//把保存的url存放到对应的实体类的字段中
		//entity.setUrl("file/"+name )
		//页面调用下载或者展示的时候就拼上127.0.0.1:8080/项目名/实体类的url
		//一般直接是ctx/实体类的url

		Map<String, Object> map = new HashMap<>();
		map.put("name", filename);
		map.put("link", bladeFileProperties.getUploadDomain() + filename);

		return R.data(map);

	}

}
