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.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.TpPictureVo;
import org.dromara.work.mapper.TpPictureMapper;
import org.dromara.work.service.ITpMessageService;
import org.springframework.stereotype.Service;
import org.dromara.work.domain.bo.TpWorksNumBo;
import org.dromara.work.domain.vo.TpWorksNumVo;
import org.dromara.work.domain.TpWorksNum;
import org.dromara.work.mapper.TpWorksNumMapper;
import org.dromara.work.service.ITpWorksNumService;

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 TpWorksNumServiceImpl implements ITpWorksNumService {

    private final TpWorksNumMapper baseMapper;

    private final TpPictureMapper pictureMapper;

    private final SysUserMapper userMapper;

    private final TpCategoryServiceImpl tpCategoryService;

    private final ITpMessageService tpMessageService;

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

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

        //处理作品
        List<Long> pictureIds = result.getRecords().stream().map(TpWorksNumVo::getPictureId).toList();
        List<TpPictureVo> worksList = pictureMapper.selectVoList(new LambdaQueryWrapper<TpPicture>().in(CollUtil.isNotEmpty(pictureIds), TpPicture::getId, pictureIds).eq(TpPicture::getType, 2));
        //resul.getRecords()和worksList两个集合对比getPictureId，相同的话，赋值给poiPictureVo对象
        for (TpWorksNumVo tpWorksNumVo : result.getRecords()) {
            for (TpPictureVo tpPictureVo : worksList) {
                if (tpWorksNumVo.getPictureId().equals(tpPictureVo.getId())) {
                    tpWorksNumVo.setTpPictureVo(tpPictureVo);
                    break;
                }
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 分页查询作品点赞收藏列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 作品点赞收藏分页列表
     */
    @Override
    public IPage<TpWorksNumVo> selectPageList(TpWorksNumBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TpWorksNum> lqw = buildQueryWrapper(bo);
        Page<TpWorksNumVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<Long> ids = null;
        if(bo.getCategoryId() != null){
            ids = tpCategoryService.selectListIds(bo.getCategoryId());
        }
        //处理作品
        List<Long> pictureIds = result.getRecords().stream().map(TpWorksNumVo::getPictureId).toList();
        List<TpPictureVo> worksList = pictureMapper.selectVoList(new LambdaQueryWrapper<TpPicture>().in(CollUtil.isNotEmpty(pictureIds), TpPicture::getId, pictureIds).in(CollUtil.isNotEmpty(ids), TpPicture::getCategoryId, ids).eq(TpPicture::getType, 2));
        //resul.getRecords()和worksList两个集合对比getPictureId，相同的话，赋值给poiPictureVo对象
        for (TpWorksNumVo tpWorksNumVo : result.getRecords()) {
            SysUserVo sysUserVo = new SysUserVo();
            for (TpPictureVo tpPictureVo : worksList) {
                if (tpWorksNumVo.getPictureId().equals(tpPictureVo.getId())) {
                    tpWorksNumVo.setTpPictureVo(tpPictureVo);
                    sysUserVo = userMapper.selectVoById(tpPictureVo.getUserId());
                    break;
                }
            }
            tpWorksNumVo.setSysUserVo(sysUserVo);
        }
        return result;
    }

    /**
     * 查询符合条件的作品点赞收藏列表
     *
     * @param bo 查询条件
     * @return 作品点赞收藏列表
     */
    @Override
    public List<TpWorksNumVo> queryList(TpWorksNumBo bo) {
        LambdaQueryWrapper<TpWorksNum> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

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

    /**
     * 新增作品点赞收藏
     *
     * @param bo 作品点赞收藏
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(TpWorksNumBo 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() + "，获得了收藏");
        }

        TpWorksNum add = MapstructUtils.convert(bo, TpWorksNum.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(TpWorksNumBo bo) {
        TpWorksNum update = MapstructUtils.convert(bo, TpWorksNum.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TpWorksNum 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 deleteTpWorksNum(TpWorksNumBo bo) {
        return baseMapper.delete(new LambdaQueryWrapper<TpWorksNum>().eq(TpWorksNum::getUserId, bo.getUserId()).eq(TpWorksNum::getPictureId, bo.getPictureId()).eq(TpWorksNum::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<TpWorksNum>().eq(TpWorksNum::getPictureId, pictureId).eq(TpWorksNum::getType, type));
    }

    /**
     * 查询我收藏的作品数量
     *
     * @param userId 用户ID
     * @return 数量
     */
    @Override
    public Long getCollectionCount(Long userId) {
        return baseMapper.selectCount(new LambdaQueryWrapper<TpWorksNum>().eq(TpWorksNum::getUserId, userId).eq(TpWorksNum::getType, 2));
    }

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