
package com.mortals.xhx.queue.rabbitmq;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.util.JsonUtil;
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;

    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)  {

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        List<GetResponse> result = queues.stream()
                .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);
        });
        log.info("doSubscribe:{}", 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 void unsubscribe(Set<TopicPartitionInfo> partitions) {
        Set<String> collect = partitions.stream().map(item -> item.getFullTopicName()).collect(Collectors.toSet());
        queues=queues.stream().filter(f->collect.contains(f)).collect(Collectors.toSet());
    }

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

    public T decode(GetResponse message) {

        try {
            DefaultTbQueueMsg msg = new DefaultTbQueueMsg();
            TbQueueMsgHeaders headers = new DefaultTbQueueMsgHeaders();

            String messageBody = new String(message.getBody());
            if(JSONUtil.isJson(messageBody)){
                Map<String, Object> map = JSON.parseObject(messageBody, 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);
            }else{
              throw new AppException("消息内容异常");
            }
        } catch (Exception e) {
            log.error("message:"+new String(message.getBody()),"反序列化异常！", e);
            return null;
        }

    }
}
