package net.northking.cctp.upperComputer.listener;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import net.northking.cctp.upperComputer.entity.ConsumerInfoDto;
import net.northking.cctp.upperComputer.service.DeviceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component("upperComputerConsumer")
public class UpperComputerConsumer implements ChannelAwareMessageListener {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private DeviceService deviceService;


    private final Logger logger = LoggerFactory.getLogger(UpperComputerConsumer.class);


    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        byte[] body = message.getBody();
        ConsumerInfoDto value = null;
        try {
            value = JSON.parseObject(body, ConsumerInfoDto.class);
        } catch (Exception e) {
            logger.error("消息转换异常",e);
        }
        if (null != value) {
            if ("0".equals(value.getType())) {   //重启上位机
                logger.debug("收到重启stf命令");
            } else if ("1".equals(value.getType())) {  //获取性能
                logger.debug("收到开启手机：{}性能命令",JSON.toJSONString(value));
                deviceService.startPerData(value.getPerDataInfo());
            } else if ("2".equals(value.getType())) {   //停止性能
                deviceService.stopPerData(value.getDeviceId());
            } else if ("3".equals(value.getType())) {   //重启设备
                logger.debug("收到重启设备：{}", JSON.toJSONString(value.getDeviceList()));
                deviceService.restartDevice(value.getDeviceList());
            }
        }
    }
}
