package com.yida.data.attendance.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.yida.data.attendance.dto.BssidImportDTO;
import com.yida.data.attendance.service.AttendanceRuleWifiService;
import com.yida.data.common.core.entity.CurrentUser;
import com.yida.data.common.core.entity.attendance.attendance.AttendanceRule;
import com.yida.data.school.dto.smart.GuideRosterErrorExportDTO;
import com.yida.data.school.dto.smart.GuideRosterImportDTO;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ehcache.impl.internal.concurrent.ConcurrentHashMap;


@Slf4j
@RequiredArgsConstructor
public class BssidExcelListener extends AnalysisEventListener<BssidImportDTO> {

    private final AttendanceRuleWifiService attendanceRuleWifiService;

    /**
     * 当前导入数据唯一标识
     */
    private final Long ruleId;

    /**
     * 每次存储条数 每隔5条存储数据库, 实际使用中可以3000条, 然后清理list, 方便内存回收
     */
    private static final int BATCH_COUNT = 3000;

    /**
     * 需要保存的数据集合
     */
    ConcurrentHashMap<Integer, BssidImportDTO> concurrentHashMap = new ConcurrentHashMap<>();

    /**
     * excel总数量
     */
    private static Integer totalCount = 0;

    /**
     * 处理次数
     */
    private static Integer handleNumber = 0;

    /**
     * 解析成功一条数据调用一次
     */
    @Override
    public void invoke(BssidImportDTO dto, AnalysisContext analysisContext) {
        totalCount = analysisContext.readSheetHolder().getApproximateTotalRowNumber() - 1;
        // 获取读取的第几条数据
        Integer i = analysisContext.readRowHolder().getRowIndex();
        log.info("解析到第: {}条数据: {}", i, JSON.toJSONString(dto));
        concurrentHashMap.put(i, dto);
        // 达到BATCH_COUNT了, 需要去存储一次数据库, 防止数据几万条数据在内存, 容易OOM
        if (concurrentHashMap.size() >= BATCH_COUNT) {
            handleNumber += 1;
            saveData();
            // 存储完成清理集合
            concurrentHashMap.clear();
        }
    }

    /**
     * 所有数据解析完成调用
     *
     * @param analysisContext analysisContext类
     * @author ZYJ
     * @date 2021/8/23 16:18
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据, 确保最后遗留的数据也存储到数据库
        saveData();

    }

    /**
     * 保存导入数据
     *
     * @author ZYJ
     * @date 2021/8/23 16:20
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", concurrentHashMap.size());
        attendanceRuleWifiService.addBssidList(concurrentHashMap, ruleId);
        log.info("存储数据库成功！");
    }
}
