package com.zd.laboratory.event;

import cn.hutool.core.collection.CollUtil;
import com.zd.laboratory.domain.LabHardware;
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;

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

    @Autowired
    ILabHardwareService labHardwareService;
    @Autowired
    LabHardwareMapper labHardwareMapper;
    @Autowired
    SubMessageSendManager subMessageSendManager;

    @Override
    public void onApplicationEvent(OnecStatusEvent onecStatusEvent) {
        EquipmentStatus source = onecStatusEvent.getSource();
        int i = labHardwareService.updateStatus(source);
        //推送硬件状态数据 ，推送不存在微应用状态不一致的问题，就算其多个实例，也会因feign负载均衡后只有一个实例实际监听事件
        //todo 这里需要优化 每次推送都要反查一次数据库，非常耗费资源
        if (i > 0) {
            LabHardware labHardware = new LabHardware();
            labHardware.setHardwareNum(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, 2);
            }

        }
    }
}
