package org.springblade.common.notify.message;

import com.aliyun.openservices.ons.api.Consumer;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.aliyun.openservices.ons.api.PropertyValueConst;
import com.aliyun.openservices.shade.com.alibaba.rocketmq.common.protocol.heartbeat.MessageModel;
import org.springblade.common.notify.constant.NotifyErrorConstants;
import com.wn.common.validator.Validator;
import io.swagger.models.auth.In;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

/**
 * @author caiyihua
 */
@Slf4j
//@Component
@ConditionalOnProperty(name = "ali.mq.consumer.support.flag", havingValue = "true", matchIfMissing = false)
public class AliMqConsumer {
    @Value("${ali.mq.new.version:false}")
    @Setter
    private Boolean newVersion;
    @Value("${ali.mq.namesrv.addr:http://onsaddr.mq-internet-access.mq-internet.aliyuncs.com:80}")
    @Setter
    private String nameServer;
    @Value("${ali.mq.access.key}")
    @Setter
    private String accessKey;
    @Value("${ali.mq.secret.key}")
    @Setter
    private String secretKey;
    @Value("${ali.mq.consume.thread.nums:20}")
    @Setter
    private Integer consumeThreadNums;
    @Setter
    private Map<String, List<MessageHandlerHolder>> handlerHolderMap;

    /**
     * 订阅消息
     */
    public void start() {
        Validator.isTrueParameter(!CollectionUtils.isEmpty(handlerHolderMap),
                NotifyErrorConstants.MQ_MESSAGE_PARMETER_ERROR);
        for (String consumerId : handlerHolderMap.keySet()) {

            List<MessageHandlerHolder> handlerHolderList = handlerHolderMap.get(consumerId);

            if (CollectionUtils.isEmpty(handlerHolderList)) {
                log.warn("There is no any message handler for consumer ID {}, just ignore it!", consumerId);
                continue;
            }

            Properties properties = new Properties();
            // AccessKey 阿里云身份验证，在阿里云服务器管理控制台创建
            properties.put(PropertyKeyConst.AccessKey, accessKey);
            // SecretKey 阿里云身份验证，在阿里云服务器管理控制台创建
            properties.put(PropertyKeyConst.SecretKey, secretKey);
            properties.put(PropertyKeyConst.MessageModel, MessageModel.CLUSTERING);
            String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
            properties.put(PropertyKeyConst.InstanceName, uuid);
            properties.put(PropertyKeyConst.ConsumeThreadNums, consumeThreadNums);
            if (newVersion) {
                // 您在控制台创建的 Group ID
                properties.put(PropertyKeyConst.GROUP_ID, consumerId);
                // 设置 TCP 接入域名（此处以公共云生产环境为例）
                properties.put(PropertyKeyConst.NAMESRV_ADDR, nameServer);
            } else {
                // 您在控制台创建的 Consumer ID
                properties.put(PropertyKeyConst.ConsumerId, consumerId);
                // 设置 TCP 接入域名（此处以公共云生产环境为例）
                properties.put(PropertyKeyConst.ONSAddr,
                        "http://onsaddr-internet.aliyun.com/rocketmq/nsaddr4client-internet");
            }
            // 集群订阅方式 (默认)
            // properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.CLUSTERING);
            // 广播订阅方式
            if (handlerHolderList.get(0).isBroadcast()) {
                properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.BROADCASTING);
            }
            Consumer consumer = ONSFactory.createConsumer(properties);
            for (MessageHandlerHolder messageHandlerHolder : handlerHolderList) {
                consumer.subscribe(messageHandlerHolder.getTopic(), messageHandlerHolder.getTag(),
                        messageHandlerHolder.getMessageHandler());
            }
            consumer.start();
            log.info("ALI RocketMQ Consumer for ID {} Started", consumerId);
        }
    }
}
