package com.sonic.frog.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sonic.frog.dao.LikedDao;
import com.sonic.frog.domain.entity.AiUser;
import com.sonic.frog.domain.entity.Liked;
import com.sonic.frog.domain.input.AiUserLikeOrCancelInput;
import com.sonic.frog.enums.ToastResultCode;
import com.sonic.frog.event.inner.payload.AiUserStatPayload;
import com.sonic.frog.service.AiUserSearchService;
import com.sonic.frog.service.CommonSendMqService;
import com.sonic.frog.service.LikedService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 点赞业务实现类
 */
@Service
@Slf4j
public class LikedServiceImpl extends ServiceImpl<LikedDao, Liked> implements LikedService {
    @Autowired
    private AiUserSearchService aiUserSearchService;
    @Autowired
    private LikedDao likedDao;
    @Autowired
    private CommonSendMqService commonSendMqService;

    @Override
    public void aiUserLikeOrCancel(Long userId, AiUserLikeOrCancelInput input) {
        //获取ai用户信息
        AiUser aiUser = aiUserSearchService.getAiUserByAiId(input.getAiId());
        ToastResultCode.AI_USER_NOT_EXIST.check(aiUser == null);
        //查询点赞信息
        Liked liked = likedDao.selectOne(Wrappers.<Liked>lambdaQuery()
                .eq(Liked::getBizId, input.getAiId())
                .eq(Liked::getBizType, Liked.BizType.AI)
                .eq(Liked::getLikedUserId, userId));
        //如果数据库状态与传过来的状态一致，不处理
        if (liked != null && liked.getLikedStatus() == input.getLikedStatus()) {
            return;
        }
        //点赞或取消点赞
        likedDao.likeOrCancel(Liked.builder()
                .bizId(input.getAiId())
                .bizType(Liked.BizType.AI)
                .aiId(input.getAiId())
                .likedUserId(userId)
                .likedStatus(input.getLikedStatus()).build());
        //如果是喜欢或者不喜欢的AI的话，需要发送MQ消息，异步计算喜欢总数
        Liked.LikedStatus likedStatus = input.getLikedStatus();
        boolean lk = likedStatus == Liked.LikedStatus.LIKED;
        commonSendMqService.aiUserStatMq(input.getAiId(), lk ? AiUserStatPayload.Type.LIKED : AiUserStatPayload.Type.CANCEL_LIKED, null);
    }

    @Override
    public Boolean isLiked(Long userId, Long bizId, Liked.BizType bizType) {
        int count = count(Wrappers.<Liked>lambdaQuery()
                .eq(Liked::getLikedUserId, userId)
                .eq(Liked::getBizId, bizId)
                .eq(Liked::getBizType, bizType)
                .eq(Liked::getLikedStatus, Liked.LikedStatus.LIKED)
        );
        return count > 0;
    }
}