package org.dromara.work.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
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.TpPictureBo;
import org.dromara.work.domain.vo.TpCategoryVo;
import org.dromara.work.domain.vo.TpPictureNumVo;
import org.dromara.work.domain.vo.TpPictureVo;
import org.dromara.work.mapper.TpPictureMapper;
import org.dromara.work.service.*;
import org.springframework.stereotype.Service;

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

/**
 * 画册Service业务层处理
 *
 * @author Maosw
 * @date 2025-02-26
 */
@RequiredArgsConstructor
@Service
public class TpPictureServiceImpl implements ITpPictureService {

    private final TpPictureMapper baseMapper;

    private final SysUserMapper sysUserMapper;

    private final ITpWorksNumService tpWorksNumService;

    private final ITpDynamicsNumService tpDynamicsNumService;

    private final ITpCommentsService tpCommentsService;

    private final ITpCategoryService tpCategoryService;

    /**
     * 查询画册
     *
     * @param id 主键
     * @return 画册
     */
    @Override
    public TpPictureVo queryById(Long id){
        // 使用 LambdaUpdateWrapper 直接更新浏览量
        baseMapper.update(null, Wrappers.<TpPicture>lambdaUpdate()
            .setIncrBy(TpPicture::getNum, 1)
            .eq(TpPicture::getId, id));
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询画册列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 画册分页列表
     */
    @Override
    public TableDataInfo<TpPictureVo> queryPageList(TpPictureBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TpPicture> lqw = buildQueryWrapper(bo);
        Page<TpPictureVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 分页查询画册列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     */
    @Override
    public IPage<TpPictureVo> selectPageList(TpPictureBo bo, Long userId, PageQuery pageQuery) {
        bo.setStatus(1);
        LambdaQueryWrapper<TpPicture> lqw = buildQueryWrapper(bo);
        if(bo.getOrderBy() == 1){
            lqw.orderByDesc(TpPicture::getCreateTime);
        }else if(bo.getOrderBy() == 2){
            lqw.orderByDesc(TpPicture::getLikeNum);
        }else if(bo.getOrderBy() == 3){
            lqw.orderByDesc(TpPicture::getComNum);
        }
        Page<TpPictureVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        for (TpPictureVo tpPictureVo : result.getRecords()) {
            SysUserVo sysUser = sysUserMapper.selectVoById(tpPictureVo.getUserId());
            tpPictureVo.setSysUserVo(sysUser);

            TpPictureNumVo vo = new TpPictureNumVo();
            Long dynamicsNum = null;
            Long collectNum = null;
            Long commentsNum = null;
            Boolean dynamics = false;
            Boolean collect = false;
            if(tpPictureVo.getType() == 2){
                dynamicsNum = tpWorksNumService.queryListCounr(tpPictureVo.getId(),1);
                collectNum = tpWorksNumService.queryListCounr(tpPictureVo.getId(),2);
                commentsNum = tpCommentsService.queryListCounr(tpPictureVo.getId(),1);
                if(userId != null){
                    //查询我是否点赞了该作品
                    dynamics = tpWorksNumService.selectOneByUserId(tpPictureVo.getId(), 1, userId);
                    //查询我是否收藏了该作品
                    collect = tpWorksNumService.selectOneByUserId(tpPictureVo.getId(), 2, userId);
                }
            }else if(tpPictureVo.getType() == 3){
                dynamicsNum = tpDynamicsNumService.queryListCounr(tpPictureVo.getId(),1);
                collectNum = tpDynamicsNumService.queryListCounr(tpPictureVo.getId(),2);
                commentsNum = tpCommentsService.queryListCounr(tpPictureVo.getId(),2);
                if(userId != null){
                    //查询我是否点赞了该动态
                    dynamics = tpDynamicsNumService.selectOneByUserId(tpPictureVo.getId(), 1, userId);
                    //查询我是否收藏了该动态
                    collect = tpDynamicsNumService.selectOneByUserId(tpPictureVo.getId(), 2, userId);
                }
            }
            vo.setDynamics(dynamics);
            vo.setCollect(collect);
            vo.setDynamicsNum(dynamicsNum);
            vo.setCollectNum(collectNum);
            vo.setCommentsNum(commentsNum);
            tpPictureVo.setTpPictureNumVo(vo);
        }
        return result;
    }

    /**
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public IPage<TpPictureVo> selectPageMyList(TpPictureBo bo, PageQuery pageQuery) {
        bo.setStatus(1);
        Long userId = null;
        if(bo.getUserId() != null){
            userId = bo.getUserId();
        }
        LambdaQueryWrapper<TpPicture> lqw = buildQueryWrapper(bo);
        Page<TpPictureVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        for (TpPictureVo tpPictureVo : result.getRecords()) {
            SysUserVo sysUser = sysUserMapper.selectVoById(tpPictureVo.getUserId());
            tpPictureVo.setSysUserVo(sysUser);

            TpPictureNumVo vo = new TpPictureNumVo();
            Long dynamicsNum = null;
            Long collectNum = null;
            Long commentsNum = null;
            Boolean dynamics = false;
            Boolean collect = false;
            if(tpPictureVo.getType() == 2){
                dynamicsNum = tpWorksNumService.queryListCounr(tpPictureVo.getId(),1);
                collectNum = tpWorksNumService.queryListCounr(tpPictureVo.getId(),2);
                commentsNum = tpCommentsService.queryListCounr(tpPictureVo.getId(),1);
                if(userId != null){
                    //查询我是否点赞了该作品
                    dynamics = tpWorksNumService.selectOneByUserId(tpPictureVo.getId(), 1, userId);
                    //查询我是否收藏了该作品
                    collect = tpWorksNumService.selectOneByUserId(tpPictureVo.getId(), 2, userId);
                }
            }else if(tpPictureVo.getType() == 3){
                dynamicsNum = tpDynamicsNumService.queryListCounr(tpPictureVo.getId(),1);
                collectNum = tpDynamicsNumService.queryListCounr(tpPictureVo.getId(),2);
                commentsNum = tpCommentsService.queryListCounr(tpPictureVo.getId(),2);
                if(userId != null){
                    //查询我是否点赞了该动态
                    dynamics = tpDynamicsNumService.selectOneByUserId(tpPictureVo.getId(), 1, userId);
                    //查询我是否收藏了该动态
                    collect = tpDynamicsNumService.selectOneByUserId(tpPictureVo.getId(), 2, userId);
                }
            }
            vo.setDynamics(dynamics);
            vo.setCollect(collect);
            vo.setDynamicsNum(dynamicsNum);
            vo.setCollectNum(collectNum);
            vo.setCommentsNum(commentsNum);
            tpPictureVo.setTpPictureNumVo(vo);
        }
        return result;
    }

    /**
     * @param pictureIds
     * @param pictureType
     * @return
     */
    @Override
    public List<TpPictureVo> selectVoList(List<Long> pictureIds, Integer pictureType) {
        return baseMapper.selectVoList(new LambdaQueryWrapper<TpPicture>().in(CollUtil.isNotEmpty(pictureIds), TpPicture::getId, pictureIds).eq(TpPicture::getType, pictureType));
    }

    /**
     * 根据ids查询画册列表
     *
     * @param ids       主键集合
     * @param pageQuery 分页参数
     * @return 画册分页列表
     */
    @Override
    public IPage<TpPictureVo> queryPageListByIds(List<Long> ids, Long userId, PageQuery pageQuery) {
        LambdaQueryWrapper<TpPicture> lqw = new LambdaQueryWrapper<TpPicture>();
        lqw.eq(TpPicture::getType, 3);
        lqw.eq(TpPicture::getStatus, 1);
        lqw.in(CollUtil.isNotEmpty(ids), TpPicture::getUserId, ids);
        lqw.orderByDesc(TpPicture::getCreateTime);
        Page<TpPictureVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        for (TpPictureVo tpPictureVo : result.getRecords()) {
            SysUserVo sysUser = sysUserMapper.selectVoById(tpPictureVo.getUserId());
            tpPictureVo.setSysUserVo(sysUser);

            TpPictureNumVo vo = new TpPictureNumVo();
            Long dynamicsNum = null;
            Long collectNum = null;
            Long commentsNum = null;
            Boolean dynamics = false;
            Boolean collect = false;
            if(tpPictureVo.getType() == 2){
                dynamicsNum = tpWorksNumService.queryListCounr(tpPictureVo.getId(),1);
                //查询我是否点赞了该作品
                dynamics = tpWorksNumService.selectOneByUserId(tpPictureVo.getId(), 1, userId);
                collectNum = tpWorksNumService.queryListCounr(tpPictureVo.getId(),2);
                //查询我是否收藏了该作品
                collect = tpWorksNumService.selectOneByUserId(tpPictureVo.getId(), 2, userId);
                commentsNum = tpCommentsService.queryListCounr(tpPictureVo.getId(),1);
            }else if(tpPictureVo.getType() == 3){
                dynamicsNum = tpDynamicsNumService.queryListCounr(tpPictureVo.getId(),1);
                //查询我是否点赞了该动态
                dynamics = tpDynamicsNumService.selectOneByUserId(tpPictureVo.getId(), 1, userId);
                collectNum = tpDynamicsNumService.queryListCounr(tpPictureVo.getId(),2);
                //查询我是否收藏了该动态
                collect = tpDynamicsNumService.selectOneByUserId(tpPictureVo.getId(), 2, userId);
                commentsNum = tpCommentsService.queryListCounr(tpPictureVo.getId(),2);
            }
            vo.setDynamics(dynamics);
            vo.setCollect(collect);
            vo.setDynamicsNum(dynamicsNum);
            vo.setCollectNum(collectNum);
            vo.setCommentsNum(commentsNum);
            tpPictureVo.setTpPictureNumVo(vo);
        }
        return result;
    }

    /**
     * 查询符合条件的画册列表
     *
     * @param bo 查询条件
     * @return 画册列表
     */
    @Override
    public List<TpPictureVo> queryList(TpPictureBo bo) {
        LambdaQueryWrapper<TpPicture> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TpPicture> buildQueryWrapper(TpPictureBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TpPicture> lqw = Wrappers.lambdaQuery();
        if(bo.getCategoryId() != null){
            List<Long> ids = tpCategoryService.selectListIds(bo.getCategoryId());
            lqw.in(CollUtil.isNotEmpty(ids), TpPicture::getCategoryId, ids);
        }
        lqw.eq(bo.getUserId() != null, TpPicture::getUserId, bo.getUserId());
        lqw.eq(bo.getToUserId() != null, TpPicture::getUserId, bo.getToUserId());
        lqw.eq(bo.getCategoryName() != null, TpPicture::getCategoryName, bo.getCategoryName());
        lqw.eq(bo.getType() != null, TpPicture::getType, bo.getType());
        lqw.eq(bo.getTenant() != null, TpPicture::getTenant, bo.getTenant());
        lqw.like(StringUtils.isNotBlank(bo.getTitle()), TpPicture::getTitle, bo.getTitle());
        lqw.eq(bo.getStatus() != null, TpPicture::getStatus, bo.getStatus());
        lqw.eq(bo.getSort() != null, TpPicture::getSort, bo.getSort());
        lqw.eq(bo.getFlag() != null, TpPicture::getFlag, bo.getFlag());
        lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
            TpPicture::getCreateTime ,params.get("beginCreateTime"), params.get("endCreateTime"));
        lqw.orderByDesc(TpPicture::getSort, TpPicture::getCreateTime);
        return lqw;
    }

    /**
     * 新增画册
     *
     * @param bo 画册
     * @return 是否新增成功
     */
    @Override
    public Long insertByBo(TpPictureBo bo) {
        if(bo.getCategoryId() != null){
            TpCategoryVo tpCategoryVo = tpCategoryService.queryById(bo.getCategoryId());
            bo.setCategoryName(tpCategoryVo.getName());
        }
        TpPicture add = MapstructUtils.convert(bo, TpPicture.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            return add.getId();
        }
        return null;
    }

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

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TpPicture 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 userId 用户id
     * @return 画册列表
     */
    @Override
    public Long getMyPictureCount(Long userId, Integer type) {
        return baseMapper.selectCount(new LambdaQueryWrapper<TpPicture>().eq(TpPicture::getUserId, userId).eq(TpPicture::getType, type));
    }
}
