package cn.com.qmth.examcloud.tool.utils;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ExcelHelper {

    public static List<List<String>> buildHeaders(List<String> headers) {
        return buildHeaders(null, headers);
    }

    public static List<List<String>> buildHeaders(String title, List<String> headers) {
        List<List<String>> fullHeaders = new ArrayList<>();
        for (String header : headers) {
            if (StringUtils.isNotEmpty(title)) {
                // 主标题
                fullHeaders.add(Arrays.asList(title, header));
                continue;
            }
            fullHeaders.add(Arrays.asList(header));
        }
        return fullHeaders;
    }

    public static SheetWriteHandler sheetStrategy() {
        return new SheetWriteHandler() {
            @Override
            public void afterSheetCreate(WriteWorkbookHolder workbookHolder, WriteSheetHolder sheetHolder) {
                Sheet sheet = sheetHolder.getSheet();
                sheet.createFreezePane(0, 1);// 固定首行
                sheet.setDefaultColumnWidth(15);
            }
        };
    }

    public static HorizontalCellStyleStrategy styleStrategy() {
        WriteCellStyle headStyle = new WriteCellStyle();
        headStyle.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());
        headStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        headStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        headStyle.setBorderLeft(BorderStyle.THIN);
        headStyle.setBorderRight(BorderStyle.THIN);
        headStyle.setBorderBottom(BorderStyle.THIN);
        headStyle.setBorderTop(BorderStyle.THIN);
        headStyle.setWrapped(false);// 是否换行
        WriteFont headFont = new WriteFont();
        headFont.setFontHeightInPoints((short) 9);
        headFont.setFontName("宋体");
        headStyle.setWriteFont(headFont);

        WriteCellStyle contentStyle = new WriteCellStyle();
        WriteFont contentFont = new WriteFont();
        contentFont.setFontHeightInPoints((short) 9);
        contentFont.setFontName("宋体");
        contentStyle.setWriteFont(contentFont);

        return new HorizontalCellStyleStrategy(headStyle, contentStyle);
    }

}
