package com.tmerclub.cloud.user.listener;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.user.dto.ShopCustomerExcelDTO;
import com.tmerclub.cloud.user.manager.UserExcelManager;

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

/**
 * @author: zsm
 * @date: 2023/1/16 10:41
 */
public class ShopCustomerExcelListener extends AnalysisEventListener<ShopCustomerExcelDTO> {

    private UserExcelManager userExcelManager;
    private Map<String, List<String>> errorMap;
    private List<ShopCustomerExcelDTO> list;
    public static final String OTHER = "other";
    public static final String ERROR_ROWS = "error_rows";
    public static final String IMPORT_ROWS = "import_rows";

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

    public ShopCustomerExcelListener() {
    }

    public ShopCustomerExcelListener(UserExcelManager userExcelManager, Map<String, List<String>> errorMap) {
        this.userExcelManager = userExcelManager;
        errorMap.put(OTHER, new ArrayList<>(Constant.INITIAL_CAPACITY));
        errorMap.put(ERROR_ROWS, new ArrayList<>(Constant.INITIAL_CAPACITY));
        errorMap.put(IMPORT_ROWS, new ArrayList<>(Constant.INITIAL_CAPACITY));
        this.errorMap = errorMap;
        this.list = new ArrayList<>(Constant.INITIAL_CAPACITY);
    }

    /**
     * 这个每一条数据解析都会来调用
     */

    @Override
    public void invoke(ShopCustomerExcelDTO shopCustomerExcelDTO, AnalysisContext analysisContext) {
        boolean isSave = list.size() > BATCH_COUNT;
        if (isSave) {
            saveData();
        }

        list.add(shopCustomerExcelDTO);
    }

    /**
     * 所有数据解析完成了 都会来调用
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //确保所有数据都能入库
        saveData();
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        if (CollUtil.isEmpty(list)) {
            return;
        }
        userExcelManager.importShopCustomerExcel(list, errorMap);
        list.clear();
    }
}
