package com.mcwl.resource.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mcwl.common.core.domain.entity.SysUser;
import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.common.utils.StringUtils;
import com.mcwl.resource.domain.SysAdvice;
import com.mcwl.resource.domain.WorkFlowComment;
import com.mcwl.resource.domain.WorkFlowCommentLike;
import com.mcwl.resource.domain.dto.WorkFlowCommentRes;
import com.mcwl.resource.domain.vo.WorkFlowCommentVo;
import com.mcwl.resource.mapper.WorkFlowCommentMapper;
import com.mcwl.resource.service.ISysAdviceService;
import com.mcwl.resource.service.WorkFlowCommentLikeService;
import com.mcwl.resource.service.WorkFlowCommentService;
import com.mcwl.system.domain.enums.AdviceEnum;
import com.mcwl.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 工作流评论 实现层
 *
 * @Author：ChenYan
 * @Project：McWl
 * @Package：com.mcwl.resource.service.impl
 * @Filename：ModelCommentServiceImpl
 * @Description TODO
 * @Date：2025/1/12 12:03
 */
@Service
public class WorkFlowCommentServiceImpl extends ServiceImpl<WorkFlowCommentMapper, WorkFlowComment> implements WorkFlowCommentService {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private WorkFlowCommentMapper workFlowCommentMapper;

    @Autowired
    private WorkFlowCommentLikeService workFlowCommentLikeService;


    @Autowired
    private ISysAdviceService sysAdviceService;


    @Override
    public void comment(WorkFlowCommentRes workFlowCommentRes) {
        Long parentId = workFlowCommentRes.getParentId();
        if (parentId != null) {
            WorkFlowComment mic = workFlowCommentMapper.selectById(parentId);

            if (Objects.isNull(mic)) {
                return;
            }
        }
        WorkFlowComment workFlowComment = new WorkFlowComment();
        BeanUtil.copyProperties(workFlowCommentRes, workFlowComment);
        Long userId = SecurityUtils.getUserId();
        workFlowComment.setUserId(userId);
        workFlowCommentMapper.insert(workFlowComment);


        Long replyUserId = workFlowCommentRes.getReplyUserId();

        if (Objects.isNull(replyUserId)) {
            return;
        }

        WorkFlowComment wfc = workFlowCommentMapper.selectById(replyUserId);
        if (Objects.isNull(wfc)) {
            return;
        }

        if (Objects.equals(userId, wfc.getUserId())) {
            return;
        }


        String content = StringUtils.format("{}给您的图片发了一条评论：{}",
                SecurityUtils.getLoginUser().getUser().getNickName(), workFlowCommentRes.getContent());

        // 向通知表中插入一条记录
        SysAdvice sysAdvice = new SysAdvice();
        sysAdvice.setSenderId(userId);
        sysAdvice.setReceiverId(wfc.getUserId());
        sysAdvice.setContent(content);
        sysAdvice.setProductId(workFlowCommentRes.getWorkFlowId());
        sysAdvice.setProductType(0);
        sysAdvice.setIsRead(0);
        sysAdvice.setType(AdviceEnum.COMMENT_REMIND);
        sysAdviceService.save(sysAdvice);



    }

    @Override
    public List<WorkFlowCommentVo> getComment(Long workFLowId, Integer sortType) {

        // 查询所有父评论
        LambdaQueryWrapper<WorkFlowComment> lqw = new LambdaQueryWrapper<WorkFlowComment>()
                .eq(WorkFlowComment::getWorkFlowId, workFLowId)
                .isNull(WorkFlowComment::getParentId);
        if (sortType == 0) {
            // 按点赞数降序，创建时间升序
            lqw.orderByDesc(WorkFlowComment::getLikeNum)
                    .orderByAsc(WorkFlowComment::getCreateTime);
        } else {
            lqw.orderByDesc(WorkFlowComment::getCreateTime);
        }
        List<WorkFlowComment> parentComments = baseMapper.selectList(lqw);

        // 无评论直接返回空列表
        if (parentComments.isEmpty()) {
            return new ArrayList<>();
        }

        // 2. 收集所有用户ID（父评论+子评论）
        List<Long> userIds = collectUserIds(parentComments); // 收集父评论用户ID
        List<WorkFlowComment> childComments = getChildComments(parentComments); // 查询子评论
        for (WorkFlowComment child : childComments) {
            userIds.add(child.getUserId()); // 收集子评论用户ID
        }

        // 3. 批量查询用户信息（避免N+1查询）
        Map<Long, SysUser> userMap = userIds.isEmpty() ?
                new HashMap<>() :
                sysUserService.listByIds(userIds).stream()
                        .collect(Collectors.toMap(SysUser::getUserId, Function.identity()));


        // 4. 收集所有评论ID（父评论+子评论）
        List<Long> allCommentIds = collectAllCommentIds(parentComments, childComments);

        // 5. 批量查询点赞状态（仅当用户已登录）
        Map<Long, Integer> likeStatusMap = SecurityUtils.getUserIdMax() != 0 ?
                batchGetLikeStatus(allCommentIds, SecurityUtils.getUserIdMax()) :
                new HashMap<>();

        // 6. 构建评论树结构（传递点赞状态）
        return buildCommentTree(parentComments, childComments, userMap, likeStatusMap);
    }

    @Override
    public Integer getCommentCount(Long workFlowId) {
        // 获取所工作流父评论
        List<WorkFlowComment> modelCommentList = baseMapper.selectList(
                new LambdaQueryWrapper<WorkFlowComment>()
                        .isNull(WorkFlowComment::getParentId)
                        .eq(WorkFlowComment::getWorkFlowId, workFlowId));

        // 获取所有父评论的ID
        List<Long> parentIds = modelCommentList.stream()
                .map(WorkFlowComment::getId)
                .collect(Collectors.toList());

        // 获取所有子评论
        List<WorkFlowComment> childCommentList = new ArrayList<>();
        if (!parentIds.isEmpty()) {
            childCommentList = baseMapper.selectList(new LambdaQueryWrapper<WorkFlowComment>()
                    .in(WorkFlowComment::getParentId, parentIds));
        }


        return parentIds.size() + childCommentList.size();
    }

    /**
     * 收集所有评论ID（父+子）
     */
    private List<Long> collectAllCommentIds(List<WorkFlowComment> parentComments, List<WorkFlowComment> childComments) {
        List<Long> commentIds = new ArrayList<>();
        parentComments.forEach(c -> commentIds.add(c.getId()));
        childComments.forEach(c -> commentIds.add(c.getId()));
        return commentIds;
    }

    private Map<Long, Integer> batchGetLikeStatus(List<Long> commentIds, Long currentUserId) {
        if (commentIds.isEmpty()) {
            return Collections.emptyMap();
        }

        // 批量查询点赞状态
        List<WorkFlowCommentLike> likes = workFlowCommentLikeService.list(new LambdaQueryWrapper<WorkFlowCommentLike>()
                .eq(WorkFlowCommentLike::getUserId, currentUserId)
                .in(WorkFlowCommentLike::getWorkFlowCommentId, commentIds));

        // 构建点赞状态映射
        return likes.stream()
                .collect(Collectors.toMap(WorkFlowCommentLike::getWorkFlowCommentId, like -> 1));
    }

    /**
     * 收集父评论的用户ID
     *
     * @param parentComments 父评论列表
     * @return 用户ID集合
     */
    private List<Long> collectUserIds(List<WorkFlowComment> parentComments) {
        List<Long> userIds = new ArrayList<>();
        for (WorkFlowComment comment : parentComments) {
            userIds.add(comment.getUserId());
        }
        return userIds;
    }

    /**
     * 批量查询子评论
     *
     * @param parentComments 父评论列表
     * @return 子评论列表
     */
    private List<WorkFlowComment> getChildComments(List<WorkFlowComment> parentComments) {
        if (parentComments.isEmpty()) {
            return new ArrayList<>();
        }
        // 提取父评论ID集合
        List<Long> parentIds = parentComments.stream()
                .map(WorkFlowComment::getId)
                .collect(Collectors.toList());

        // 查询子评论
        return baseMapper.selectList(
                new LambdaQueryWrapper<WorkFlowComment>()
                        .in(WorkFlowComment::getParentId, parentIds)
                        .orderByAsc(WorkFlowComment::getCreateTime)
        );
    }

    /**
     * 构建树形VO结构
     */
    private List<WorkFlowCommentVo> buildCommentTree(List<WorkFlowComment> parentComments,
                                                     List<WorkFlowComment> childComments,
                                                     Map<Long, SysUser> userMap,
                                                     Map<Long, Integer> likeStatusMap) {
        Map<Long, List<WorkFlowComment>> childMap = new HashMap<>();
        for (WorkFlowComment child : childComments) {
            childMap.computeIfAbsent(child.getParentId(), k -> new ArrayList<>()).add(child);
        }

        List<WorkFlowCommentVo> result = new ArrayList<>();
        for (WorkFlowComment parent : parentComments) {
            WorkFlowCommentVo parentVo = convertToVo(parent, userMap, likeStatusMap);
            List<WorkFlowComment> children = childMap.getOrDefault(parent.getId(), new ArrayList<>());
            List<WorkFlowCommentVo> childVos = new ArrayList<>();
            for (WorkFlowComment child : children) {
                childVos.add(convertToVo(child, userMap, likeStatusMap));
            }
            parentVo.setContentList(childVos);
            result.add(parentVo);
        }
        return result;
    }

    /**
     * 转换单个评论为VO对象
     */
    private WorkFlowCommentVo convertToVo(WorkFlowComment comment,
                                          Map<Long, SysUser> userMap,
                                          Map<Long, Integer> likeStatusMap) {
        SysUser user = userMap.get(comment.getUserId());
        if (user == null) {
            user = createDefaultUser(); // 处理用户信息缺失
        }

        WorkFlowCommentVo vo = new WorkFlowCommentVo();
        vo.setUserId(comment.getUserId());
        vo.setUserName(user.getNickName());
        vo.setUserAvatar(user.getAvatar());
        vo.setCommentId(comment.getId());
        vo.setContent(comment.getContent());
        vo.setReplyUserId(comment.getReplyUserId());
        vo.setLikeNum(comment.getLikeNum());
        vo.setIsLike(likeStatusMap.getOrDefault(comment.getId(), 0));
        vo.setCreateTime(comment.getCreateTime());
        return vo;
    }

    /**
     * 创建默认用户（防止空指针）
     */
    private SysUser createDefaultUser() {
        SysUser defaultUser = new SysUser();
        defaultUser.setUserName("匿名用户");
        defaultUser.setAvatar("/default-avatar.png");
        return defaultUser;
    }


}
