package cn.com.poc.common.listener;

import cn.com.poc.thirdparty.resource.demand.ai.function.notification_reminder.NotificationReminderConstant;
import cn.com.yict.framemax.frame.entity.EmailSenderEntity;
import cn.com.yict.framemax.frame.service.EmailSenderService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Helen
 * @date 2021/11/12 14:46
 */
//@Component
public class RedisKeyExpiredListener extends KeyExpirationEventMessageListener {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public RedisKeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Resource
    private EmailSenderService emailSenderService;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取过期的key， 格式：CALLBACK_KEY-TYPE-{json}
        String expiredKey = message.toString();
        //前缀校验
        if (expiredKey.contains(NotificationReminderConstant.REDIS_KEY)) {
            int i = expiredKey.indexOf(":");
            String json = expiredKey.substring(i + 1);
            if (StringUtils.isNoneBlank(json)) {
                JSONObject jsonObject = JSONObject.parseObject(json);
                String email = jsonObject.getString("email");
                String content = jsonObject.getString("content");
                EmailSenderEntity entity = new EmailSenderEntity();
                List<String> list = new LinkedList<>();
                list.add(email);
                entity.setTo(list);
                entity.setBody(content);
                entity.setSubject("Agent Application Notification");
                try {
                    emailSenderService.sendMail(entity, null);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }

}
