package com.chinaweal.aiccs.aiccs.nonIocalCirculation.excelListener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.chinaweal.aiccs.aiccs.nonIocalCirculation.entity.EOtCase;
import com.chinaweal.aiccs.aiccs.nonIocalCirculation.entity.dto.EOTCaseDto;
import com.chinaweal.aiccs.aiccs.nonIocalCirculation.service.EOtCaseService;
import com.chinaweal.aiccs.common.util.StringUtils;
import org.springframework.beans.BeanUtils;

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

/**
 * @author Lee
 * @since 2021-08-19 15:41
 */
public class EOTCaseExcelListener extends AnalysisEventListener<EOTCaseDto> {

    //Logger

    /**
     * 每隔10条存储数据库，实际使用中可以1000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 1000;
    List<EOtCase> list = new ArrayList<>();

    private EOtCaseService eOtCaseService;

    public EOTCaseExcelListener(EOtCaseService eOtCaseService){
        this.eOtCaseService = eOtCaseService;
    }

    /**
     * 这个每一条数据解析都会来调用
     * @param eotCaseDto
     * @param analysisContext
     */
    @Override
    public void invoke(EOTCaseDto eotCaseDto, AnalysisContext analysisContext) {
        if (eotCaseDto != null) {  //如果excel不为空
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");

            if(StringUtils.isNotBlank(eotCaseDto.getPendecissdateStr())){
                LocalDate date = LocalDate.parse(eotCaseDto.getPendecissdateStr(), df);
                eotCaseDto.setPendecissdate(date);
            }
            if(StringUtils.isNotBlank(eotCaseDto.getPublicDateStr())){
                LocalDate date = LocalDate.parse(eotCaseDto.getPublicDateStr(), df);
                eotCaseDto.setPublicDate(date);
            }
            EOtCase eOtCase = new EOtCase();
            BeanUtils.copyProperties(eotCaseDto,eOtCase);
            eOtCase.setInsertTime(LocalDateTime.now());
//            eOtCase.setPublicDate(eotCaseDto.getPublicDate());
//            System.out.println(eotCaseDto.getPublicDate());
            eOtCase.setEntname(eotCaseDto.getEntname());
            list.add(eOtCase);
            //调用service方法，将数据存入数据库中
            // 达到BATCH_COUNT了，需要去存储一次数据库
            if(list.size()>=BATCH_COUNT) {
                saveData();
                list.clear();
            }
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
//        LOGGER.info("所有数据解析完成！");
    }

    private void saveData() {

//        System.out.println(list.size()+"条数据，开始存储数据库！");
//        System.out.println(list);
//            eOtCaseService.saveBatch(list);
        for (EOtCase eOtCase : list) {
            eOtCaseService.save(eOtCase);
        }
    }
}
