package com.sonic.pigeon.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.ImmutableMap;
import com.sonic.pigeon.dao.AiChatFeedbackDao;
import com.sonic.pigeon.domain.entity.AiChatFeedback;
import com.sonic.pigeon.domain.input.FeedbackInput;
import com.sonic.pigeon.service.AiChatFeedbackService;
import com.sonic.pigeon.service.ImMessageService;
import com.sonic.pigeon.utils.LimitUtils;
import com.sonic.pigeon.utils.RedisKeyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * AI聊天反馈
 */

@Slf4j
@Service
public class AiChatFeedbackServiceImpl extends ServiceImpl<AiChatFeedbackDao, AiChatFeedback> implements AiChatFeedbackService {

    @Autowired
    private RedisKeyUtils redisKeyUtils;
    @Autowired
    private LimitUtils limitUtils;
    @Autowired
    private ImMessageService imMessageService;

    @Override
    public void feedback(Long userId, FeedbackInput input) {
        //上锁、限流
        boolean bl = limitUtils.defaultLimitCheckByKey(redisKeyUtils.feedbackLimitKey(userId), 200, 24 * 60 * 60);
        if(bl) {
            //限流了，则不再进行处理
            return;
        }
        try {
            AiChatFeedback feedback = getOne(Wrappers.<AiChatFeedback>lambdaQuery().eq(AiChatFeedback::getMessageId, input.getMessageId()));
            if(feedback == null) {
                //保存数据
                feedback = new AiChatFeedback();
                feedback.setUserId(userId);
                feedback.setAiId(input.getAiId());
                feedback.setContent(input.getContent());
                feedback.setMessageId(input.getMessageId());
                feedback.setOptType(input.getOptType());
                feedback.setCreateTime(LocalDateTime.now());
                save(feedback);
            } else {
                //校验操作用户是否匹配，不匹配直接快速返回
                if(!feedback.getUserId().equals(userId)) {
                    return;
                }
                //更新状态
                update(Wrappers.<AiChatFeedback>lambdaUpdate().set(AiChatFeedback::getOptType, input.getOptType()).eq(AiChatFeedback::getId, feedback.getId()));
            }
            if(input.getMessageId().startsWith("prologue_")) {
                return;
            }
            //更新im消息
            imMessageService.updateAiSendMessage(input.getAiId(), userId, Long.valueOf(input.getMessageId()), ImmutableMap.of("optType", input.getOptType()));
        } catch (Exception e) {
            log.error("===> feedback save error : ", e);
        }
    }

}
