package com.wms.utils.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wms.entity.table.WorkDate;
import com.wms.service.WorkDateService;
import com.wms.utils.excel.vo.WorkDateExcelVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.wms.config.InitLocalConfig.localWorkDateList;

/**
 * 上传DBS监听
 */
public class UploadWorkDateListener implements ReadListener<WorkDateExcelVo> {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    private List<WorkDateExcelVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private final WorkDateService workDateService;// 工作日服务
    private int key = 1;// 主键
    private final Map<LocalDate, WorkDate> newWorkDateMap = new HashMap<>();// 新的工作日
    public UploadWorkDateListener(WorkDateService workDateService) {
        this.workDateService = workDateService;
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        int rowCount = context.readRowHolder().getRowIndex() + 1;
        logger.error("处理Dbs数据发生异常，第{}行发生异常。", rowCount);
        throw new Exception("第" + rowCount + "行数据异常。");
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param workDateExcelVo    one row value. It is same as {@link AnalysisContext#readRowHolder()}
     * @param analysisContext context
     */
    @Override
    public void invoke(WorkDateExcelVo workDateExcelVo, AnalysisContext analysisContext) {
        if (workDateExcelVo.getWorkDate() != null && !newWorkDateMap.containsKey(workDateExcelVo.getWorkDate())) {
            // 符合条件的数据
            cachedDataList.add(workDateExcelVo);
        }
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param analysisContext context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 再做一次数据处理
        saveData();
        // 在这里统一保存数据
        insertIntoDb();

    }

    /**
     * 存储数据
     */
    private void saveData() {
        for (WorkDateExcelVo workDateExcelVo : cachedDataList) {
            if (newWorkDateMap.containsKey(workDateExcelVo.getWorkDate())) {
                // 工作日重复
                continue;
            }
            // 创建一个新的工作日历对象
            WorkDate workDate = new WorkDate();
            workDate.setKeyId(key);
            workDate.setWorkDate(workDateExcelVo.getWorkDate());
            workDate.setRemark(workDateExcelVo.getRemark());
            newWorkDateMap.put(workDateExcelVo.getWorkDate(), workDate);
            key++;
        }
    }

    /**
     * 保存数据库
     */
    private void insertIntoDb() {
        logger.info("此次共导入{}条数据。", newWorkDateMap.size());
        // 保存数据
        workDateService.saveOrUpdateBatch(newWorkDateMap.values(), BATCH_COUNT);
        logger.info("保存成功{}条数据。", newWorkDateMap.size());
        // 生成工作日历
        localWorkDateList = workDateService.list(new LambdaQueryWrapper<WorkDate>().orderByAsc(WorkDate::getWorkDate)).stream().map(WorkDate::getWorkDate).distinct().toList();
        logger.info("生成工作日历Map成功。");
    }
}
