package org.dromara.zjk.learning_world.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
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.common.satoken.utils.LoginHelper;
import org.dromara.system.api.model.LoginUser;
import org.dromara.zjk.domain.vo.ZjkExpertVo;
import org.dromara.zjk.learning_world.domain.bo.ZjkLearningCommontBo;
import org.dromara.zjk.learning_world.domain.entity.ZjkLearningCommont;
import org.dromara.zjk.learning_world.domain.entity.ZjkLearningInformation;
import org.dromara.zjk.learning_world.domain.vo.ZjkLearningCommontVo;
import org.dromara.zjk.learning_world.mapper.ZjkLearningCommontMapper;
import org.dromara.zjk.learning_world.mapper.ZjkLearningInformationMapper;
import org.dromara.zjk.learning_world.service.IZjkLearningCommontService;
import org.dromara.zjk.mapper.ZjkExpertMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 评论Service业务层处理
 *
 * @author ygh
 * @date 2024-11-11
 */
@RequiredArgsConstructor
@Service
public class ZjkLearningCommontServiceImpl implements IZjkLearningCommontService {

    private final ZjkLearningCommontMapper baseMapper;

    private final ZjkLearningInformationMapper zjkLearningInformationMapper;

    private final ZjkExpertMapper zjkExpertMapper;

    /**
     * 查询评论
     *
     * @param id 主键
     * @return 评论
     */
    @Override
    public ZjkLearningCommontVo queryById(Long id) {
        ZjkLearningCommontVo zjkLearningCommontVo = baseMapper.selectVoById(id);
        //封装用户信息
        Long reviewerId = zjkLearningCommontVo.getReviewerId();
        List<ZjkExpertVo> zjkExpertVos = zjkExpertMapper.selectByUserIds(Arrays.asList(reviewerId));
        if (!CollectionUtil.isEmpty(zjkExpertVos)) {
            Map<Long, ZjkExpertVo> getExpertMap = zjkExpertVos.stream().collect(Collectors.toMap(ZjkExpertVo::getUserId, v -> v));
            ZjkExpertVo zjkExpertVo = getExpertMap.get(reviewerId);
            zjkLearningCommontVo.setExpertName(zjkExpertVo.getExpertName());
        }
        return zjkLearningCommontVo;
    }

    /**
     * 分页查询评论列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 评论分页列表
     */
    @Override
    public TableDataInfo<ZjkLearningCommontVo> queryPageList(ZjkLearningCommontBo bo, PageQuery pageQuery) {
        Long informationId = bo.getInformationId();
        Long userId = null;
        if (informationId != null) {
            ZjkLearningInformation zjkLearningInformation = zjkLearningInformationMapper.selectById(informationId);
            if (null == zjkLearningInformation) {
                throw new ServiceException("无效帖子ID");
            }
            userId =  zjkLearningInformation.getUserId();

        }
        //LambdaQueryWrapper<ZjkLearningCommont> lqw = buildQueryWrapper(bo);
        bo.setStatus("2");
        Page<ZjkLearningCommontVo> result = baseMapper.selectCommonPage(pageQuery.build(), bo);
        List<ZjkLearningCommontVo> records = result.getRecords();
        if (CollectionUtil.isEmpty(records)) {
            return TableDataInfo.build(result);
        }

        //封装用户信息
        Set<Long> getReviewerIdSet = records.stream().map(ZjkLearningCommontVo::getReviewerId).collect(Collectors.toSet());
        Set<Long> getReplyIdSet = records.stream().map(ZjkLearningCommontVo::getReplyId).collect(Collectors.toSet());
        getReviewerIdSet.addAll(getReplyIdSet);
        List<ZjkExpertVo> zjkExpertVos = zjkExpertMapper.selectByUserIds(getReviewerIdSet);
        if (!CollectionUtil.isEmpty(zjkExpertVos)) {
            Map<Long, ZjkExpertVo> getExpertMap = zjkExpertVos.stream().collect(Collectors.toMap(ZjkExpertVo::getUserId, v -> v));
            for (ZjkLearningCommontVo record : records) {
                ZjkExpertVo zjkExpertVo = getExpertMap.get(record.getReviewerId());
                record.setExpertName(zjkExpertVo.getExpertName());
                record.setExpertPhotograph(zjkExpertVo.getPhotograph());
                boolean flag = LoginHelper.getUserId().equals(userId);
                record.setReply(flag);
                if (flag || LoginHelper.getUserId().equals(record.getReviewerId())) {
                    record.setDeleted(true);
                }
            }
        }

        //收集回复
        Set<Long> collect = records.stream().map(ZjkLearningCommontVo::getId).collect(Collectors.toSet());

        // 使用 LambdaQueryWrapper，增加过滤条件，排除已删除的回复
        LambdaQueryWrapper<ZjkLearningCommont> lm = Wrappers.lambdaQuery();
        lm.in(ZjkLearningCommont::getParentId, collect)
            .eq(ZjkLearningCommont::getDelFlag, 0)// 过滤已删除的回复
            .eq(ZjkLearningCommont::getStatus, 2);  // 过滤已撤销的回复


        List<ZjkLearningCommontVo> zjkLearningCommont = baseMapper.selectVoList(lm);


        if (!CollectionUtil.isEmpty(zjkLearningCommont)) {
            Map<Long, List<ZjkLearningCommontVo>> commList = zjkLearningCommont.stream().collect(Collectors.groupingBy(ZjkLearningCommontVo::getParentId));
            for (ZjkLearningCommontVo record : records) {
                List<ZjkLearningCommontVo> zjkLearningCommontVos1 = commList.get(record.getId());
                record.setCommontVoList(zjkLearningCommontVos1);
                if (CollectionUtil.isEmpty(zjkLearningCommontVos1)) {
                    continue;
                }
                for (ZjkLearningCommontVo learningCommont : zjkLearningCommontVos1) {
                    if (learningCommont.getReplyId() == null) {
                        continue;
                    }
                    Map<Long, ZjkExpertVo> getExpertMap = zjkExpertVos.stream().collect(Collectors.toMap(ZjkExpertVo::getUserId, v -> v));
                    ZjkExpertVo reply = getExpertMap.get(learningCommont.getReviewerId());
                    if (reply != null) {
                        learningCommont.setReplyName(reply.getUserName());
                        learningCommont.setReplyPhotograph(reply.getAvatar());
                        boolean flag = LoginHelper.getUserId().equals(userId);
                        learningCommont.setDeleted(flag);
                    }
                }
            }
        }

        return TableDataInfo.build(result);
    }

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

    private LambdaQueryWrapper<ZjkLearningCommont> buildQueryWrapper(ZjkLearningCommontBo bo) {
        LambdaQueryWrapper<ZjkLearningCommont> lqw = Wrappers.lambdaQuery();
        lqw.eq(!ObjectUtil.isEmpty(bo.getInformationId()), ZjkLearningCommont::getInformationId, bo.getInformationId());
        lqw.eq(!ObjectUtil.isEmpty(bo.getReviewerId()), ZjkLearningCommont::getReviewerId, bo.getReviewerId());
        lqw.eq(!ObjectUtil.isEmpty(bo.getReplyId()), ZjkLearningCommont::getReplyId, bo.getReplyId());
        lqw.like(StringUtils.isNotBlank(bo.getComment()), ZjkLearningCommont::getComment, bo.getComment());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), ZjkLearningCommont::getStatus, bo.getStatus());
        lqw.eq(!ObjectUtil.isEmpty(bo.getParentId()), ZjkLearningCommont::getParentId, bo.getParentId());
        lqw.ge(!ObjectUtil.isEmpty(bo.getStartTime()), ZjkLearningCommont::getCommentTime, bo.getStartTime());
        lqw.le(!ObjectUtil.isEmpty(bo.getEndTime()), ZjkLearningCommont::getCommentTime, bo.getEndTime());
        return lqw;
    }

    /**
     * 新增评论
     *
     * @param bo 评论
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(ZjkLearningCommontBo bo) {
        ZjkLearningCommont add = MapstructUtils.convert(bo, ZjkLearningCommont.class);
        Long informationId = bo.getInformationId();
        Long parentId = bo.getParentId();
        ZjkLearningInformation zjkLearningInformation = zjkLearningInformationMapper.selectById(informationId);
        if (zjkLearningInformation == null) {
            throw new ServiceException("无效信息id");
        }
        if (parentId != null && !zjkLearningInformation.getUserId().equals(LoginHelper.getUserId())) {
            throw new ServiceException("不是你的 帖子无法回复");
        }
        if (parentId != null) {
            ZjkLearningCommontVo zjkLearningCommontVo = baseMapper.selectVoById(parentId);
            if (zjkLearningCommontVo == null) {
                throw new ServiceException("无效回复id");
            }
            add.setReplyId(zjkLearningCommontVo.getReviewerId());
        }
        add.setReviewerId(LoginHelper.getUserId());
        add.setCommentTime(new Date());
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        Integer commentCount = zjkLearningInformation.getCommentCount();
        commentCount = commentCount + 1;
        zjkLearningInformation.setCommentCount(commentCount);
        zjkLearningInformationMapper.updateById(zjkLearningInformation);
        return flag;
    }

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

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

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

        // 获取所有 ZjkLearningCommont 记录
        List<ZjkLearningCommont> zjkLearningCommontList = baseMapper.selectBatchIds(ids);

        // 提取所有 unique 的 informationId
        Set<Long> informationIds = zjkLearningCommontList.stream()
            .map(ZjkLearningCommont::getInformationId)
            .collect(Collectors.toSet());

        // 批量查询所有 ZjkLearningInformation
        List<ZjkLearningInformation> zjkLearningInformationList = zjkLearningInformationMapper.selectBatchIds(informationIds);

        // 使用一个 Map 来存储每个 informationId 对应的 commentCount 减少值
        Map<Long, Integer> informationCommentMap = new HashMap<>();
        for (ZjkLearningCommont zjkLearningCommont : zjkLearningCommontList) {
            Long informationId = zjkLearningCommont.getInformationId();
            informationCommentMap.put(informationId, informationCommentMap.getOrDefault(informationId, 0) + 1);
        }

        // 更新所有对应的 ZjkLearningInformation 的评论数
        for (ZjkLearningInformation zjkLearningInformation : zjkLearningInformationList) {
            Long informationId = zjkLearningInformation.getId();
            Integer commentDecrease = informationCommentMap.get(informationId);

            if (commentDecrease != null) {
                Integer currentCommentCount = zjkLearningInformation.getCommentCount();
                zjkLearningInformation.setCommentCount(currentCommentCount - commentDecrease);
            }
        }

        // 批量更新所有的 ZjkLearningInformation
        zjkLearningInformationMapper.updateBatchById(zjkLearningInformationList);

        // 批量删除 ZjkLearningCommont 记录
        return baseMapper.deleteByIds(ids) > 0;
    }



    @Override
    public int updateStatuso(ZjkLearningCommontBo bo) {
        Long id = bo.getId();
        ZjkLearningCommont zjkLearningCommont = baseMapper.selectById(id);
        if (zjkLearningCommont == null) {
            throw new ServiceException("无效id");
        }
        zjkLearningCommont.setTakedownTime(new Date());
        zjkLearningCommont.setStatus(bo.getStatus());
        return baseMapper.updateById(zjkLearningCommont);
    }
}
