package com.neusoft.smart.pos.mq.aliyunRocketMq;

import java.util.List;
import java.util.Properties;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Consumer;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.neusoft.smart.pos.mq.MQConfig;

import lombok.extern.slf4j.Slf4j;

@Slf4j
//@Service
//@Profile(MQConfig.Impl.ALIYUN_ROCKET_MQ)
public abstract class AliyunRocketMqConsumer {

    @Value("${spring.aliyunRocketmq.accessKeyId}")
    private String accessKeyId;
    
    @Value("${spring.aliyunRocketmq.accessKeySecret}")
    private String accessKeySecret;
    
    @Value("${spring.aliyunRocketmq.namesrvAddr}")
    private String namesrvAddr;
	
    @PostConstruct
    public void init() {
        for (EnumMsgTopic topic: EnumMsgTopic.values()) {
        	Properties properties = new Properties();
            // 您在控制台创建的 Group ID
            properties.put(PropertyKeyConst.GROUP_ID, topic.getGroupId());
            // AccessKey 阿里云身份验证，在阿里云服务器管理控制台创建
            properties.put(PropertyKeyConst.AccessKey, accessKeyId);
            // SecretKey 阿里云身份验证，在阿里云服务器管理控制台创建
            properties.put(PropertyKeyConst.SecretKey, accessKeySecret);
            // 设置 TCP 接入域名，到控制台的实例基本信息中查看
            properties.put(PropertyKeyConst.NAMESRV_ADDR,namesrvAddr);
            // 集群订阅方式（默认）
            // properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.CLUSTERING);
            // 广播订阅方式
            // properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.BROADCASTING);       	
        	Consumer consumer = ONSFactory.createConsumer(properties);
        	
        	List<EnumMsgTopicTags> topicTags = EnumMsgTopicTags.getTagsByTopic(topic.getTopic());
        	if (null != topicTags) {
        		for (EnumMsgTopicTags emtt:topicTags) {
		        	consumer.subscribe(topic.getTopic(), emtt.getTags(), new MessageListener() { //订阅Tag
		                public Action consume(Message message, ConsumeContext context) {
		                	try {
			                    System.out.println("Receive: " + message);
			                    doMessage(topic.getTopic(),emtt.getTags(),new String(message.getBody()));
			                    return Action.CommitMessage;
		                	}catch(Exception e) {
		                		log.error("AliyunRocketMqConsumer error:",e);
		                		return Action.ReconsumeLater;
		                	}
		                }
		            });
		        	consumer.start();
		        	log.info(" aliyunrocketMq consumer start success! "+JSON.toJSONString(consumer));
        		}
        	}
        	
//        	consumer.subscribe(topic.getTopic(), "*", new MessageListener() { //订阅多个 Tag
//                public Action consume(Message message, ConsumeContext context) {
//                	try {
//	                    System.out.println("Receive: " + message);
//	                    doMessage(topic.getTopic(),new String(message.getBody()));
//	                    return Action.CommitMessage;
//                	}catch(Exception e) {
//                		log.error("AliyunRocketMqConsumer error:",e);
//                		return Action.ReconsumeLater;
//                	}
//                }
//            });
//        	consumer.start();
//        	log.info(" aliyunrocketMq consumer start success! "+JSON.toJSONString(consumer));
        }
       
    }
    
    protected abstract void doMessage(String topic,String tag,String msg);
    
}
