package jnpf.cultivate.v2.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jnpf.cultivate.mapper.FtbCourseGainedCommentMapper;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.cultivate.v2.service.V2CourseGainedCommentService;
import jnpf.model.cultivate.po.gained.FtbCourseGainedCommentEntity;
import jnpf.model.cultivate.v2.gained.req.V2AppCommentPageListReq;
import jnpf.model.cultivate.v2.gained.vo.V2AppCourseGainedCommentVO;
import jnpf.model.cultivate.v2.gained.vo.V2SimpleCourseGainedCommentVO;
import jnpf.permission.entity.UserCopyEntity;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.util.StringUtil;
import jnpf.util.UploaderUtil;
import jnpf.util.UserProvider;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class V2CourseGainedCommentServiceImpl implements V2CourseGainedCommentService {


    @Autowired
    private FtbCourseGainedCommentMapper ftbCourseGainedCommentMapper;

    @Autowired
    private UserApiV2Util userApiV2Util;

    /**
     * 获取列表
     *
     * @param req 请求参数
     * @return 列表
     */
    @Override
    public Page<V2AppCourseGainedCommentVO> getList(V2AppCommentPageListReq req) {
        String userId = UserProvider.getUser().getUserId();
        Page<V2AppCourseGainedCommentVO> page = ftbCourseGainedCommentMapper.appCommentPage(Page.of(req.getCurrentPage(), req.getPageSize()), req);
        if (CollUtil.isNotEmpty(page.getRecords())) {
            List<String> userIds = new ArrayList<>();
            for (V2AppCourseGainedCommentVO record : page.getRecords()) {
                userIds.add(record.getCreatorUserId());
            }

            List<V2SimpleCourseGainedCommentVO> simpleList = ftbCourseGainedCommentMapper.appSimpleComment(req.getGainedId());
            simpleList = buildTree(simpleList);
            Map<String, V2SimpleCourseGainedCommentVO> simpleMap = new HashMap<>();
            for (V2SimpleCourseGainedCommentVO record : simpleList) {
                simpleMap.put(record.getId(), record);
            }
            Map<String, UserBoundVO> userPrimaryBoundBatch = userApiV2Util.getUserPrimaryBoundBatch(userIds, null);
            Map<String, UserCopyEntity> userNameAndCopyForUserIds = userApiV2Util.getUserNameOnlyCopy(userIds);
            for (V2AppCourseGainedCommentVO record : page.getRecords()) {
                record.setReplyNumber(calNum(record.getId(), simpleMap));
                record.setReplyId(record.getId());
                record.setIsAuthor(userId.equals(record.getCreatorUserId()) ? 1 : 0);
                UserBoundVO userBoundVO = userPrimaryBoundBatch.get(record.getCreatorUserId());
                if (userBoundVO != null) {
                    record.setOrganizeName(userBoundVO.getOrganizeName());
                    record.setPositionName(userBoundVO.getPositionName());
                    record.setUserName(userBoundVO.getUserName());
                    record.setHeadIcon(UploaderUtil.uploaderImg(userBoundVO.getHeadIcon()));
                } else {
                    UserCopyEntity userEntity = userNameAndCopyForUserIds.get(record.getCreatorUserId());
                    if (userEntity != null) {
                        record.setUserName(userEntity.getRealName());
                        if (StringUtil.isNotEmpty(userEntity.getHeadIcon())) {
                            record.setHeadIcon(UploaderUtil.uploaderImg(userEntity.getHeadIcon()));
                        }
                    }
                }
            }
        }
        return page;
    }

    /**
     * 获取评论列表
     *
     * @param firstCommentId 一级评论
     * @return 列表
     */
    @Override
    public List<V2AppCourseGainedCommentVO> listReply(String firstCommentId) {
        String userId = UserProvider.getUser().getUserId();
        FtbCourseGainedCommentEntity commentEntity = ftbCourseGainedCommentMapper.selectById(firstCommentId);
        if (commentEntity == null) {
            return new ArrayList<>();
        }

        List<FtbCourseGainedCommentEntity> ftbCourseGainedCommentEntities = ftbCourseGainedCommentMapper.queryNextAllComment(firstCommentId);
        if (CollUtil.isEmpty(ftbCourseGainedCommentEntities)) {
            return new ArrayList<>();
        }
        List<String> userIds = ftbCourseGainedCommentEntities.stream().map(FtbCourseGainedCommentEntity::getCreatorUserId).collect(Collectors.toList());
        Map<String, UserBoundVO> userPrimaryBoundBatch = userApiV2Util.getUserPrimaryBoundBatch(userIds, null);
        Map<String, UserCopyEntity> userNameAndCopyForUserIds = userApiV2Util.getUserNameOnlyCopy(userIds);
        Map<String, FtbCourseGainedCommentEntity> listMap = ftbCourseGainedCommentEntities.stream().collect(Collectors.toMap(FtbCourseGainedCommentEntity::getId, v -> v));
        FtbCourseGainedCommentEntity ftbCourseGainedCommentEntity1 = ftbCourseGainedCommentMapper.selectById(firstCommentId);//查一级主要显示二级的名称
        if(ftbCourseGainedCommentEntity1!=null){
            listMap.put(ftbCourseGainedCommentEntity1.getId(), ftbCourseGainedCommentEntity1);
        }
        List<V2AppCourseGainedCommentVO> appCourseGainedCommentVOList = new ArrayList<>();
        for (FtbCourseGainedCommentEntity ftbCourseGainedCommentEntity : ftbCourseGainedCommentEntities) {
            V2AppCourseGainedCommentVO appCourseGainedCommentVO = new V2AppCourseGainedCommentVO();
            appCourseGainedCommentVO.setId(ftbCourseGainedCommentEntity.getId());
            if (StringUtils.isNotEmpty(ftbCourseGainedCommentEntity.getParentId())) {
                FtbCourseGainedCommentEntity parent = listMap.get(ftbCourseGainedCommentEntity.getParentId());
                if (parent != null) {
                    appCourseGainedCommentVO.setReplyUserId(parent.getCreatorUserId());
                    appCourseGainedCommentVO.setReplyUserName(parent.getRealName());
                }
            } else {
                appCourseGainedCommentVO.setAccount(ftbCourseGainedCommentEntity.getAccount());
                appCourseGainedCommentVO.setRealName(ftbCourseGainedCommentEntity.getRealName());
            }
            appCourseGainedCommentVO.setContent(ftbCourseGainedCommentEntity.getContent());
            appCourseGainedCommentVO.setCreatorUserId(ftbCourseGainedCommentEntity.getCreatorUserId());
            appCourseGainedCommentVO.setCreatorTime(ftbCourseGainedCommentEntity.getCreatorTime());
            appCourseGainedCommentVO.setIsAuthor(userId.equals(ftbCourseGainedCommentEntity.getCreatorUserId()) ? 1 : 0);
            UserBoundVO userBoundVO = userPrimaryBoundBatch.get(ftbCourseGainedCommentEntity.getCreatorUserId());

            if (userBoundVO != null) {
                appCourseGainedCommentVO.setOrganizeName(userBoundVO.getOrganizeName());
                appCourseGainedCommentVO.setPositionName(userBoundVO.getPositionName());
                appCourseGainedCommentVO.setUserName(userBoundVO.getUserName());
                appCourseGainedCommentVO.setHeadIcon(UploaderUtil.uploaderImg(userBoundVO.getHeadIcon()));
            } else {
                UserCopyEntity userEntity = userNameAndCopyForUserIds.get(ftbCourseGainedCommentEntity.getCreatorUserId());
                if (userEntity != null) {
                    appCourseGainedCommentVO.setUserName(userEntity.getRealName());
                    if (StringUtil.isNotEmpty(userEntity.getHeadIcon())) {
                        appCourseGainedCommentVO.setHeadIcon(UploaderUtil.uploaderImg(userEntity.getHeadIcon()));
                    }
                }
            }

            appCourseGainedCommentVOList.add(appCourseGainedCommentVO);
        }


        return appCourseGainedCommentVOList;
    }

    @Override
    public Boolean dealOldData(String tenantId) {

        // 查询该租户下所有评论数据
        List<FtbCourseGainedCommentEntity> allComments = ftbCourseGainedCommentMapper.selectList(new QueryWrapper<>());

        if (CollUtil.isEmpty(allComments)) {
            return true;
        }

        // 按 gainedId 分组处理
        Map<String, List<FtbCourseGainedCommentEntity>> groupedByGainedId = allComments.stream()
                .collect(Collectors.groupingBy(FtbCourseGainedCommentEntity::getGainedId));

        for (Map.Entry<String, List<FtbCourseGainedCommentEntity>> entry : groupedByGainedId.entrySet()) {
            List<FtbCourseGainedCommentEntity> comments = entry.getValue();

            // 构建简单 VO 列表用于建树
            List<V2SimpleCourseGainedCommentVO> simpleList = new ArrayList<>();
            for (FtbCourseGainedCommentEntity comment : comments) {
                V2SimpleCourseGainedCommentVO vo = new V2SimpleCourseGainedCommentVO();
                vo.setId(comment.getId());
                vo.setParentId(comment.getParentId());
                simpleList.add(vo);
            }

            // 构建树形结构
            List<V2SimpleCourseGainedCommentVO> treeList = buildTree(simpleList);

            // 递归生成路径并更新
            generatePathAndUpdate(treeList, "");
        }

        return true;
    }

    /**
     * 递归生成路径并更新数据库
     *
     * @param nodeList   节点列表
     * @param parentPath 父级路径
     */
    private void generatePathAndUpdate(List<V2SimpleCourseGainedCommentVO> nodeList, String parentPath) {
        if (CollUtil.isEmpty(nodeList)) {
            return;
        }

        for (V2SimpleCourseGainedCommentVO node : nodeList) {
            String currentPath = "";
            if (StringUtil.isNotEmpty(node.getParentId())) {
                currentPath = parentPath + node.getParentId() + "/";
            }
            // 生成当前节点的路径：父路径 + 当前索引（从 1 开始）


            // 更新数据库
            FtbCourseGainedCommentEntity updateEntity = new FtbCourseGainedCommentEntity();
            updateEntity.setId(node.getId());
            updateEntity.setPath(currentPath);
            ftbCourseGainedCommentMapper.updateById(updateEntity);

            // 递归处理子节点
            if (CollUtil.isNotEmpty(node.getChildren())) {
                generatePathAndUpdate(node.getChildren(), currentPath);
            }
        }
    }

    private Long calNum(String id, Map<String, V2SimpleCourseGainedCommentVO> simpleMap) {
        Long num = 0L;
        V2SimpleCourseGainedCommentVO vo = simpleMap.get(id);
        if (vo == null) {
            return 0L;
        }
        if (CollUtil.isEmpty(vo.getChildren())) {
            return 0L;
        }
        return calRealNum(vo.getChildren());
    }

    private Long calRealNum(List<V2SimpleCourseGainedCommentVO> vo) {
        Long num = 0L;
        if (CollUtil.isEmpty(vo)) {
            return num;
        }
        for (V2SimpleCourseGainedCommentVO v2SimpleCourseGainedCommentVO : vo) {
            num += 1;
            if (CollUtil.isNotEmpty(v2SimpleCourseGainedCommentVO.getChildren())) {
                num += calRealNum(v2SimpleCourseGainedCommentVO.getChildren());
            }

        }
        return num;
    }

    private void calRealIds(List<V2SimpleCourseGainedCommentVO> vo, List<String> ids) {
        if (CollUtil.isEmpty(vo)) {
            return;
        }
        for (V2SimpleCourseGainedCommentVO v2SimpleCourseGainedCommentVO : vo) {
            ids.add(v2SimpleCourseGainedCommentVO.getId());
            if (CollUtil.isNotEmpty(v2SimpleCourseGainedCommentVO.getChildren())) {
                calRealIds(v2SimpleCourseGainedCommentVO.getChildren(), ids);
            }
        }
    }


    /**
     * 构建树形结构
     *
     * @param list 扁平列表
     * @return 树形结构列表
     */
    private List<V2SimpleCourseGainedCommentVO> buildTree(List<V2SimpleCourseGainedCommentVO> list) {
        if (list == null || list.isEmpty()) {
            return new ArrayList<>();
        }

        // 1. 创建 Map 用于快速查找节点
        Map<String, V2SimpleCourseGainedCommentVO> nodeMap = new HashMap<>();
        for (V2SimpleCourseGainedCommentVO node : list) {
            nodeMap.put(node.getId(), node);
        }

        // 2. 构建树结构
        List<V2SimpleCourseGainedCommentVO> rootNodes = new ArrayList<>();
        for (V2SimpleCourseGainedCommentVO node : list) {
            String parentId = node.getParentId();
            if (parentId == null || "0".equals(parentId) || "-1".equals(parentId)) {
                // 根节点直接加入结果集
                rootNodes.add(node);
            } else {
                // 查找父节点并添加当前节点为其子节点
                V2SimpleCourseGainedCommentVO parent = nodeMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(node);
                }
            }
        }

        return rootNodes;
    }
}