package com.wms.utils.excel.listener;

import cn.hutool.core.bean.BeanUtil;
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.WorkStationConfig;
import com.wms.service.WorkStationConfigService;
import com.wms.utils.StringUtils;
import com.wms.utils.excel.vo.StationConfigExcelVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

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

/**
 * 上传DBS监听
 */
public class UploadStationConfigListener implements ReadListener<StationConfigExcelVo> {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    private List<StationConfigExcelVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private final WorkStationConfigService workStationConfigService;// 工站配置服务
    private final String uploadUser;// 用户
    private final Map<String, WorkStationConfig> oldWorkStationConfigMap;// 旧配置
    private final Map<String, WorkStationConfig> newWorkStationConfigMap = new HashMap<>();// 新配置
    public UploadStationConfigListener(WorkStationConfigService workStationConfigService, Map<String, WorkStationConfig> oldWorkStationConfigMap, String uploadUser) {
        this.workStationConfigService = workStationConfigService;
        this.oldWorkStationConfigMap = oldWorkStationConfigMap;
        this.uploadUser = uploadUser;
    }

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

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param stationConfigExcelVo    one row value. It is same as {@link AnalysisContext#readRowHolder()}
     * @param analysisContext context
     */
    @Override
    public void invoke(StationConfigExcelVo stationConfigExcelVo, AnalysisContext analysisContext) {
        if (StringUtils.isNotEmpty(stationConfigExcelVo.getWorkStation())
        && StringUtils.isNotEmpty(stationConfigExcelVo.getSmallBox())) {
            // 符合条件的数据
            cachedDataList.add(stationConfigExcelVo);
        }
        // 达到BATCH_COUNT了
        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 (StationConfigExcelVo stationConfigExcelVo : cachedDataList) {
            String key = stationConfigExcelVo.getSmallBox();
            if (oldWorkStationConfigMap.containsKey(key)) {
                WorkStationConfig oldConfig = oldWorkStationConfigMap.get(key);
                oldConfig.setOrderQuantity(stationConfigExcelVo.getOrderQuantity());
                oldConfig.setWorkStation(stationConfigExcelVo.getWorkStation());
                oldConfig.setVehicle(stationConfigExcelVo.getVehicle());
                oldConfig.setVehicleLocation(stationConfigExcelVo.getVehicleLocation());
                oldConfig.setStartDateAdjust(stationConfigExcelVo.getStartDateAdjust());
                oldConfig.setWorkCenter(stationConfigExcelVo.getWorkCenter());
                oldConfig.setLastUpdateTime(LocalDateTime.now());
                oldConfig.setLastUpdateUser(uploadUser);
                oldConfig.setModel(stationConfigExcelVo.getModel());
                oldConfig.setBigBox(stationConfigExcelVo.getBigBox());
                newWorkStationConfigMap.put(key, oldConfig);
            } else {
                WorkStationConfig newStationConfig = BeanUtil.copyProperties(stationConfigExcelVo, WorkStationConfig.class);
                newStationConfig.setConfigId(generateId("STATION-CONFIG_"));
                newStationConfig.setLastUpdateTime(LocalDateTime.now());
                newStationConfig.setLastUpdateUser(uploadUser);
                newWorkStationConfigMap.put(key, newStationConfig);
            }
        }
    }

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