package com.hssx.pcbms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hssx.pcbms.entity.Idea;
import com.hssx.pcbms.entity.IdeaComment;
import com.hssx.pcbms.entity.User;
import com.hssx.pcbms.mapper.IdeaCommentMapper;
import com.hssx.pcbms.mapper.IdeaMapper;
import com.hssx.pcbms.mapper.UserMapper;
import com.hssx.pcbms.service.IdeaCommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hssx.pcbms.util.HttpRespMsg;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;

/**
 * @author 吴涛涛
 * @since 2019-11-02
 */
@Service
public class IdeaCommentServiceImpl extends ServiceImpl<IdeaCommentMapper, IdeaComment> implements IdeaCommentService {

    @Resource
    private IdeaCommentMapper ideaCommentMapper;
    @Resource
    private IdeaMapper ideaMapper;
    @Resource
    private UserMapper userMapper;

    @Override
    public HttpRespMsg addOrUpdate(IdeaComment ideaComment,Double score,Integer scoreId) {
        HttpRespMsg msg = new HttpRespMsg();
        if (null == ideaComment.getId()) {
            //添加评论
            User user = userMapper.selectById(ideaComment.getResponderId());
            ideaComment.setResponder(user.getName());
            ideaCommentMapper.insert(ideaComment);
            Idea idea = new Idea();
            idea.setScore(score);
            idea.setIsEvaluated(1);
            idea.setScoreId(scoreId);
            ideaMapper.update(idea,new QueryWrapper<Idea>().eq("id",ideaComment.getIdeaId()));
        } else {
            //修改评论
            Idea idea = ideaMapper.selectOne(new QueryWrapper<Idea>().eq("id", ideaComment.getIdeaId()));
            if (idea != null) {
                ideaCommentMapper.updateById(ideaComment);
                if(null != score){
                    idea.setScore(score);
                    ideaMapper.updateById(idea);
                }
            } else {
                msg.setError("该建议数据不存在。");
                return msg;
            }
        }
        return msg;
    }

    @Override
    public HttpRespMsg del(IdeaComment ideaComment) {
        HttpRespMsg msg = new HttpRespMsg();
        IdeaComment oldIdeaComment = ideaCommentMapper.selectById(ideaComment.getId());
        if (oldIdeaComment != null) {
            Idea idea = ideaMapper.selectOne(new QueryWrapper<Idea>().eq("id", oldIdeaComment.getIdeaId()));
            idea.setScore(0.0);
            idea.setIsEvaluated(0);
            ideaMapper.updateById(idea);
            ideaCommentMapper.deleteById(ideaComment.getId());
        }else{
            msg.setError("想要删除的回复数据不存在。");
        }
        return msg;
    }
}
