package com.ylcm.sys.common;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.ylcm.sys.excel.export.WriteExcelDataDelegated;

import jxl.Workbook;

public class ExcelUtil {

    /**
     * 每个sheet存储的记录数 100W
     */
    public static final Integer PER_SHEET_ROW_COUNT = 1000000;

    /**
     * 每次向EXCEL写入的记录数(查询每页数据大小)
     */
    public static final Integer PER_WRITE_ROW_COUNT = 2000;

    /**
     * 每个sheet的写入次数 5
     */
    public static final Integer PER_SHEET_WRITE_COUNT = PER_SHEET_ROW_COUNT / PER_WRITE_ROW_COUNT;


    /**
     * 导出Excel到浏览器
     *
     * @param response
     * @param fileName                文件名称
     * @param model                   模型类
     * @param writeExcelDataDelegated 向EXCEL写数据/处理格式的委托类 自行实现
     * @throws Exception
     */
    public static void exportExcelToWebsite(HttpServletResponse response,String fileName, Object model, WriteExcelDataDelegated writeExcelDataDelegated) {

        ServletOutputStream outputStream = null;
        try {

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String name = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + name + ".xlsx");

            outputStream = response.getOutputStream();
            ExcelWriter writer = EasyExcel.write(outputStream, model.getClass())
                    .excelType( ExcelTypeEnum.XLSX)
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .build();

            int i = 0;
            List<?> data;
            int dataSize = PER_WRITE_ROW_COUNT;
            while (PER_WRITE_ROW_COUNT == dataSize) {
                WriteSheet sheet = EasyExcel.writerSheet(i++, "数据" + i).build();
                for (int j = 1; j <= PER_SHEET_WRITE_COUNT; j++) {
                    data = writeExcelDataDelegated.getExcelData(j, PER_WRITE_ROW_COUNT);

                    if (CollectionUtils.isEmpty(data)) {
                        dataSize = 0;
                        writer.write(data, sheet);
                        break;
                    }
                    dataSize = data.size();
                    writer.write(data, sheet);
                }
            }

            writer.finish();
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    
    
	/**
	 * 导出excel
	 * 
	 * @date 2018年1月3日
	 * @author zjm
	 */
	public static void exportExcel(HttpServletResponse response, String fileName, ByteArrayOutputStream os)
			throws UnsupportedEncodingException, IOException {
		byte[] content = os.toByteArray();
		InputStream is = new ByteArrayInputStream(content);
		response.reset();
		response.setContentType("application/vnd.ms-exce" + "l;charset=utf-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1"));
		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;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (final IOException e) {
			throw e;
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
	}
	
	
}
