package cn.com.qmth.examcloud.core.questions.base.excel;

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

/**
 * Created by zhengmin on 2016/8/17.
 */
@SuppressWarnings("rawtypes")
public abstract class ExcelUtils {

    private Class dataClass;
    private List<ColumnSetting> columnSettings;

    public ExcelUtils(Class<?> dataClass, boolean isRead) {
        this.dataClass = dataClass;
        this.columnSettings = getColumnSettings(dataClass, isRead);
    }

    public Class getDataClass() {
        return dataClass;
    }

    public void setDataClass(Class dataClass) {
        this.dataClass = dataClass;
    }

    public List<ColumnSetting> getColumnSettings() {
        return columnSettings;
    }

    public void setColumnSettings(List<ColumnSetting> columnSettings) {
        this.columnSettings = columnSettings;
    }

    /**
     * 提取ExcelProperty注解类的字段信息
     *
     * @param dataClass 需要解析excel的数据类型
     * @return
     */
    protected List<ColumnSetting> getColumnSettings(Class<?> dataClass, boolean isRead) {
        List<ColumnSetting> columnSettings = new ArrayList<>();
        Field[] fileds = dataClass.getDeclaredFields();
        for (Field field : fileds) {
            ExcelProperty exportProperty = field.getAnnotation(ExcelProperty.class);
            if (exportProperty != null) {
                if (isRead) {
                    if (exportProperty.type() == 0 || exportProperty.type() == 2) {
                        ColumnSetting columnSetting = new ColumnSetting(
                                exportProperty.name(), field.getName(), exportProperty.width(),
                                exportProperty.index());
                        columnSettings.add(columnSetting);
                    }
                } else {
                    if (exportProperty.type() == 1 || exportProperty.type() == 2) {
                        ColumnSetting columnSetting = new ColumnSetting(
                                exportProperty.name(), field.getName(), exportProperty.width(),
                                exportProperty.index());
                        columnSettings.add(columnSetting);
                    }
                }
            }
        }
        Collections.sort(columnSettings);
        return columnSettings;
    }

}
