package com.jwipc.util;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.handler.context.SheetWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.Sheet;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * <p> </p>
 *
 * @author ZhangJie
 * @version 1.0
 * @since JDK 1.8
 */
public class HideColumnAnnotationHandler implements SheetWriteHandler {
    private final List<Integer> hiddenColumns;

    public HideColumnAnnotationHandler(Class<?> clazz) {
        this.hiddenColumns = getHiddenColumns(clazz);
    }

    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        // No-op
    }

    @Override
    public void afterSheetCreate(SheetWriteHandlerContext context) {
        final Sheet sheet = context.getWriteSheetHolder().getSheet();
        for (int columnIndex : hiddenColumns) {
            sheet.setColumnHidden(columnIndex, true);
        }
    }

    private List<Integer> getHiddenColumns(Class<?> clazz) {
        List<Integer> hiddenColumns = new ArrayList<>();
        Field[] fields = clazz.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            if (fields[i].isAnnotationPresent(ExcelColumnHidden.class)) {
                hiddenColumns.add(i);
            }
        }
        return hiddenColumns;
    }
}
