package com.zksy.park.listener;


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.zksy.park.domain.SmartEmployment;
import com.zksy.park.service.SmartEmploymentService;
import org.springframework.transaction.annotation.Transactional;

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

public class SmartEmploymentListener extends AnalysisEventListener<SmartEmployment> {

    private static final int BATCH_COUNT = 1000;
    private final SmartEmploymentService service;
    private final List<SmartEmployment> cachedDataList = new ArrayList<>();

    public SmartEmploymentListener(SmartEmploymentService service) {
        this.service = service;
    }

    @Override
    public void invoke(SmartEmployment data, AnalysisContext context) {
        LocalDateTime now = LocalDateTime.now();
        data.setId(null);
        //TODO 时间处理
        if(data.getCreateTime()==null){
            data.setCreateTime(now);
        }
        data.setUpdateTime(now);

        cachedDataList.add(data);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            cachedDataList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
    }

    @Transactional
    protected void saveData() {
        if (!cachedDataList.isEmpty()) {
            service.saveBatch(cachedDataList);
        }
    }
}