package com.malk.utils;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.malk.base.BaseDto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.function.Consumer;

/**
 * easy excel 导入
 */
@Slf4j
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
@Component
public class UtilImport extends AnalysisEventListener<BaseDto> {

    @FunctionalInterface
    public interface ExecuteLambda {
        void row(BaseDto dto);
    }

    /**
     * 表头信息读取
     */
    private Consumer headerLambda;

    /**
     * 执行每行调用
     */
    private ExecuteLambda executeLambda;

    /**
     * 导入结束回调
     */
    private Consumer completeLambda;

    @Override
    public void invoke(BaseDto balanceDTO, AnalysisContext analysisContext) {
        // 2. 执行每行调用
        log.info("执行每行调用: {}", balanceDTO);
        if (ObjectUtil.isNotNull(executeLambda)) {
            executeLambda.row(balanceDTO);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 3. 导入结束回调
        log.info("#### 导入结束回调 ####");
        if (ObjectUtil.isNotNull(completeLambda)) {
            headerLambda.accept(analysisContext);
        }
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        // 1. 表头信息读取
        log.info("表头信息读取: {}", headMap);
        if (ObjectUtil.isNotNull(headerLambda)) {
            headerLambda.accept(headMap);
        }
    }
}
