package com.sonic.frog.event.outer.handler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sonic.common.event.Event;
import com.sonic.common.event.EventConsumer;
import com.sonic.common.event.EventHandler;
import com.sonic.frog.domain.entity.AiUser;
import com.sonic.frog.event.outer.EventType;
import com.sonic.frog.event.outer.payload.AiChatPayload;
import com.sonic.frog.service.AiUserService;
import com.sonic.frog.utils.RedisKeyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * AI聊天同步业务服务
 * @author code
 */
@Slf4j
@Component
public class AiChatNotifyUpdateLastChatTimeHandler implements EventHandler, InitializingBean {

    @Autowired
    private EventConsumer eventConsumer;
    @Autowired
    private AiUserService aiUserService;
    @Autowired
    private RedisKeyUtils redisKeyUtils;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void onEvent(Event event) {
        //处理业务逻辑，更新AI的最后聊天时间
        AiChatPayload payload = event.normalizedData(AiChatPayload.class);
        //自己和自己聊不更新最后聊天时间
        boolean isExist = stringRedisTemplate.hasKey(redisKeyUtils.creatorAiUserRelationKey(payload.getFromUserId(), payload.getToUserId()));
        if(isExist) {
            return;
        }
        //查询AI
        AiUser aiUser = aiUserService.getOne(Wrappers.<AiUser>lambdaQuery().select(AiUser::getId, AiUser::getAiId, AiUser::getUserId).eq(AiUser::getAiId, payload.getToUserId()));
        if(aiUser == null) {
            return;
        }
        //自己和自己聊不更新最后聊天时间
        if(aiUser.getUserId().equals(payload.getFromUserId())) {
            stringRedisTemplate.opsForValue().set(redisKeyUtils.creatorAiUserRelationKey(payload.getFromUserId(), payload.getToUserId()), "1", 24 * 60 * 60, TimeUnit.SECONDS);
            return;
        }
        //已经更新了则不再继续更新
        boolean isUpdateExist = stringRedisTemplate.hasKey(redisKeyUtils.updateLastChatTimeLimitKey(payload.getToUserId()));
        if(isUpdateExist) {
            return;
        }
        //更新数据
        aiUserService.update(Wrappers.<AiUser>lambdaUpdate().set(AiUser::getLastChatTime, LocalDateTime.now()).eq(AiUser::getId, aiUser.getId()));
        //写入redis
        stringRedisTemplate.opsForValue().set(redisKeyUtils.updateLastChatTimeLimitKey(payload.getToUserId()), "1", 60, TimeUnit.SECONDS);
    }

    @Override
    public void afterPropertiesSet() {
        eventConsumer.registerHandler(EventType.AI_CHAT_TO_FROG.getEventCode(), this);
    }
}
