package com.yuchen.saas.torch.api.util;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * @Author 任业政
 * @Date 2021/9/10 19:54
 * @Description
 */
public class ExcelUtil {

    /**
     * 指定格式创建 Workbook
     * @param headList
     * @param columnList
     * @param datas
     * @return
     */
    public static Workbook getExcel(List<String> headList, List<String> columnList, List<Map<String, Object>> datas) {

        HSSFWorkbook wb;
        int rowsIndex = -1;

        wb = new HSSFWorkbook();
        CellStyle centerStyle = wb.createCellStyle();
        centerStyle.setAlignment(HorizontalAlignment.CENTER);
        centerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        CellStyle autoLineStyle = wb.createCellStyle();
        autoLineStyle.setWrapText(true);
        autoLineStyle.setAlignment(HorizontalAlignment.CENTER);
        autoLineStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        wb.createSheet("Sheet1");
        HSSFSheet sheet1 = wb.getSheet("Sheet1");
        HSSFRow row = null;
        HSSFCell cell = null;

        int headSize = (headList == null) ? 0 : headList.size();

        if (headSize > 0) {
            row = sheet1.createRow(0);
            rowsIndex++;
        }

        for (int i = 0; i < headSize; i++) {
            cell = row.createCell(i);
            String head = headList.get(i);
            cell.setCellValue(head);
            if (head.length() > 4) {
                sheet1.setColumnWidth(i, 5000);
            }

            if (head.length() > 7) {
                sheet1.setColumnWidth(i, 6000);
            }

            if (head.length() > 10) {
                sheet1.setColumnWidth(i, 8000);
            }
            cell.setCellStyle(centerStyle);
        }

        int size = (datas == null) ? 0 : datas.size();
        int columnSize = (columnList == null) ? 0 : columnList.size();
        for (int i = 0; i < size; i++) {
            Map<String, Object> tmpData = datas.get(i);
            rowsIndex++;
            row = sheet1.createRow(rowsIndex);
            for (int j = 0; j < columnSize; j++) {
                String columnKey = columnList.get(j);
                Object value = tmpData.get(columnKey);
                String valueStr = String.valueOf(value);
                cell = row.createCell(j);
                cell.setCellValue(valueStr);
                cell.setCellStyle(centerStyle);
            }

        }
        return wb;
    }


    /**
     * 创建标题样式和Sheet对象
     * @param titleName 标题名称
     * @return
     */
    public static XSSFWorkbook getXSSFWorkbook(String titleName){
        XSSFWorkbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet();
        sheet.setDefaultColumnWidth(13);
        Row title = sheet.createRow(0);
        Cell name = title.createCell(0);
        // 合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
        // 设置单元格内容
        name.setCellValue(titleName);
        name.setCellStyle(titleStyle(workbook));
        return workbook;
    }


    /**
     * 标题样式
     * @param workbook
     * @return
     */
    public static XSSFCellStyle titleStyle(XSSFWorkbook workbook){
        XSSFCellStyle titleStyle = workbook.createCellStyle();
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Font ztFont = workbook.createFont();
        ztFont.setItalic(false);
        ztFont.setColor(Font.COLOR_NORMAL);
        ztFont.setFontHeightInPoints((short)12);
        ztFont.setFontName("宋体");
        ztFont.setBold(true);
        titleStyle.setFont(ztFont);
        return titleStyle;
    }


    /**
     * 返回excel 文件
     *
     * @param workbook
     * @param response
     */
    public static void getExcelResponse(Workbook workbook, HttpServletResponse response, String fileName) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            workbook.write(baos);
            ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
            int len;
            byte[] buffer = new byte[1024];
            response.setHeader("content-disposition", "attachment;filename=" +
                    URLEncoder.encode(fileName, StandardCharsets.UTF_8));
            OutputStream out = response.getOutputStream();
            while ((len = swapStream.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            swapStream.close();
        } catch (IOException ioException) {
        }
    }

    public static OutputStream getEasyExcelOutputStream(String fileName, HttpServletResponse response) throws Exception {

        try {
            fileName = URLEncoder.encode(fileName, "utf-8").replaceAll("\\+", "%20");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName);
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "no-store");
            response.addHeader("Cache-Control", "max-age=0");
            return response.getOutputStream();
        } catch (IOException e) {
            throw new Exception("导出excel表格失败!", e);
        }
    }
}
