package com.ruoyi.post.frequency.postlike.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.code.DictConstant;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.enums.message.InteractionMessageEnums;
import com.ruoyi.message.frequency.interactionmessagerecord.service.InteractionMessageRecordService;
import com.ruoyi.post.controller.req.PostLikeReq;
import com.ruoyi.post.frequency.post.entity.Post;
import com.ruoyi.post.frequency.post.service.PostService;
import com.ruoyi.post.frequency.postcomment.entity.PostComment;
import com.ruoyi.post.frequency.postcomment.service.PostCommentService;
import com.ruoyi.post.frequency.postlike.entity.PostLike;
import com.ruoyi.post.frequency.postlike.mapper.PostLikeMapper;
import com.ruoyi.post.frequency.postlike.service.PostLikeService;
import com.ruoyi.response.ResponseData;
import com.ruoyi.utils.BusinessUtil;
import com.ruoyi.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 帖子点赞Service业务层处理
 *
 * @author liwenlong
 * @date 2023-10-09
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class PostLikeServiceImpl extends ServiceImpl<PostLikeMapper, PostLike> implements PostLikeService {
    @Autowired
    private PostLikeMapper postLikeMapper;

    /**
     * 查询帖子点赞
     *
     * @param id 帖子点赞主键
     * @return 帖子点赞
     */
    @Override
    public PostLike selectPostLikeById(Long id) {
        return postLikeMapper.selectPostLikeById(id);
    }

    /**
     * 查询帖子点赞列表
     *
     * @param postLike 帖子点赞
     * @return 帖子点赞
     */
    @Override
    public List<PostLike> selectPostLikeList(PostLike postLike) {
        return postLikeMapper.selectPostLikeList(postLike);
    }

    /**
     * 新增帖子点赞
     *
     * @param postLike 帖子点赞
     * @return 结果
     */
    @Override
    public int insertPostLike(PostLike postLike) {
        postLike.setCreateTime(DateUtils.getNowDate());
        return postLikeMapper.insertPostLike(postLike);
    }

    /**
     * 修改帖子点赞
     *
     * @param postLike 帖子点赞
     * @return 结果
     */
    @Override
    public int updatePostLike(PostLike postLike) {
        postLike.setUpdateTime(DateUtils.getNowDate());
        return postLikeMapper.updatePostLike(postLike);
    }

    /**
     * 批量删除帖子点赞
     *
     * @param ids 需要删除的帖子点赞主键
     * @return 结果
     */
    @Override
    public int deletePostLikeByIds(Long[] ids) {
        this.lambdaUpdate().set(PostLike::getDelFlag, PublicCommon.删除).in(PostLike::getId, ids).update();
        return ids.length;
    }

    /**
     * 删除帖子点赞信息
     *
     * @param id 帖子点赞主键
     * @return 结果
     */
    @Override
    public int deletePostLikeById(Long id) {
        this.lambdaUpdate().set(PostLike::getDelFlag, PublicCommon.删除).eq(PostLike::getId, id).update();
        return 1;
    }

    @Autowired
    private PostService postService;

    @Autowired
    private PostCommentService postCommentService;

    @Autowired
    private BusinessUtil businessUtil;

    @Override
    public ResponseData postLike(PostLikeReq req, UserVo userVo) {

        PostLike postLike = new PostLike(req.getType(), req.getObjectId());

        //更新帖子点赞记录
        postLikeMapper.postLike(postLike, userVo);

        postLike = postLikeMapper.selectOne(new QueryWrapper<PostLike>().lambda()
                .eq(PostLike::getObjectId, req.getObjectId())
                .eq(PostLike::getType, req.getType())
                .eq(PostLike::getUserType, userVo.getUserType())
                .eq(PostLike::getUserId, userVo.getUserId()));

        //是否点赞
        Boolean isLike = postLike.getDelFlag().equals(PublicCommon.启用);

        //1 帖子 2帖子评论
        updatePostLikeNum(req.getType(), req.getObjectId(), isLike);

        //精彩评论 1 帖子 2 帖子评论
        if (isLike && req.getType() == 2) {
            //点赞量基础量（超过）
            Integer likeNum = Integer.valueOf(businessUtil.getDict(DictConstant.点赞好评基础量).getDictValue());

            PostComment postComment = postCommentService.getById(req.getObjectId());

            Post post = postService.getById(postComment.getPostId());

            if (ObjectUtil.isEmpty(post.getCommentId()) && postComment.getParentId() == 0L && postComment.getLikeNum() >= likeNum) {
                postService.lambdaUpdate().set(Post::getCommentId, postComment.getId())
                        .eq(Post::getId, postComment.getPostId()).update();
            }
        }

        //推送消息
        pushMessage(req, userVo, isLike);
        return ResponseData.success();
    }


    /**
     * 推送消息
     *
     * @param req
     * @param userVo
     * @param isLike
     */
    private void pushMessage(PostLikeReq req, UserVo userVo, Boolean isLike) {

        InteractionMessageEnums enums = ObjectUtil.equal(1, req.getType()) ? InteractionMessageEnums.LIKE_POST : InteractionMessageEnums.LIKE_POST_COMMENT;

        //帖子id
        Long postId = null;

        //接收消息用户
        UserVo sendUserVo = null;

        switch (req.getType()) {
            case 1:
                //帖子点赞
                postId = req.getObjectId();
                Post post = postService.getById(postId);
                sendUserVo = new UserVo(post.getUserType(), post.getUserId());
                break;
            case 2:
                //评论点赞
                PostComment postComment = postCommentService.getById(req.getObjectId());
                postId = postComment.getPostId();
                sendUserVo = new UserVo(postComment.getUserType(), postComment.getUserId());
                break;
        }

        //互动消息
        interactionMessageRecordService.addInteractionMessage(userVo, sendUserVo, PublicCommon.InteractionMessage.点赞, postId, isLike, enums);

    }

    @Autowired
    private InteractionMessageRecordService interactionMessageRecordService;


    /**
     * 更新帖子点赞数据
     *
     * @param type     1 帖子 2帖子评论
     * @param objectId 帖子id/评论id
     * @param isLike   是否点赞
     */
    private void updatePostLikeNum(Integer type, Long objectId, Boolean isLike) {

        //点赞 +1 ，取消点赞 -1
        Integer num = isLike ? 1 : -1;

        switch (type) {
            case 1:
                postService.updatePostLikeNum(new Post().setId(objectId), num);
                break;
            case 2:
                postCommentService.updatePostComment(new PostComment().setId(objectId).setLikeNum(num));
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + type);
        }
    }
}
