package com.qunzhixinxi.hnqz.admin.controller;

import cn.hutool.json.JSONUtil;
import com.qunzhixinxi.hnqz.admin.util.OsEnvUtils;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * {@code WmTemplateFileController} 模板文件控制层
 *
 * @author Hengchen.Sun
 * @version 1.0.0
 * @date 2021-04-16
 * @since ver.1.0.0
 */
@RestController
@AllArgsConstructor
@RequestMapping("/template-file")
@Api(value = "template-file", tags = "模板文件管理")
public class WmTemplateFileController {

	/**
	 * 根据模板文件名称下载模板
	 *
	 * @param paramStr 模板名称
	 * @param response response
	 * @throws IOException
	 */
	@PostMapping(value = "/download")
	@SneakyThrows
	public void templateFileDownload(@RequestBody String paramStr, HttpServletResponse response) {
		String fileName = JSONUtil.parseObj(paramStr).getStr("fileName");
		String locPath = (String) OsEnvUtils.getEachEnvPaths().get("EXCEL_FILE_PATH");
		File file = new File(locPath + fileName);
		byte[] bytesArray = new byte[(int) file.length()];
		FileInputStream fileInputStream = new FileInputStream(file);
		fileInputStream.read(bytesArray);

		response.reset();
		response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
		response.addHeader("Content-Length", "" + bytesArray.length);
		response.setContentType("application/octet-stream; charset=UTF-8");

		IOUtils.write(bytesArray, response.getOutputStream());
	}
}
