
package com.mortals.xhx.queue.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.mortals.xhx.common.model.DefaultTbQueueMsgHeaders;
import com.mortals.xhx.common.model.MessageHeader;
import com.mortals.xhx.queue.*;
import com.mortals.xhx.queue.kafka.AbstractTbQueueConsumerTemplate;
import com.rabbitmq.client.*;
import lombok.Getter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;

/**
 * 消费连接池
 *
 * @author: zxfei
 * @date: 2022/4/25 13:49
 */
@Slf4j
public class TbRabbitMqConsumerTemplate<T extends TbQueueMsg> extends AbstractTbQueueConsumerTemplate<GetResponse, T> {

    private final TbQueueMsgDecoder<T> decoder;
    @Getter
    private Channel channel;
    private Connection connection;

    /**
     * rabbmit设置
     */
    private TbRabbitMqSettings rabbitMqSettings;

    private volatile Set<String> queues=new HashSet<>();

    public TbRabbitMqConsumerTemplate(TbRabbitMqSettings rabbitMqSettings, String topic, TbQueueMsgDecoder<T> decoder) {
        super(topic);
        this.decoder = decoder;
        this.rabbitMqSettings = rabbitMqSettings;
        try {
            connection = rabbitMqSettings.getConnectionFactory().newConnection();
            channel = connection.createChannel();
            log.info("channelNumber:" + channel.getChannelNumber());
        } catch (IOException | TimeoutException e) {
            log.error("Failed to create connection.", e);
        }
        stopped = false;
    }

    @Override
    protected List<GetResponse> doPoll(long durationInMillis) {
        List<GetResponse> result = queues.parallelStream()
                .map(queue -> {
                    try {
                        GetResponse getResponse = channel.basicGet(queue, true);
                        return getResponse;
                    } catch (IOException e) {
                        log.error("Failed to get messages from queue: {},{}", queue, e);
                        try {
                            channel = connection.createChannel();
                            Map<String, Object> args = new HashMap<>();
                            args.put("x-message-ttl", Integer.parseInt(rabbitMqSettings.getMessageTtl()));
                            channel.queueDeclare(queue, true, false, false, args);
                        } catch (IOException ioException) {
                            ioException.printStackTrace();
                        }
                        return null;
                    }
                }).filter(Objects::nonNull).collect(Collectors.toList());
        if (result.size() > 0) {
            return result;
        } else {
            return Collections.emptyList();
        }
    }

    @Override
    protected void doSubscribe(List<String> topicNames) {

        //新增的topkcnames
        topicNames.stream().forEach(topic->{
            queues.add(topic);
        });

//        queues = partitions.stream()
//                .map(TopicPartitionInfo::getFullTopicName)
//                .collect(Collectors.toSet());
        log.info("doSubscribe:{},topicNames:{}", JSON.toJSONString(queues), JSON.toJSONString(queues));
    }

    @Override
    protected void doCommit() {
        try {
            channel.basicAck(0, true);
        } catch (IOException e) {
            log.error("Failed to ack messages.", e);
        }
    }

    @Override
    protected void doUnsubscribe() {
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException | TimeoutException e) {
                log.error("Failed to close the channel.");
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException e) {
                log.error("Failed to close the connection.");
            }
        }
    }

    @Override
    public String getChannelNumber() {
        return channel.getChannelNumber() + "";
    }

    public T decode(GetResponse message) {
        try {
            DefaultTbQueueMsg msg = new DefaultTbQueueMsg();
            TbQueueMsgHeaders headers = new DefaultTbQueueMsgHeaders();

            Map<String, Object> map = JSON.parseObject(new String(message.getBody()), HashMap.class);
            msg.setKey((String) map.get("key"));
            String payloadStr = (String) map.get("data");
            msg.setData(payloadStr);
            String headerStr = ((JSONObject) map.get("headers")).getString("data");
            HashMap<String, String> hashMap = JSON.parseObject(headerStr, HashMap.class);
            headers.setData(hashMap);
            msg.setHeaders(headers);
            return decoder.decode(msg);
        } catch (Exception e) {
            log.error("反序列化异常！", e);
            return null;
        }

    }
}
