package cn.reghao.tnb.sb.util.excel;

import cn.reghao.jutil.jdk.web.db.BaseMapper;
import cn.reghao.tnb.sb.util.ClassUtil;
import lombok.extern.slf4j.Slf4j;

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

/**
 * @author reghao
 * @date 2023-03-01 21:09:20
 */
@Slf4j
public class ExcelProcessor<T> {
    protected final List<T> list = new ArrayList<>();
    protected BaseMapper<T> baseMapper;
    private int total = 0;
    private Class<?> clazz;

    public ExcelProcessor(BaseMapper<T> baseMapper) {
        this.baseMapper = baseMapper;
    }

    public void readExcel(Class<?> clazz, String filePath) throws Exception {
        this.clazz = clazz;
        if (filePath.endsWith(".xls")) {
            // excel2003
            XlsReader excelXls = new XlsReader(this);
            excelXls.process(filePath);
        } else if (filePath.endsWith(".xlsx")) {
            // excel2007
            XlsxReader xlsxReader = new XlsxReader(this);
            xlsxReader.process(filePath);
        } else {
            log.error("文件格式错误，{} 的扩展名不是 xls 或 xlsx", filePath);
        }
    }

    public void sendRows(List<String> list) {
        try {
            String[] fields = list.toArray(new String[0]);
            Object object = ClassUtil.getObject(clazz, fields);
            if (object != null) {
                T t = (T) object;
                processObject(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void processObject(T t) {
        list.add(t);
        if (list.size() > 1000) {
            baseMapper.saveAll(list);
            total += list.size();
            list.clear();

            if (total % 100_000 == 0) {
                log.info("已持久化 {} 条数据", total);
            }
        }
    }
}
