package com.mortals.xhx.thread;


import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.util.AbstractThread;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.common.key.QueueKey;
import com.mortals.xhx.module.alarm.model.AlarmRecordsEntity;
import com.mortals.xhx.module.alarm.model.AlarmRecordsQuery;
import com.mortals.xhx.module.alarm.service.AlarmRecordsService;
import com.mortals.xhx.module.device.service.DeviceService;
import com.mortals.xhx.queue.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


/**
 * 告警信息发送
 *
 * @author: zxfei
 * @date: 2025/4/3 17:00
 */
@Slf4j
@Service
@Order(value = 3)
public class AlarmSendMsgThread extends AbstractThread {

    @Autowired
    private ICacheService cacheService;
    @Autowired
    private DeviceService deviceService;

    @Autowired
    private AlarmRecordsService recordsService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

/*
    @Autowired
    private MessageProducer messageProducer;
*/

    @Override
    protected int getSleepTime() {
        return 1000;
    }

    @Override
    protected void process() {
        log.info("AlarmSendMsgThread process");

        List<AlarmRecordsEntity> alarmRecordsEntities = recordsService.find(new AlarmRecordsQuery().push(YesNoEnum.NO.getValue()));
        for (AlarmRecordsEntity alarmRecordsEntity : alarmRecordsEntities) {

            TbQueueMsgHeaders header = new DefaultTbQueueMsgHeaders();
            header.put(MessageHeader.MESSAGETYPE, "alarm");
            header.put(MessageHeader.TIMESTAMP, new Date().getTime() + "");
            TbQueueMsg queueMsg = new DefaultTbQueueMsg(IdUtil.fastUUID(), alarmRecordsEntity.getAlarmContent(), header);

            CorrelationData correlationData = new CorrelationData(IdUtil.fastSimpleUUID());
            rabbitTemplate.convertAndSend(QueueKey.DEFAULT_EXCHANGE, QueueKey.ALARM_MSG_QUEUE, JSON.toJSONString(queueMsg), correlationData);

        }

    }


    @Override
    protected void threadClosed() {
        super.close();
    }
}
