package com.rongwei.savecheck.controller;

import com.rongwei.sfcommon.sys.service.EasyExcelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author rongwei
 * @date 2019-08-06
 */
@RestController
@RequestMapping("/system/easyexcel")
public class EasyExcelController
{
	@Autowired
	private EasyExcelService easyExcelService;


	/**
	 * 下载
	 * type=1 无模板直接导出JqGrid中的数据
	 * type=2 有模板，直接从本系统模板库下载
	 *
	 * @param fileName
	 * @param response
	 * @throws IOException
	 */
	@PostMapping("/download/{type}/{fileName}")
	public void fileDownload(@PathVariable("type") Integer type, @PathVariable("fileName") String fileName, HttpServletResponse response) throws Exception
	{

        InputStream inputStream = easyExcelService.getFilePath(1, fileName+".doc");
		// 1.Content-disposition是 MIME 协议的扩展,它会激活文件下载对话框,它的文件名框自动填充了头中指定的文件名
		// 否则只会在浏览器中打开，而不会以附件的形式下载
        //设置输出文件类型为 word.doc
//		response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
		// 2.必须设置mimeType，否则下载的文件没有后缀,只会有个名字
		// 设置文件ContentType类型:multipart/form-data，这样设置，会自动判断下载文件类型,不推荐，有时会有问题。
		// 先固定为 excel的mime
//		String mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
//		response.setContentType(mimeType);
        response.setHeader("content-Type", "application/octet-stream;charset=ISO8859-1");
        response.setHeader("Content-Disposition", "attachment;filename="+fileName+".doc");
        response.addHeader("Pargam", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
		ServletOutputStream outputStream = response.getOutputStream();
		byte[] buffer = new byte[1024];
		int len;
		while ((len = inputStream.read(buffer)) != -1)
		{
			outputStream.write(buffer, 0, len);
		}
       // document.save(outputStream, );
		inputStream.close();
	}

}
