package com.zcxk.rmcp.web.excel.resolver.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.zcxk.core.common.pojo.ResultMessage;
import com.zcxk.rmcp.web.excel.model.DeviceImportData;
import com.zcxk.rmcp.web.excel.model.ExcelData;
import com.zcxk.rmcp.web.excel.model.InstallMeterData;
import com.zcxk.rmcp.web.service.DeviceService;
import com.zcxk.rmcp.web.service.install.InstallListService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author linqingwei
 * @date 2021-07-28 15:29
 */
@Slf4j
public class InstallImportListener extends AnalysisEventListener<InstallMeterData> {
    private List<InstallMeterData> list = new ArrayList<>();


    private InstallListService installListService;
    private ExcelData excelData;


    public InstallImportListener(InstallListService installListService,ExcelData excelData) {
        this.installListService = installListService;
        this.excelData = excelData;
    }
    @Override
    public void invoke(InstallMeterData data, AnalysisContext analysisContext) {
        System.out.println(data);
        if (
                data.getId() == null ||
                        data.getDoorNo() == null || data.getMeterNo() == null
                        || data.getDeviceNo() == null || data.getStartDegree() == null
        ) {
            data.setRemark("必填项不能为空");
            list.add(data);
            excelData.getFailNum().incrementAndGet();
            return;
        }
        ResultMessage resultMessage = installListService.saveExcelData(data,excelData);
        if(resultMessage.getStatus()){
            excelData.getSuccessNum().incrementAndGet();
        }else {
            data.setRemark(resultMessage.getMessage());
            list.add(data);
            excelData.getFailNum().incrementAndGet();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("批量导出设备完成 successNum = {},failNum = {}",excelData.getSuccessNum().get(),excelData.getFailNum().get());
    }

    public List<InstallMeterData> getData(){
        return list;
    }

}
