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

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.zcxk.core.common.pojo.AjaxMessage;
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.service.DeviceService;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

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

/**
 * @author linqingwei
 * @date 2021-07-22 17:52
 */
@Slf4j
public class DeviceImportListener extends AnalysisEventListener<DeviceImportData> {
    private List<DeviceImportData> list = new ArrayList<>();
    private DeviceService deviceService;
    private ExcelData excelData;


    public DeviceImportListener(DeviceService deviceService,ExcelData excelData) {
        this.deviceService = deviceService;
        this.excelData = excelData;
    }

    @Override
    public void invoke(DeviceImportData data, AnalysisContext analysisContext) {
        if (
                data.getDeviceNo() == null || data.getDeviceTypeName() == null
                && data.getMeterNo() == null || data.getCompanyOrgName() == null
        ) {
            data.setRemark("必填项不能为空");
            list.add(data);
            excelData.getFailNum().incrementAndGet();
            return;
        }
        ResultMessage resultMessage = deviceService.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<DeviceImportData> getData(){
        return list;
    }

}
