package org.dromara.work.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.work.domain.TpPicture;
import org.dromara.work.domain.bo.TpMessageBo;
import org.dromara.work.domain.vo.TpDynamicsNumVo;
import org.dromara.work.mapper.TpPictureMapper;
import org.dromara.work.service.ITpMessageService;
import org.springframework.stereotype.Service;
import org.dromara.work.domain.bo.TpCommentsBo;
import org.dromara.work.domain.vo.TpCommentsVo;
import org.dromara.work.domain.TpComments;
import org.dromara.work.mapper.TpCommentsMapper;
import org.dromara.work.service.ITpCommentsService;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 评论Service业务层处理
 *
 * @author Maosw
 * @date 2025-04-12
 */
@RequiredArgsConstructor
@Service
public class TpCommentsServiceImpl implements ITpCommentsService {

    private final TpCommentsMapper baseMapper;

    private final TpPictureMapper pictureMapper;

    private final SysUserMapper userMapper;

    private final ITpMessageService tpMessageService;

    /**
     * 查询评论
     *
     * @param id 主键
     * @return 评论
     */
    @Override
    public TpCommentsVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }


    /**
     * 查询符合条件的评论列表
     *
     * @param bo 查询条件
     * @return 评论列表
     */
    @Override
    public List<TpCommentsVo> queryList(TpCommentsBo bo) {
        LambdaQueryWrapper<TpComments> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询评论分页列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页条件
     * @return 评论分页列表
     */
    @Override
    public TableDataInfo<TpCommentsVo> queryPageList(TpCommentsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TpComments> lqw = buildQueryWrapper(bo);
        Page<TpCommentsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询评论分页列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页条件
     * @return 评论分页列表
     */
    @Override
    public IPage<TpCommentsVo> selectPageList(TpCommentsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TpComments> lqw = buildQueryWrapper(bo);
        if(bo.getOrderBy() == 1){
            lqw.orderByDesc(TpComments::getCreateTime);
        }else if(bo.getOrderBy() == 2){
            lqw.orderByAsc(TpComments::getCreateTime);
        }
        Page<TpCommentsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        //循环赋值用户对象
        for (TpCommentsVo tpCommentsVo : result.getRecords()) {
            SysUserVo sysUser = userMapper.selectVoById(tpCommentsVo.getUserId());
            tpCommentsVo.setUser(sysUser);
            if(tpCommentsVo.getToUserId() != null){
                SysUserVo sysUser1 = userMapper.selectVoById(tpCommentsVo.getToUserId());
                tpCommentsVo.setToUser(sysUser1);
            }
        }
        return result;
    }

    private LambdaQueryWrapper<TpComments> buildQueryWrapper(TpCommentsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TpComments> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getPictureId() != null, TpComments::getPictureId, bo.getPictureId());
        lqw.eq(bo.getUserId() != null, TpComments::getUserId, bo.getUserId());
        lqw.eq(bo.getParentId() != null, TpComments::getParentId, bo.getParentId());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), TpComments::getContent, bo.getContent());
        lqw.eq(bo.getNum() != null, TpComments::getNum, bo.getNum());
        lqw.eq(bo.getType() != null, TpComments::getType, bo.getType());
        lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
            TpComments::getCreateTime ,params.get("beginCreateTime"), params.get("endCreateTime"));
        return lqw;
    }

    /**
     * 新增评论
     *
     * @param bo 评论
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(TpCommentsBo bo) {
        TpMessageBo tpMessageBo = new TpMessageBo();
        TpPicture tpPicture = pictureMapper.selectById(bo.getPictureId());
        //作品/动态评论数量+1
        pictureMapper.update(null, Wrappers.<TpPicture>lambdaUpdate()
            .setIncrBy(TpPicture::getComNum, 1)
            .eq(TpPicture::getId, bo.getPictureId()));

        if(bo.getParentId() != 0){
            //父评论数量+1
            baseMapper.update(null, Wrappers.<TpComments>lambdaUpdate()
                .setIncrBy(TpComments::getSubset, 1)
                .eq(TpComments::getId, bo.getParentId()));
        }
        TpComments add = MapstructUtils.convert(bo, TpComments.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            // 发送消息
            if(bo.getType() == 1){
                tpMessageBo.setContent("你的作品："+ tpPicture.getTitle() + "，获得了评论");
            }else if(bo.getType() == 2){
                tpMessageBo.setContent("你的动态："+ tpPicture.getTitle() + "，获得了评论");
            }
            tpMessageBo.setUserId(bo.getUserId());
            tpMessageBo.setToUserId(tpPicture.getUserId());
            tpMessageBo.setType(2);
            tpMessageBo.setPictureId(bo.getPictureId());
            tpMessageBo.setCreateTime(new Date());
            tpMessageService.insertByBo(tpMessageBo);
        }
        return flag;
    }

    /**
     * 修改评论
     *
     * @param bo 评论
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(TpCommentsBo bo) {
        TpComments update = MapstructUtils.convert(bo, TpComments.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TpComments entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除评论信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 查询评论数量
     *
     * @param pictureId 作品ID
     * @param type      类型  1-作品  2-动态
     * @return 评论数量
     */
    @Override
    public Long queryListCounr(Long pictureId, int type) {
        return baseMapper.selectCount(new LambdaQueryWrapper<TpComments>().eq(TpComments::getPictureId, pictureId).eq(TpComments::getType, type));
    }
}
