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;

/**
 * 视频状态切换监听器
 *
 * @author zhoupan
 * @date 2021/10/20
 */
@Component
public class VideoStatusListener implements ApplicationListener<VideoHardwareStatusEvent> {

    @Autowired
    ILabHardwareService labHardwareService;

    @Autowired
    LabHardwareMapper labHardwareMapper;
    @Autowired
    SubMessageSendManager subMessageSendManager;

    @Override
    public void onApplicationEvent(VideoHardwareStatusEvent relayHardwareStatusEvent) {
        //视频一直再推送 ，每次修改都很耗费资源，
        //todo 优化：需要加入缓存
        EquipmentStatus source = relayHardwareStatusEvent.getSource();
        int i = labHardwareService.updateStatus(source);
        //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);
            }
        }
    }
}
