package com.xxfc.platform.im.biz;

import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.xxfc.platform.im.dto.MsgTypeEnum;
import com.xxfc.platform.im.dto.UpdateTypeEnum;
import com.xxfc.platform.im.entity.ImComment;
import com.xxfc.platform.im.entity.ImQuestion;
import com.xxfc.platform.im.mapper.ImCommentMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ImCommentBiz extends BaseBiz<ImCommentMapper, ImComment> {

    @Autowired
    ImQuestionBiz imQuestionBiz;
    @Autowired
    UserBiz userBiz;

    /**
     * 添加评论
     *
     * @param imComment
     * @return
     */
    public ObjectRestResponse add(ImComment imComment) {
        AppUserDTO appUserDTO = userBiz.getUserInfo();
        if (appUserDTO == null) {
            return ObjectRestResponse.createFailedResult(508, "token is null or invalid");
        }
        imComment.setUserId(Long.parseLong(appUserDTO.getImUserid() + ""));
        if (imComment == null || imComment.getQuestionId() == null) {
            return ObjectRestResponse.paramIsEmpty();
        }

        ImQuestion imQuestion = imQuestionBiz.selectById(imComment.getQuestionId());
        if (imQuestion == null) {
            return ObjectRestResponse.createDefaultFail();
        }
        mapper.insert(imComment);
        //修改评论数
        imQuestionBiz.update(imComment.getQuestionId(), MsgTypeEnum.comment, UpdateTypeEnum.add);
        return ObjectRestResponse.succ();
    }

    /**
     * 删除评论
     *
     * @param imComment
     * @return
     */
    public ObjectRestResponse deleteById(ImComment imComment) {
        AppUserDTO appUserDTO = userBiz.getUserInfo();
        if (appUserDTO == null) {
            return ObjectRestResponse.createFailedResult(508, "token is null or invalid");
        }
        if (imComment == null || imComment.getId() == null) {
            return ObjectRestResponse.paramIsEmpty();
        }
        ImComment oldValue = mapper.selectByPrimaryKey(imComment);
        if (oldValue == null) {
            return ObjectRestResponse.createDefaultFail();
        }
        oldValue.setIsDel(true);
        mapper.updateByPrimaryKeySelective(oldValue);
        imQuestionBiz.update(oldValue.getQuestionId(), MsgTypeEnum.comment, UpdateTypeEnum.subtraction);
        return ObjectRestResponse.succ();
    }

}
