package com.junmp.jyzb.utils;

import com.alibaba.fastjson.JSON;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RabbitMQSendMsg {
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private RabbitAdmin rabbitAdmin;
    public  void SendMsg(String exchangeName,String name,Object msg)
    {
        //exchangeName交换机名称，name组织机构名称，msg发送的消息
        Queue queue=new Queue(name,true,false,false);
        Exchange exchange = new DirectExchange(exchangeName, true, false);
        rabbitAdmin.declareQueue(queue);
        rabbitAdmin.declareExchange(exchange);
        rabbitAdmin.declareBinding(BindingBuilder.bind(queue).to(exchange).with(name).noargs());

        String jsonString = JSON.toJSONString(msg);
//        // 创建 MessageProperties 对象，并设置 TTL
//        MessageProperties messageProperties = new MessageProperties();
//        messageProperties.setExpiration(String.valueOf(ttlMillis));
//
//        // 发送带有 TTL 的消息
//        rabbitTemplate.send(exchangeName, name, new Message(jsonString.getBytes(), messageProperties));
        rabbitTemplate.convertAndSend(exchangeName, name, jsonString);
    }



    // 发布消息到交换机，根据不同的主题和消息内容
    public void publishOrgMessage(String orgId, String message) {
        String routingKey = "org." + orgId;
        rabbitTemplate.convertAndSend("topicExchange", routingKey, message);
    }

    public void publishCabinetMessage(String cabinetId, String message) {
        String routingKey = "cabinet." + cabinetId;
        rabbitTemplate.convertAndSend("topicExchange", routingKey, message);
    }

    public void sendToExchange(String exchangeName,String routingKey,Object msg){
        String jsonString = JSON.toJSONString(msg);
        rabbitTemplate.convertAndSend(exchangeName,routingKey,jsonString);
    }
    //推送消息（广播式推送）
    public void sendFanoutMsg(String exchangeName, List<String> names,Object msg){
        //exchangeName交换机名称，name单警柜或本地仓库，msg发送的消息
        for (String name:names) {
            Queue queue=new Queue(name,true,false,false);
            Exchange exchange = new FanoutExchange(exchangeName, true, false);
            rabbitAdmin.declareQueue(queue);
            rabbitAdmin.declareExchange(exchange);
            rabbitAdmin.declareBinding(BindingBuilder.bind(queue).to(exchange).with("").noargs());
            // 将消息发送到交换机
            String jsonString = JSON.toJSONString(msg);
            rabbitTemplate.convertAndSend(exchangeName, name, jsonString);
        }

    }
}
