package net.northking.cctp.device.bus.publisher;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.common.security.authentication.NKSecurityContext;
import net.northking.cctp.device.bus.BusConstants;
import net.northking.cctp.device.constants.DeviceError;
import net.northking.cctp.device.db.entity.CdDeviceStatus;
import net.northking.cctp.device.db.service.CdDeviceStatusService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;
@Component
public class DeviceStatusMQPublisher implements DeviceStatusPublisher {

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

    @Autowired
    private CdDeviceStatusService cdDeviceStatusService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    public void sendDeviceStateFanoutMQ(String deviceId){

        CdDeviceStatus status = this.cdDeviceStatusService.findByPrimaryKey(deviceId);

        Map<String,String> map = new LinkedHashMap<>();
        map.put("deviceId",deviceId);
        map.put("type",status.getDeviceType());
        map.put("status",status.getDeviceStatus());
        map.put("lastHeartbeatTime",status.getLastHeartbeatTime().toString());
        logger.info("---------------------------发送广播队列,{}",JSON.toJSONString(map));
        byte[] bytes;
        try {
            bytes = objectMapper.writeValueAsBytes(map);
        } catch (Exception e) {
            throw new PlatformRuntimeException(DeviceError.MQ_PUBLISHER_ERR,e);
        }
        MessageBuilder mb = MessageBuilder.withBody(bytes);
        mb.setContentType(MediaType.APPLICATION_JSON_VALUE);
        mb.setHeader("CCTP_User_ID", NKSecurityContext.getUserId());
        mb.setHeader("SaaS_Tenant_ID", NKSecurityContext.getTenantId());
        rabbitTemplate.convertAndSend(BusConstants.Device_Exchange_Name,"status",mb.build());
    }


}
