package com.yonge.cooleshow.biz.dal.execl.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.enums.RowTypeEnum;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.CellExtra;
import com.google.common.collect.Lists;
import com.yonge.cooleshow.biz.dal.execl.entity.TenantAccountRecordImport;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Optional;

/**
 * 课件信息读取监听器
 * Created by Eric.Shang on 2020/7/1.
 */
@Slf4j
@Getter
public class TenantAccountRecordImportListener extends AnalysisEventListener<TenantAccountRecordImport> {

    // 课件信息
    private final List<TenantAccountRecordImport> importList;
    // sheet名称
    private final String sheetName;
    // 合并标识
    private Boolean mergeFlag;

    public TenantAccountRecordImportListener(List<TenantAccountRecordImport> examinations, String sheetName) {
        // 单元测试数据
        this.importList = Optional.ofNullable(examinations).orElse(Lists.newArrayList());
        // sheet名称
        this.sheetName = sheetName;
    }

    /**
     * 读取每行数据触发
     * @param  examination 数据内容
     * @param analysisContext AnalysisContext
     */
    @Override
    public void invoke(TenantAccountRecordImport examination, AnalysisContext analysisContext) {
        // 忽略空行读取
        //analysisContext.readWorkbookHolder().setIgnoreEmptyRow(false);
        // 读取数据
        getImportList().add(examination.rowIndex(getImportList().size() + 2).sheetName(getSheetName()));
    }

    /**
     * 空行数据判定
     * @param context AnalysisContext
     * @return boolean
     */
    @Override
    public boolean hasNext(AnalysisContext context) {
        // 忽略空行判定
        if (RowTypeEnum.EMPTY.equals(context.readRowHolder().getRowType())){
            doAfterAllAnalysed(context);
            return false;
        }

        return super.hasNext(context);
    }

    /**
     * 数据解板读完触发
     * @param analysisContext AnalysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
    }

    /**
     * 额外信息（批注、超链接、合并单元格信息读取）
     * @param extra CellExtra
     * @param context AnalysisContext
     */
    @Override
    public void extra(CellExtra extra, AnalysisContext context) {
        switch (extra.getType()) {
            case MERGE:
                mergeFlag = false;
                break;
            case COMMENT:
            case HYPERLINK:
            default:
                break;
        }
    }
}
