package com.fs.framework.redis;

import com.alibaba.fastjson.JSON;
import com.fs.common.constant.FsConstants;
import com.fs.qw.service.IQwFriendWelcomeService;
import com.fs.qw.service.impl.QwFriendWelcomeServiceImpl;
import com.fs.qw.vo.QwFriendWelcomeDayPart;
import com.fs.qw.vo.QwFriendWelcomeVO;
import com.fs.qwApi.param.SendWelcomeMsgParam;
import com.fs.qwApi.service.QwApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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;
import java.util.List;

@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private IQwFriendWelcomeService qwFriendWelcomeService;
    @Autowired
    private QwApiService qwApiService;

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

    /**
     * 针对redis数据失效事件，进行数据处理
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        //过期的key
        String key = new String(message.getBody(),StandardCharsets.UTF_8);
        // 好友欢迎语过期判断
        if(key.contains(FsConstants.FRIEND_WELCOME_VIDEO_KEY)) {
            key = key.replace(FsConstants.FRIEND_WELCOME_VIDEO_KEY, "");
            Long id = Long.parseLong(key.split(":")[0]);
            QwFriendWelcomeVO vo = qwFriendWelcomeService.selectQwFriendWelcomeById(id);
            List<SendWelcomeMsgParam.Attachment> list = JSON.parseArray(vo.getAttachments(), SendWelcomeMsgParam.Attachment.class);
            list.forEach(e -> this.build(e, vo));
            if (vo.getIsDayparting().equals("1")) {
                List<QwFriendWelcomeDayPart.Schedule> schedules = JSON.parseArray(vo.getDaypartingItemlist(), QwFriendWelcomeDayPart.Schedule.class);
                schedules.forEach(schedule -> {
                    schedule.getAttachments().forEach(e -> this.build(e, vo));
                });
            }
        }
    }

    public void build(SendWelcomeMsgParam.Attachment e, QwFriendWelcomeVO vo){
        if(e.getMsgtype().equals("video")) {
            try {
                QwFriendWelcomeServiceImpl.uploadVideo(qwApiService, e, vo.getCorpId());
            } catch (Exception ex) {
                log.error("欢迎语视频重新上传失败", ex);
            }
        }
    }
}
