package com.foreverwin.mesnac.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.foreverwin.modular.core.util.I18nUtil;
import com.foreverwin.modular.core.util.R;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;

import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.List;

public class ExportR<T> extends R<T> {
    public static Long MAX_EXPORT_SIZE = 20000L;

    public static <T> R export(T data, String fileName, LinkedHashMap<String, String> headers, HttpServletResponse response) {
        ExportR apiResult = new ExportR();
        apiResult.setCode(0);
        apiResult.setData(data);
        //-----------------------------------------------------------------------------------------------------------
        if (data == null || !(data instanceof List) || headers == null || headers.size() == 0) return apiResult;
        if (((List)data).size() > MAX_EXPORT_SIZE) {
            return R.failed(I18nUtil.getI18nText("common.export.maxRows.error", new Object[]{MAX_EXPORT_SIZE, ((List)data).size()}));
        }//if
        //-----------------------------------------------------------------------------------------------------------
        try {
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet();
            sheet.setDefaultColumnWidth(15);
            HSSFRow row = sheet.createRow(0);
            //--------------------------------------------------------------------------------------------------------------------------
            HSSFCellStyle headerStyle = getHeaderStyle(workbook);// 获取列头样式对象
            Object[] columns = headers.keySet().toArray();
            for (int i = 0; i < columns.length; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                HSSFRichTextString text = new HSSFRichTextString(headers.get(columns[i]));
                cell.setCellValue(text);
                cell.setCellStyle(headerStyle); // 设置列头单元格样式
            }//for
            //--------------------------------------------------------------------------------------------------------------------------
            List dataList = (List)data;
            HSSFCellStyle rowStyle = getRowStyle(workbook);// 获取列头样式对象
            for (int rowNum = 0; rowNum < dataList.size(); rowNum++) {
                JSONObject item = JSON.parseObject(JSON.toJSONString(dataList.get(rowNum)));
                HSSFRow child = sheet.createRow(rowNum+1);
                for (int i = 0; i < columns.length; i++) {
                    HSSFCell cell = child.createCell(i);
                    cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                    HSSFRichTextString text = new HSSFRichTextString(item.getString(columns[i].toString()));
                    cell.setCellValue(text);
                    cell.setCellStyle(rowStyle);
                }
            }//for
            //--------------------------------------------------------------------------------------------------------------------------
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            return R.failed(e);
        }//try
        //-----------------------------------------------------------------------------------------------------------
        return apiResult;
    }

    /*
     * 列头单元格样式
     */
    public static HSSFCellStyle getHeaderStyle(HSSFWorkbook workbook) {
        // 设置字体
        HSSFFont font = workbook.createFont();
        // 设置字体大小
        font.setFontHeightInPoints((short) 11);
        // 字体加粗
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 设置字体名字
        font.setFontName("Courier New");
        // 设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        style.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
        style.setFillPattern((short)1);
        // 设置底边框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        // 设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        // 设置左边框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        // 设置右边框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 设置右边框颜色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        // 设置顶边框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        // 在样式用应用设置的字体;
        style.setFont(font);
        // 设置自动换行;
        style.setWrapText(false);
        // 设置水平对齐的样式为居中对齐;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        //-----------------------------------------------------------------------------------------------------------
        return style;
    }

    public static HSSFCellStyle getRowStyle(HSSFWorkbook workbook) {
        // 设置字体
        HSSFFont font = workbook.createFont();
        // 设置字体大小
        // font.setFontHeightInPoints((short)10);
        // 字体加粗
        // font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 设置字体名字
        font.setFontName("Courier New");
        // 设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置底边框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        // 设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        // 设置左边框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        // 设置右边框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 设置右边框颜色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        // 设置顶边框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        // 在样式用应用设置的字体;
        style.setFont(font);
        // 设置自动换行;
        style.setWrapText(false);
        // 设置水平对齐的样式为居中对齐;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        //-----------------------------------------------------------------------------------------------------------
        return style;
    }
}
