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.wms.entity.table.KateDBS;
import com.wms.service.KateDBSService;
import com.wms.utils.StringUtils;
import com.wms.utils.excel.vo.KateDbsExcelVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

import static com.wms.utils.WmsUtils.generateId;

/**
 * 上传DBS监听
 */
public class UploadDbsListener implements ReadListener<KateDbsExcelVo> {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    private List<KateDbsExcelVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private final KateDBSService kateDBSService;// Dbs服务
    private final String uploadUser;// 用户
    private final Map<String, KateDBS> oldKateDBSMap;// 旧的DBS数据
    private final Map<String, KateDBS> newKateDBSMap = new HashMap<>();// 新的DBS数据
    public UploadDbsListener(KateDBSService kateDBSService, Map<String, KateDBS> oldKateDBSMap, String uploadUser) {
        this.kateDBSService = kateDBSService;
        this.oldKateDBSMap = oldKateDBSMap;
        this.uploadUser = uploadUser;
    }

    @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 kateDbsExcelVo    one row value. It is same as {@link AnalysisContext#readRowHolder()}
     * @param analysisContext context
     */
    @Override
    public void invoke(KateDbsExcelVo kateDbsExcelVo, AnalysisContext analysisContext) {
        if (kateDbsExcelVo.getWorkSequence() != null
        && StringUtils.isNotEmpty(kateDbsExcelVo.getWorkOrder())
        && StringUtils.isNotEmpty(kateDbsExcelVo.getMachineNo())
        && kateDbsExcelVo.getPlanStartDate() != null) {
            // 符合条件的数据
            cachedDataList.add(kateDbsExcelVo);
        }
        // 达到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 (KateDbsExcelVo kateDbsExcelVo : cachedDataList) {
            if (newKateDBSMap.containsKey(kateDbsExcelVo.getWorkOrder())) {
                // 新的数据工单号重复，那么跳过这条DBS
                continue;
            }
            if (oldKateDBSMap.containsKey(kateDbsExcelVo.getWorkOrder())) {
                // 之前有
                KateDBS oldKateDbs = oldKateDBSMap.get(kateDbsExcelVo.getWorkOrder());
                oldKateDbs.setWorkSequence(kateDbsExcelVo.getWorkSequence());
                oldKateDbs.setMachineNo(kateDbsExcelVo.getMachineNo());
                oldKateDbs.setPlanStartDate(kateDbsExcelVo.getPlanStartDate());
                oldKateDbs.setLastUpdateTime(LocalDateTime.now());
                oldKateDbs.setLastUpdateUser(uploadUser);
                // 替换
                newKateDBSMap.put(kateDbsExcelVo.getWorkOrder(), oldKateDbs);
            } else {
                // 之前没有
                KateDBS newKateDbs = new KateDBS();
                newKateDbs.setDbsId(generateId("DBS_"));
                newKateDbs.setWorkSequence(kateDbsExcelVo.getWorkSequence());
                newKateDbs.setMachineNo(kateDbsExcelVo.getMachineNo());
                newKateDbs.setWorkOrder(kateDbsExcelVo.getWorkOrder());
                newKateDbs.setPlanStartDate(kateDbsExcelVo.getPlanStartDate());
                newKateDbs.setDbsStatus(0);
                newKateDbs.setLastUpdateTime(LocalDateTime.now());
                newKateDbs.setLastUpdateUser(uploadUser);
                // 添加
                newKateDBSMap.put(kateDbsExcelVo.getWorkOrder(), newKateDbs);
            }
        }
    }

    /**
     * 保存数据库
     */
    private void insertIntoDb() {
        logger.info("此次共导入{}条数据。", newKateDBSMap.size());
        // 保存数据
        kateDBSService.saveOrUpdateBatch(newKateDBSMap.values(), BATCH_COUNT);
        logger.info("保存成功{}条数据。", newKateDBSMap.size());
    }
}
