package org.jeecg.modules.excelutil;

import cn.com.ctop.common.module.utils.SpringUtils;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.ctop.service.impl.JhsBakendDataServiceImpl;
import org.jeecg.modules.excelutil.entity.JhsBakendDataEntity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class JhsBakendDataExcelListener extends AnalysisEventListener<JhsBakendDataEntity> {
    //自定义用于暂时存储data。
    //可以通过实例获取该值
    private List<JhsBakendDataEntity> datas = new ArrayList<>();
    private static final int BATCH_COUNT = 200;

    @Override
    public void invoke(JhsBakendDataEntity object, AnalysisContext context) {
        //数据存储到list，供批量处理，或后续自己业务逻辑处理。
        String date = object.getStateDate();
        String formatDate = date.substring(0,4)+"-"+date.substring(4,6)+"-"+date.substring(6,8);
        object.setStateDate(formatDate);
        object.setVistor(object.getTaskName().split("-")[1]);
        datas.add(object);
        if(null!=datas&&datas.size()>=BATCH_COUNT){
            saveDate();
            datas.clear();
        }
    }

    private void saveDate() {
        JhsBakendDataServiceImpl dataService = SpringUtils.getApplicationContext().getBean(JhsBakendDataServiceImpl.class);
        dataService.replaceEntityList(datas);
    }

    private void doSomething(Object object) {
        //入库调用接口
        JhsBakendDataEntity dataEntity = (JhsBakendDataEntity) object;
        dataEntity.setCreateTime(new Date());
        dataEntity.setUpdateTime(new Date());
        String date = dataEntity.getStateDate();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        try {
            date = DateUtils.formatDate(dateFormat.parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        dataEntity.setStateDate(date);
        JhsBakendDataServiceImpl dataService = SpringUtils.getApplicationContext().getBean(JhsBakendDataServiceImpl.class);
        dataService.replaceEntity(dataEntity);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // datas.clear();//解析结束销毁不用的资源
    }

    public List<JhsBakendDataEntity> getDatas() {
        return datas;
    }

    public void setDatas(List<JhsBakendDataEntity> datas) {
        this.datas = datas;
    }
}
