package com.winsun.utils;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class ExportExcel {

	private static final Logger logger = LoggerFactory.getLogger(ExportExcel.class);
    /**
     * 返回输出流
     * @param workBook
     * @param request
     * @param response
     * @param FileName
     * @throws Exception
     */
    public static ResponseEntity<byte[]> toDownLoad(XSSFWorkbook workBook, HttpServletRequest request, HttpServletResponse response, String FileName) throws Exception{
    	ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
        workBook.write(os);
        } catch (IOException e) {
        	logger.error(e.getMessage(), e);
//            e.printStackTrace();
        }
        String realFileName = FileName + ".xlsx";

        // 浏览器兼容
        String agent = request.getHeader("User-Agent");
        if (null != agent) {
            agent = agent.toLowerCase();
            if (agent.indexOf("firefox") != -1) {
                realFileName = new String(URLDecoder.decode(realFileName, "UTF-8").getBytes(), "iso-8859-1");
            } else {
                realFileName = java.net.URLEncoder.encode(realFileName, "UTF-8");
            }
        }

        byte[] content = os.toByteArray();
        // 设置返回文件大小
        response.addHeader("content-length",os.size() + "");

        InputStream is = new ByteArrayInputStream(content);

        // 设置response参数，可以打开下载页面
//        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + realFileName);
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }

            HttpHeaders headers = new HttpHeaders();
            // 设置返回文件参数
            headers.add("Content-Type","application/vnd.ms-excel;charset=utf-8");
            headers.add("Connection", "close");
            headers.add("Content-Disposition",
                    "attachment;filename="+realFileName);

            return new ResponseEntity<byte[]>(buff, headers, HttpStatus.OK);

        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null){
            	try {
           		 	bis.close();
				} catch (IOException e2) {
					logger.error(e2.getMessage(),e2);
//					e2.printStackTrace();
				}
            }

            if (bos != null){
            	try {
            		bos.close();
   				} catch (IOException e2) {
   					logger.error(e2.getMessage(), e2);
//   					e2.printStackTrace();
   				}
            }

        }
    }

}
