package org.dromara.work.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.work.domain.TpPicture;
import org.dromara.work.domain.bo.TpMessageBo;
import org.dromara.work.domain.vo.TpPictureVo;
import org.dromara.work.mapper.TpPictureMapper;
import org.dromara.work.service.ITpMessageService;
import org.springframework.stereotype.Service;
import org.dromara.work.domain.bo.TpDynamicsNumBo;
import org.dromara.work.domain.vo.TpDynamicsNumVo;
import org.dromara.work.domain.TpDynamicsNum;
import org.dromara.work.mapper.TpDynamicsNumMapper;
import org.dromara.work.service.ITpDynamicsNumService;

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

/**
 * 动态点赞收藏Service业务层处理
 *
 * @author Maosw
 * @date 2025-04-11
 */
@RequiredArgsConstructor
@Service
public class TpDynamicsNumServiceImpl implements ITpDynamicsNumService {

    private final TpDynamicsNumMapper baseMapper;

    private final TpPictureMapper pictureMapper;

    private final ITpMessageService tpMessageService;

    /**
     * 查询动态点赞收藏
     *
     * @param id 主键
     * @return 动态点赞收藏
     */
    @Override
    public TpDynamicsNumVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询动态点赞收藏列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 动态点赞收藏分页列表
     */
    @Override
    public TableDataInfo<TpDynamicsNumVo> queryPageList(TpDynamicsNumBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TpDynamicsNum> lqw = buildQueryWrapper(bo);
        Page<TpDynamicsNumVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        List<Long> pictureIds = result.getRecords().stream().map(TpDynamicsNumVo::getPictureId).toList();
        List<TpPictureVo> dynamicsList = pictureMapper.selectVoList(new LambdaQueryWrapper<TpPicture>().in(CollUtil.isNotEmpty(pictureIds), TpPicture::getId, pictureIds).eq(TpPicture::getType, 3));
        for (TpDynamicsNumVo tpDynamicsNumVo : result.getRecords()) {
            for (TpPictureVo tpPictureVo : dynamicsList) {
                if (tpDynamicsNumVo.getPictureId().equals(tpPictureVo.getId())) {
                    tpDynamicsNumVo.setTpPictureVo(tpPictureVo);
                    break;
                }
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 分页查询点赞收藏列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 点赞收藏分页列表
     */
    @Override
    public IPage<TpDynamicsNumVo> selectPageList(TpDynamicsNumBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TpDynamicsNum> lqw = buildQueryWrapper(bo);
        Page<TpDynamicsNumVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        List<Long> pictureIds = result.getRecords().stream().map(TpDynamicsNumVo::getPictureId).toList();
        List<TpPictureVo> dynamicsList = pictureMapper.selectVoList(new LambdaQueryWrapper<TpPicture>().in(CollUtil.isNotEmpty(pictureIds), TpPicture::getId, pictureIds).eq(TpPicture::getType, 3));
        for (TpDynamicsNumVo tpDynamicsNumVo : result.getRecords()) {
            for (TpPictureVo tpPictureVo : dynamicsList) {
                if (tpDynamicsNumVo.getPictureId().equals(tpPictureVo.getId())) {
                    tpDynamicsNumVo.setTpPictureVo(tpPictureVo);
                    break;
                }
            }
        }
        return result;
    }

    /**
     * 查询符合条件的动态点赞收藏列表
     *
     * @param bo 查询条件
     * @return 动态点赞收藏列表
     */
    @Override
    public List<TpDynamicsNumVo> queryList(TpDynamicsNumBo bo) {
        LambdaQueryWrapper<TpDynamicsNum> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TpDynamicsNum> buildQueryWrapper(TpDynamicsNumBo bo) {
        LambdaQueryWrapper<TpDynamicsNum> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(TpDynamicsNum::getId);
        lqw.eq(bo.getUserId() != null, TpDynamicsNum::getUserId, bo.getUserId());
        lqw.eq(bo.getPictureId() != null, TpDynamicsNum::getPictureId, bo.getPictureId());
        lqw.eq(bo.getType() != null, TpDynamicsNum::getType, bo.getType());
        return lqw;
    }

    /**
     * 新增动态点赞收藏
     *
     * @param bo 动态点赞收藏
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(TpDynamicsNumBo bo) {
        TpMessageBo tpMessageBo = new TpMessageBo();
        TpPicture tpPicture = pictureMapper.selectById(bo.getPictureId());
        if (bo.getType() == 1) {
            pictureMapper.update(null, Wrappers.<TpPicture>lambdaUpdate()
                .setIncrBy(TpPicture::getLikeNum, 1)
                .eq(TpPicture::getId, bo.getPictureId()));

            tpMessageBo.setContent("你的动态："+ tpPicture.getTitle() + "，获得了点赞");
        } else if (bo.getType() == 2) {
            pictureMapper.update(null, Wrappers.<TpPicture>lambdaUpdate()
                .setIncrBy(TpPicture::getCollecNum, 1)
                .eq(TpPicture::getId, bo.getPictureId()));

            tpMessageBo.setContent("你的动态："+ tpPicture.getTitle() + "，获得了收藏");
        }

        TpDynamicsNum add = MapstructUtils.convert(bo, TpDynamicsNum.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            // 发送消息
            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(TpDynamicsNumBo bo) {
        TpDynamicsNum update = MapstructUtils.convert(bo, TpDynamicsNum.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TpDynamicsNum 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 bo 动态点赞收藏
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteTpDynamicsNum(TpDynamicsNumBo bo) {
        return baseMapper.delete(new LambdaQueryWrapper<TpDynamicsNum>().eq(TpDynamicsNum::getUserId, bo.getUserId()).eq(TpDynamicsNum::getPictureId, bo.getPictureId()).eq(TpDynamicsNum::getType, bo.getType())) > 0;
    }

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

    /**
     * 根据用户ID查询我是否点赞/收藏了该动态
     *
     * @param id
     * @param type
     * @param userId
     * @return 点赞收藏列表
     */
    @Override
    public Boolean selectOneByUserId(Long id, int type, Long userId) {
        return baseMapper.exists(new LambdaQueryWrapper<TpDynamicsNum>().eq(TpDynamicsNum::getPictureId, id).eq(TpDynamicsNum::getType, type).eq(TpDynamicsNum::getUserId, userId));
    }
}
