package com.fs.app.redis;

import com.fs.chat.domain.ChatSession;
import com.fs.chat.service.IChatSessionService;
import com.fs.common.constant.FsConstants;
import com.fs.common.utils.spring.SpringUtils;
import com.fs.event.TemplateBean;
import com.fs.event.TemplateEvent;
import com.fs.event.TemplateListenEnum;
import com.fs.his.domain.FsInquiryOrder;
import com.fs.his.domain.FsPackageOrder;
import com.fs.his.param.FsInquiryOrderCancelParam;
import com.fs.his.service.IFsInquiryOrderLogsService;
import com.fs.his.service.IFsInquiryOrderService;
import com.fs.his.service.IFsPackageOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
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 java.nio.charset.StandardCharsets;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    private static final Logger log = LoggerFactory.getLogger(RedisKeyExpirationListener.class);

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

    @Autowired
    IFsInquiryOrderLogsService fsInquiryOrderLogsService;
    @Autowired
    private ApplicationEventPublisher publisher;
    /**
     * 针对redis数据失效事件，进行数据处理
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String channel = new String(message.getChannel(), StandardCharsets.UTF_8);
        //过期的key
        String key = new String(message.getBody(),StandardCharsets.UTF_8);
        if(key.contains(FsConstants.REDIS_CHAT_SESSION)) {
            key = key.replace(FsConstants.REDIS_CHAT_SESSION, "");
            log.info("rediskey过期：key={}",key);
            String[] ids = key.split(":");
            IChatSessionService sessionService= SpringUtils.getBean(IChatSessionService.class);
            ChatSession session=sessionService.selectChatSessionByIds(ids[0],ids[1]);
            if(session!=null){
                session.setStatus(2);
                sessionService.updateChatSession(session);
            }

        }

    }
}
