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.app.dto.extend.StockDetailInfo;
import com.wms.entity.table.Stock;
import com.wms.service.StockService;
import com.wms.utils.excel.vo.StockExcelVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static com.wms.constants.WmsConstants.MYSQL_JSON_CI;
import static com.wms.utils.WmsUtils.generateId;

/**
 * 上传库存监听
 */
public class UploadStocksListener implements ReadListener<StockExcelVo> {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 每隔5条存储数据库，实际使用中可以1000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 1000;
    /**
     * 保存数据总数
     */
    private int SAVE_COUNT = 0;
    private List<StockExcelVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private final StockService stockService;
    public UploadStocksListener(StockService stockService) {
        this.stockService = stockService;
    }

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

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param stockExcelVo    one row value. It is same as {@link AnalysisContext#readRowHolder()}
     * @param analysisContext context
     */
    @Override
    public void invoke(StockExcelVo stockExcelVo, AnalysisContext analysisContext) {
        cachedDataList.add(stockExcelVo);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            logger.info("已经导入{}条数据，开始存储数据库！", cachedDataList.size());
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param analysisContext context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        logger.info("此次共保存{}条数据。", SAVE_COUNT);
    }

    /**
     * 存储数据
     */
    private void saveData() {
        List<Stock> stockList = new ArrayList<>();
        // TODO 下个项目优化
        for (StockExcelVo stockExcelVo : cachedDataList) {
            Stock oldStock = stockService.getOne(new LambdaQueryWrapper<Stock>()
                    .eq(Stock::getVehicleId, stockExcelVo.getVehicleId())
                    .eq(Stock::getLocationId, stockExcelVo.getLocationId())
                    .apply("goods_related ->> '$.goodsId' = {0}" + MYSQL_JSON_CI, stockExcelVo.getGoodsId())
                    .last("limit 1"));
            if (oldStock != null) {
                StockDetailInfo goodsRelated = oldStock.getGoodsRelated();
                goodsRelated.setGoodsStatus(stockExcelVo.getGoodsStatus());
                goodsRelated.setRemainNum(stockExcelVo.getRemainNum());
                oldStock.setGoodsRelated(goodsRelated);
                oldStock.setLocationId(stockExcelVo.getLocationId());
                oldStock.setStockStatus(stockExcelVo.getStockStatus());
                oldStock.setWeight(stockExcelVo.getWeight());
                oldStock.setNoUseDays(stockExcelVo.getNoUseDays());
                oldStock.setLastUpdateTime(LocalDateTime.now());
                oldStock.setIsInventory(stockExcelVo.getIsInventory());
                oldStock.setInventoryTaskId(stockExcelVo.getInventoryTaskId());
                stockList.add(oldStock);
            } else {
                Stock stock = new Stock();
                stock.setStockId(generateId("ST_"));
                stock.setLocationId(stockExcelVo.getLocationId());
                stock.setVehicleId(stockExcelVo.getVehicleId());
                stock.setWeight(stockExcelVo.getWeight());
                stock.setStockStatus(stockExcelVo.getStockStatus());
                stock.setCreateTime(stockExcelVo.getCreateTime());
                stock.setLastUpdateTime(stockExcelVo.getLastUpdateTime());
                stock.setLastUpdateUser(stockExcelVo.getLastUpdateUser());
                stock.setIsInventory(stockExcelVo.getIsInventory());
                stock.setInventoryTaskId(stockExcelVo.getInventoryTaskId());
                stock.setNoUseDays(stockExcelVo.getNoUseDays());
                // 物料信息
                StockDetailInfo goodsRelated = new StockDetailInfo();
                goodsRelated.setGoodsId(stockExcelVo.getGoodsId());
                goodsRelated.setGoodsName(stockExcelVo.getGoodsName());
                goodsRelated.setGoodsStatus(stockExcelVo.getGoodsStatus());
                goodsRelated.setTotalNum(stockExcelVo.getTotalNum());
                goodsRelated.setRemainNum(stockExcelVo.getRemainNum());
                stock.setGoodsRelated(goodsRelated);
                stockList.add(stock);
            }
        }
        stockService.saveBatch(stockList);
        SAVE_COUNT += stockList.size();
    }
}
