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.constants.enums.ConfigMapKeyEnum;
import com.wms.entity.table.WorkFlow;
import com.wms.service.WorkFlowService;
import com.wms.utils.WmsUtils;
import com.wms.utils.excel.vo.KateWorkFlowExcelVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * 上传库存监听
 */
public class UploadWorkFlowListener implements ReadListener<KateWorkFlowExcelVo> {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 每隔5条存储数据库，实际使用中可以1000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 1000;
    private List<KateWorkFlowExcelVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private final WorkFlowService workFlowService;// Dbs服务
    private final Map<String, WorkFlow> oldWorkFlowMap;// 旧的工作流数据
    private final Map<String, WorkFlow> newWorkFlowMap = new HashMap<>();// 新的工作流数据
    private final List<String> standIds;// 不可用工作站台
    public UploadWorkFlowListener(WorkFlowService workFlowService, Map<String, WorkFlow> oldWorkFlowMap, List<String> standIds) {
        this.workFlowService = workFlowService;
        this.oldWorkFlowMap = oldWorkFlowMap;
        this.standIds = standIds;
    }

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

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param workFlowExcelVo    one row value. It is same as {@link AnalysisContext#readRowHolder()}
     * @param analysisContext context
     */
    @Override
    public void invoke(KateWorkFlowExcelVo workFlowExcelVo, AnalysisContext analysisContext) {
        if (!standIds.contains(workFlowExcelVo.getWorkOrder())) {
                // 符合条件
                cachedDataList.add(workFlowExcelVo);
        }
        // 达到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 (KateWorkFlowExcelVo workFlowExcelVo : cachedDataList) {
            String key = workFlowExcelVo.getWorkOrder() + workFlowExcelVo.getGoodsId() + workFlowExcelVo.getWorkCenter();
            if (newWorkFlowMap.containsKey(key)) {
                continue;
            }
            // 查询数据库是否存在重复数据
            if (!oldWorkFlowMap.containsKey(key)) {
                // 之前没存在过
                WorkFlow newWorkFlow = new WorkFlow();
                newWorkFlow.setWorkFlowId(WmsUtils.generateId("WORKFLOW_"));
                newWorkFlow.setOrderId(key);
                newWorkFlow.setWorkStation(workFlowExcelVo.getWorkStation());
                newWorkFlow.setWorkOrder(workFlowExcelVo.getWorkOrder());
                newWorkFlow.setWorkCenter(workFlowExcelVo.getWorkCenter());
                newWorkFlow.setGoodsId(workFlowExcelVo.getGoodsId());
                newWorkFlow.setNeedNum(workFlowExcelVo.getNeedNum());
                newWorkFlow.setCreateTime(LocalDateTime.now());
                newWorkFlow.setWorkStatus(0);
                newWorkFlow.setLightStatus(0);
                newWorkFlow.setPickedNum(BigDecimal.ZERO);
                newWorkFlowMap.put(key, newWorkFlow);
            }
        }
    }

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