package com.hs.admin.util;

import com.hs.admin.base.RabbitMqConstant;
import com.hs.admin.dao.JcbDao;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xieheng
 */
@Component
public class RabbitmqUtil {
    @Resource
    RabbitTemplate rabbitTemplate;
    @Resource
    JcbDao jcbDao;

    String[] queueNames;

    public String[] getQueueNames() {
        return queueNames;
    }

    public void setQueueNames(String[] queueNames) {
        this.queueNames = queueNames;
    }

    /**
     * @description:新增队列
     * @author: XieHeng
     * @param: queueName
     * @return: void
     * @date: 2021/5/25 1:49 下午
     */
    public void newQueue(String queueName) {
        ConnectionFactory connectionFactory = rabbitTemplate.getConnectionFactory();
        Connection connection = connectionFactory.createConnection();
        Channel channel = connection.createChannel(true);
        try {
            channel.queueDeclare(queueName, false, false, false, null);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                channel.close();
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    @PostConstruct
    public void getJcbIdList() {
        List<String> jcbIdList = jcbDao.getJcbIdList();
        if (!CollectionUtils.isEmpty(jcbIdList)) {
            List<String> list = new ArrayList<>();
            for (String jcbId : jcbIdList) {
                String queueName = RabbitMqConstant.JOB_QUEUE + jcbId;
                newQueue(queueName);
                list.add(queueName);
            }
            queueNames = list.toArray(new String[list.size()]);
        } else {
            queueNames = new String[]{RabbitMqConstant.JOB_QUEUE};
        }
    }
}
