package com.zd.laboratory.event;

import cn.hutool.core.collection.CollUtil;
import com.zd.laboratory.domain.LabHardware;
import com.zd.laboratory.domain.vo.LabHardwareVO;
import com.zd.laboratory.mapper.LabHardwareMapper;
import com.zd.laboratory.mqtt.entiy.EquipmentStatus;
import com.zd.laboratory.mqtt.service.impl.SubMessageSendManager;
import com.zd.laboratory.service.ILabHardwareService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 继电器状态切换监听器
 *
 * @author zhoupan
 * @date 2021/10/20
 */
@Component
public class RelayStatusListener implements ApplicationListener<RelayHardwareStatusEvent> {

    @Autowired
    ILabHardwareService labHardwareService;

    @Autowired
    LabHardwareMapper labHardwareMapper;

    @Autowired
    SubMessageSendManager subMessageSendManager;

    @Override
    public void onApplicationEvent(RelayHardwareStatusEvent relayHardwareStatusEvent) {
        EquipmentStatus source = relayHardwareStatusEvent.getSource();
        int i = labHardwareService.updateRelayStatus(source);
        //推送硬件状态数据 ，推送不存在微应用状态不一致的问题，就算其多个实例，也会因feign负载均衡后只有一个实例实际监听事件
        //todo 这里需要优化 每次推送都要反查一次数据库，非常耗费资源
        //这里不管是继电器下的哪一个设备变化，都把继电器下的所有设备查出来
        if (i > 0) {
            //这里的前提是继电器下的设备都是属于一个实验室的 切记！！！
            LabHardware labHardware = new LabHardware();
            labHardware.setRelayCode(source.getNum());
            List<LabHardware> labHardwareVOS = labHardwareMapper.selectLabHardwareStatusByRelay(labHardware);
            List<EquipmentStatus> collect = Optional.ofNullable(labHardwareVOS)
                    .orElseGet(Collections::emptyList)
                    .stream()
                    .map(a -> {
                        EquipmentStatus equipmentStatus = new EquipmentStatus();
                        equipmentStatus.setNum(a.getId().toString());
                        equipmentStatus.setHardwareOperate(a.getOperate());
                        return equipmentStatus;
                    }).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(collect)) {
                subMessageSendManager.sendHardwareUpdate(labHardwareVOS.get(0), collect, 1);
            }
        }
    }
}
