package org.jeecg.modules.adweb.listener;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.adweb.common.jedis.ObjectUtil;
import org.jeecg.modules.adweb.common.util.JedisUtil;
import org.jeecg.modules.adweb.enquiry.constant.EnquiryConstants;
import org.jeecg.modules.adweb.enquiry.service.IEnquiryEmailMessageService;

import redis.clients.jedis.JedisPubSub;

@Setter
@Slf4j
public class EnquiryEmailSenderListener extends JedisPubSub {

    public static byte[] redisKey = EnquiryConstants.ENQUIRY_EMAIL.getBytes();

    private IEnquiryEmailMessageService enquiryEmailMessageService;

    // 取得订阅的消息后的处理
    @Override
    public void onMessage(String channel, String message) {
        log.info("redis订阅channel是:{}, message是:{}", channel, message);
        try {
            while (true) {
                byte[] bytes = JedisUtil.rpop(redisKey);
                if (bytes != null) {
                    Long enquiryId = (Long) ObjectUtil.bytes2Object(bytes);
                    enquiryEmailMessageService.sendEnquiryEmail(enquiryId);
                } else {
                    break;
                }
            }
        } catch (Exception e) {
            log.error("通过redis订阅服务发送邮件失败", e);
        }
    }

    // 初始化订阅时候的处理
    public void onSubscribe(String channel, int subscribedChannels) {
        // log.info(channel + "=" + subscribedChannels);
    }

    // 取消订阅时候的处理
    public void onUnsubscribe(String channel, int subscribedChannels) {
        // log.info(channel + "=" + subscribedChannels);
    }

    // 初始化按表达式的方式订阅时候的处理
    public void onPSubscribe(String pattern, int subscribedChannels) {
        // log.info(pattern + "=" + subscribedChannels);
    }

    // 取消按表达式的方式订阅时候的处理
    public void onPUnsubscribe(String pattern, int subscribedChannels) {
        // log.info(pattern + "=" + subscribedChannels);
    }

    // 取得按表达式的方式订阅的消息后的处理
    public void onPMessage(String pattern, String channel, String message) {}
}
