package com.tmerclub.cloud.product.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.product.service.StockBillLogItemService;
import com.tmerclub.cloud.product.vo.StockBillLogItemImportExcelVO;
import com.tmerclub.cloud.product.vo.StockBillLogItemImportVO;

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

/**
 * @author lanhai
 */
public class StockBillLogItemExcelListener extends AnalysisEventListener<StockBillLogItemImportExcelVO> {
    private StockBillLogItemService stockBillLogItemService;
    /**
     * 错误信息集合
     */
    private List<String> errorList;
    private List<StockBillLogItemImportExcelVO> list;
    private Integer type;
    private StockBillLogItemImportVO stockBillLogItemImportVO;

    /**
     * 每隔1000条数据存储数据库，然后清理map ，方便内存回收
     */
    private static final int BATCH_COUNT = 3000;

    public StockBillLogItemExcelListener() {
    }

    public StockBillLogItemExcelListener(StockBillLogItemService stockBillLogItemService, List<String> errorList, Integer type, StockBillLogItemImportVO stockBillLogItemImportVO) {
        this.stockBillLogItemService = stockBillLogItemService;
        this.errorList = new ArrayList<>(Constant.INITIAL_CAPACITY);
        this.list = new ArrayList<>(Constant.INITIAL_CAPACITY);
        this.type = type;
        this.stockBillLogItemImportVO = stockBillLogItemImportVO;
    }

    /**
     * 这个每一条数据解析都会来调用
     */
    @Override
    public void invoke(StockBillLogItemImportExcelVO stockBillLogItemImportExcelVO, AnalysisContext analysisContext) {
        if (Objects.isNull(stockBillLogItemImportExcelVO)) {
            return;
        }
        boolean isSave = list.size() > BATCH_COUNT;
        if (isSave) {
            saveData();
        }
        list.add(stockBillLogItemImportExcelVO);
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        stockBillLogItemService.importExcel(list, errorList, type, stockBillLogItemImportVO);
        list.clear();
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //确保所有数据都能入库
        saveData();
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) {

        int row, column;
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException convertException = (ExcelDataConvertException) exception;
            row = convertException.getRowIndex() + 1;
            column = convertException.getColumnIndex() + 1;
            errorList.add("  第" + row + "行，第 " + column + "列数据不符合要求，请检验后重新导入!");
        }
    }
}
