package com.sptg.gateway.util;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.google.common.collect.Lists;
import com.sptg.gateway.service.ExcelService;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author WFT
 * @date 2020/5/29
 * description:
 */
public class ExcelUtils {

    /**
     * 导出表格
     * @param response javax.servlet.http.HttpServletResponse
     * @param list java.util.List
     * @param service com.sptg.gateway.service.ExcelService
     */
    public static void writeExcel(
            HttpServletResponse response,
            List<? extends BaseRowModel> list,
            ExcelService service){
        //  获取流对象
        OutputStream outputStream = ExcelUtils.getOutputStream(service.getExcelTemplateName(),response);
        try {
            ExcelWriter writer = new ExcelWriter(outputStream, ExcelTypeEnum.XLSX);
            //  写出数据
            if (list.size() >= 50000) {
                List<? extends List<? extends BaseRowModel>> dataList = Lists.partition(list, 50000);
                for (int i = 0; i < dataList.size(); i++) {
                    Sheet sheet = new Sheet((i + 1), 0, service.getExcelTemplate().getClass());
                    sheet.setSheetName(null);
                    writer.write(dataList.get(i), sheet);
                }
            } else {
                Sheet sheet = new Sheet(1, 0, service.getExcelTemplate().getClass());
                sheet.setSheetName(null);
                writer.write(list, sheet);
            }
            writer.finish();
        } finally {
            if (null != outputStream){
                try {
                    outputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

    private static OutputStream getOutputStream(String fileName,HttpServletResponse response){
        //创建本地文件
        fileName = fileName + ".xlsx";
        File dbfFile = new File(fileName);
        OutputStream outputStream = null;
        try {
            if (!dbfFile.exists() || dbfFile.isDirectory()) {
                dbfFile.createNewFile();
            }
            fileName = new String(fileName.getBytes(), StandardCharsets.ISO_8859_1);
            response.addHeader("Content-Disposition", "filename=" + fileName);
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(dbfFile.exists()){
                dbfFile.delete();
            }
        }
        return outputStream;
    }
}
