package com.ruoyi.frequency.worklike.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.controller.req.WorksLikeReq;
import com.ruoyi.enums.message.InteractionMessageEnums;
import com.ruoyi.enums.user.UserEnums;
import com.ruoyi.frequency.order.entity.Order;
import com.ruoyi.frequency.worklike.entity.WorkLike;
import com.ruoyi.frequency.worklike.mapper.WorkLikeMapper;
import com.ruoyi.frequency.worklike.service.WorkLikeService;
import com.ruoyi.frequency.works.entity.Works;
import com.ruoyi.frequency.works.mapper.WorksMapper;
import com.ruoyi.frequency.works.service.WorksService;
import com.ruoyi.frequency.workscomment.entity.WorksComment;
import com.ruoyi.frequency.workscomment.service.WorksCommentService;
import com.ruoyi.frequency.workstep.entity.WorkStep;
import com.ruoyi.frequency.workstep.mapper.WorkStepMapper;
import com.ruoyi.message.frequency.interactionmessagerecord.service.InteractionMessageRecordService;
import com.ruoyi.response.ResponseData;
import com.ruoyi.utils.BusinessUtil;
import com.ruoyi.vo.BodyIdReq;
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-12
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class WorkLikeServiceImpl extends ServiceImpl<WorkLikeMapper, WorkLike> implements WorkLikeService {
    @Autowired
    private WorkLikeMapper workLikeMapper;

    /**
     * 查询作品点赞
     *
     * @param id 作品点赞主键
     * @return 作品点赞
     */
    @Override
    public WorkLike selectWorkLikeById(Long id) {
        return workLikeMapper.selectWorkLikeById(id);
    }

    /**
     * 查询作品点赞列表
     *
     * @param workLike 作品点赞
     * @return 作品点赞
     */
    @Override
    public List<WorkLike> selectWorkLikeList(WorkLike workLike) {
        return workLikeMapper.selectWorkLikeList(workLike);
    }

    /**
     * 新增作品点赞
     *
     * @param workLike 作品点赞
     * @return 结果
     */
    @Override
    public int insertWorkLike(WorkLike workLike) {
        workLike.setCreateTime(DateUtils.getNowDate());
        return workLikeMapper.insertWorkLike(workLike);
    }

    /**
     * 修改作品点赞
     *
     * @param workLike 作品点赞
     * @return 结果
     */
    @Override
    public int updateWorkLike(WorkLike workLike) {
        workLike.setUpdateTime(DateUtils.getNowDate());
        return workLikeMapper.updateWorkLike(workLike);
    }

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

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

    @Autowired
    private WorkStepMapper workStepMapper;


    @Autowired
    private WorksService worksService;

    @Autowired
    private BusinessUtil businessUtil;

    @Autowired
    private WorksCommentService worksCommentService;

    @Autowired
    private WorksMapper worksMapper;


    @Override
    public ResponseData worksLike(WorksLikeReq req, UserVo userVo) {

        WorkLike workLike = new WorkLike(req);

        //更新帖子点赞记录
        workLikeMapper.workLike(workLike, userVo);

        workLike = workLikeMapper.selectOne(new QueryWrapper<WorkLike>().lambda()
                .eq(WorkLike::getWorkId, req.getObjectId())
                .eq(WorkLike::getType, req.getType())
                .eq(WorkLike::getUserType, userVo.getUserType())
                .eq(WorkLike::getUserId, userVo.getUserId())
        );
        //是否点赞
        Boolean isLike = workLike.getDelFlag().equals(PublicCommon.启用);

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

            WorksComment worksComment = worksCommentService.getById(req.getObjectId());

            Works work = worksService.getById(worksComment.getWorksId());

            if (ObjectUtil.isEmpty(work.getCommentId()) && worksComment.getParentId() == 0L && worksComment.getLikeNum() >= likeNum) {
                worksService.lambdaUpdate().set(Works::getCommentId, worksComment.getId())
                        .eq(Works::getId, worksComment.getWorksId()).update();
            }
        } else {
            //只有作品有踩赞
            if (isLike) {
                WorkStep workStep = workStepMapper.selectOne(new QueryWrapper<WorkStep>().lambda()
                        .eq(WorkStep::getWorkId, req.getObjectId())
                        .eq(WorkStep::getUserType, userVo.getUserType())
                        .eq(WorkStep::getUserId, userVo.getUserId())
                );
                if (workStep != null && workStep.getDelFlag().equals(PublicCommon.启用)) {

                    workStep.setDelFlag(PublicCommon.禁用);
                    //更新作品踩记录
                    workStepMapper.workStep(workStep, userVo);
                    //修改踩数量
                    worksMapper.updateWorks(new Works().setId(req.getObjectId()).setLikeNum(-1));
                }
            }
        }

        //更新数量
        switch (req.getType()) {
            case 1:
                Works works = new Works().setId(req.getObjectId());
                works.setUpdateTime(DateUtils.getNowDate());
                works.setLikeNum(isLike ? 1 : -1);
                worksMapper.updateWorks(works);

                break;
            case 2:
                worksCommentService.updateWorksComment(new WorksComment().setId(req.getObjectId()).setLikeNum(isLike ? 1 : -1));
                break;
        }

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



    @Autowired
    private InteractionMessageRecordService interactionMessageRecordService;

    /**
     * 推送消息
     *
     * @param req
     * @param userVo
     * @param isPush
     */
    private void pushMessage(WorksLikeReq req, UserVo userVo, Boolean isPush) {
        if (!isPush) {
            return;
        }

        InteractionMessageEnums enums = ObjectUtil.equal(1, req.getType()) ? InteractionMessageEnums.LIKE_WORKS : InteractionMessageEnums.LIKE_WORKS_COMMENT;

        //作品id
        Long worksId = null;

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

        switch (req.getType()) {
            case 1:
                //作品点赞
                worksId = req.getObjectId();
                Works works = worksService.getById(worksId);
                sendUserVo = new UserVo(works.getUserType(), works.getStoreId());
                break;
            case 2:
                //评论点赞
                WorksComment worksComment = worksCommentService.getById(req.getObjectId());
                worksId = worksComment.getWorksId();
                sendUserVo = new UserVo(worksComment.getUserType(), worksComment.getUserId());
                break;
        }

        //互动消息
        interactionMessageRecordService.addInteractionMessage(userVo, sendUserVo, PublicCommon.InteractionMessage.点赞, worksId, isPush, enums);
    }

}
