package com.bailuntec.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.bailuntec.domain.constant.CommonConstant;
import com.bailuntec.domain.entity.DcBaseStock;
import com.bailuntec.domain.example.DcBaseStockExample;
import com.bailuntec.job.AutoTurnoverJob;
import com.bailuntec.mapper.DcBaseStockMapper;
import com.bailuntec.utils.SessionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 有个很重要的点 DemoDataListener 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进去
 * </p>
 *
 * @author robbendev
 * @since 2020/6/6 5:29 下午
 */
public class ExcelListener extends AnalysisEventListener<DcAutoTurnoverExcel> {

    private static final Logger LOGGER = LoggerFactory.getLogger(DcAutoTurnoverExcel.class);
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;

    private AutoTurnoverJob autoTurnoverJob;

    public ExcelListener() {
        autoTurnoverJob = new AutoTurnoverJob();
    }

    List<DcAutoTurnoverExcel> list = new ArrayList<>();


    @Override
    public void invoke(DcAutoTurnoverExcel data, AnalysisContext context) {
        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data));
        list.add(data);
        if (list.size() >= BATCH_COUNT) {
            syncData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        syncData();
        LOGGER.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void syncData() {
        LOGGER.info("{}条数据，开始存储数据库！", list.size());
        list.forEach(dcAutoTurnoverExcel -> {

            DcBaseStock dcBaseStock = SessionUtil.getSession().getMapper(DcBaseStockMapper.class)
                    .selectOneByExample(DcBaseStockExample.newAndCreateCriteria()
                            .andBailunSkuEqualTo(dcAutoTurnoverExcel.getSku())
                            .andWarehouseCodeEqualTo(dcAutoTurnoverExcel.getWarehouseCode())
                            .example());

            try {
                autoTurnoverJob.autoTurnoverFromStock(DateTimeFormatter.ofPattern(CommonConstant.DATE_FORMAT).format(LocalDate.now()), dcBaseStock);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        LOGGER.info("存储数据库成功！");
    }
}
