package com.bweb.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.bweb.excel.model.ImportDeviceModel;
import com.hfkj.entity.BsDevice;
import com.hfkj.model.UserInfoModel;
import com.hfkj.service.BsDeviceService;
import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: 胡锐
 * @Description: 导入监听器
 * @Date: 2021/3/20 21:03
 */
public class ImportDeviceListener extends AnalysisEventListener<ImportDeviceModel> {

    List<ImportDeviceModel> errorData = new ArrayList<>();
    List<BsDevice> successData = new ArrayList<>();

    /**
     * 全部设备数据集合
     */
    List<BsDevice> allDeviceList = new ArrayList<>();

    private BsDeviceService deviceService;

    private UserInfoModel userInfoModel;

    Integer deviceType;

    private BsDevice device;

    /**
     * @Author 胡锐
     * @Description 解析到的每一条数据都会调用此方法
     * @Date 2021/3/20 21:08 
     **/
    @Override
    public void invoke(ImportDeviceModel deviceModel, AnalysisContext analysisContext) {
        if (StringUtils.isBlank(deviceModel.getDeviceNo())) {
            deviceModel.setErrorMessage("请填写设备编号");
            errorData.add(deviceModel);
            return;
        }

        List<BsDevice> collect = allDeviceList.stream().filter(o -> o.getDeviceNo().equals(deviceModel.getDeviceNo())).collect(Collectors.toList());
        if (collect.size() > 0) {
            deviceModel.setErrorMessage("设备编号已存在，请勿重复导入");
            errorData.add(deviceModel);
            return;
        }

        device = new BsDevice();
        device.setDeviceType(deviceType);
        device.setDeviceNo(deviceModel.getDeviceNo());
        device.setDeviceIccid(deviceModel.getDeviceIccid());
        device.setDeviceImsi(deviceModel.getDeviceImsi());
        device.setOpUserId(userInfoModel.getSecUser().getId());
        device.setOpUserName(userInfoModel.getSecUser().getUserName());
        device.setBindStatus(false);
        successData.add(device);
        allDeviceList.add(device);
    }

    /**
     * @Author 胡锐
     * @Description 所有数据解析完成了 都会来调用此方法
     * @Date 2021/3/20 21:08 
     **/
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (successData.size() > 0) {
            for (BsDevice device : successData) {
                deviceService.addDevice(device);
            }
        }
        this.successData.clear();
        this.allDeviceList.clear();
    }

    public List<ImportDeviceModel> getErrorData() {
        return errorData;
    }

    public void initData(UserInfoModel userInfoModel, Integer deviceType,BsDeviceService deviceService) {
        this.userInfoModel = userInfoModel;
        this.deviceType = deviceType;
        this.deviceService = deviceService;
        this.allDeviceList = this.deviceService.getDeviceList(new HashMap<>());
    }
}
