package shop.alien.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import shop.alien.entity.store.*;
import shop.alien.entity.store.vo.CommonCommentVo;
import shop.alien.entity.store.vo.CommonRatingVo;
import shop.alien.mapper.*;
import shop.alien.store.service.CommonCommentService;
import shop.alien.store.util.CommonConstant;
import shop.alien.store.util.LifeDynamicsIdentityHelper;
import shop.alien.store.util.StoreLikeRecordIdentityHelper;
import shop.alien.store.util.StoreLikeRecordIdentityHelper.StoreLikerScope;
import shop.alien.store.util.ai.AiContentModerationUtil;
import shop.alien.util.common.constant.CommentSourceTypeEnum;
import shop.alien.util.common.safe.TextModerationUtil;
import shop.alien.util.type.LifeFansIdentityQuery;
import shop.alien.util.type.TypeUtil;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 评论表 服务实现类
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional
public class CommonCommentServiceImpl extends ServiceImpl<CommonCommentMapper, CommonComment> implements CommonCommentService {

    @Autowired
    private TextModerationUtil textModerationUtil;

    private final CommonCommentMapper commonCommentMapper;
    private final LifeUserDynamicsMapper lifeUserDynamicsMapper;

    private final LifeDynamicsIdentityHelper dynamicsIdentityHelper;
    private final LifeLikeRecordMapper lifeLikeRecordMapper;
    private final StoreLikeRecordIdentityHelper lifeLikeIdentityHelper;
    private final StoreUserMapper storeUserMapper;
    private final LifeUserViolationMapper lifeUserViolationMapper;
    private final LifeUserMapper lifeUserMapper;
    private final TypeUtil typeUtil;
    @Autowired
    private LifeFansMapper lifeFansMapper;
    private final AiContentModerationUtil aiContentModerationUtil;

    /**
     * 新增评论
     *
     * @param commonComment 评论对象
     * @return 0:成功, 1:失败, 2:文本内容异常, 4:字数超限（超过300字）
     */
    @Override
    public Integer addComment(CommonComment commonComment) {
        // 校验评论内容字数限制（300字）
        if (commonComment.getContent() != null && commonComment.getContent().length() > 300) {
            log.warn("评论内容超过300字限制，content length={}", commonComment.getContent().length());
            return 4; // 字数超限
        }

        // 文本内容审核 + 视频审核(评论没有)
        try {
            AiContentModerationUtil.AuditResult auditResult = aiContentModerationUtil.auditContent(commonComment.getContent(), null);
            if (!auditResult.isPassed()) {
                return 2; // 文本内容异常（包含敏感词）
            }
            // 2.审核通过，设置评价状态为已审核
            commonComment.setAuditStatus(1);
            return this.save(commonComment) ? 0 : 1;
        } catch (Exception e) {
            log.error("新增评论失败", e);
            return 1;
        }
    }

    @Override
    public List<CommonCommentVo> getListBySourceType(Integer sourceType, Integer sourceId, Integer pageNum, Integer pageSize, Long userId) {
        String likeType = null;
        if(sourceType == CommentSourceTypeEnum.STORE_COMMENT.getType()){
            likeType = CommonConstant.COMMENT_LIKE;
        } else if (sourceType == CommentSourceTypeEnum.DYNAMIC_COMMENT.getType()) {
            likeType = CommonConstant.DYNAMIC_LIKE;
        } else if (sourceType == CommentSourceTypeEnum.CLOCK_IN_COMMENT.getType()){
            likeType = CommonConstant.CLOCK_IN_LIKE;
        } else if (sourceType == CommentSourceTypeEnum.SECOND_HAND_COMMENT.getType()){
            likeType =  CommonConstant.SECOND_HAND_LIKE;
        } else if (sourceType == CommentSourceTypeEnum.STORE_DYNAMIC_COMMENT.getType()){
            likeType = CommonConstant.STORE_DYNAMIC_LIKE;
        }
        List<CommonCommentVo> firstLevelComment = getFirstLevelComment(sourceType, sourceId, pageNum, pageSize, userId,likeType);
        CommonRatingVo commonRatingVo = new CommonRatingVo();
        getAllChildComment(userId, commonRatingVo, firstLevelComment,likeType);
        return commonRatingVo.getChildCommonComments();
    }

    @Override
    public List<CommonCommentVo> getFirstLevelComment(Integer sourceType, Integer sourceId, Integer pageNum, Integer pageSize, Long userId, String likeType){
        List<CommonCommentVo> commonComments = null;
        QueryWrapper<CommonCommentVo> commentWrapper = new QueryWrapper<CommonCommentVo>();
/*        if(sourceType == CommentSourceTypeEnum.STORE_COMMENT.getType()){
            // 1查询店铺评价
            commentWrapper.eq("cc.source_type", CommentSourceTypeEnum.STORE_COMMENT.getType());

        } else if (sourceType == CommentSourceTypeEnum.DYNAMIC_COMMENT.getType()) {
            // 2查询动态评论
            commentWrapper.eq("cc.source_type", CommentSourceTypeEnum.DYNAMIC_COMMENT.getType());
        } else if (sourceType == CommentSourceTypeEnum.CLOCK_IN_COMMENT.getType()) {
            commentWrapper.eq("cc.source_type", CommentSourceTypeEnum.CLOCK_IN_COMMENT.getType());
        }*/
        if(sourceType == CommentSourceTypeEnum.STORE_DYNAMIC_COMMENT.getType()){
            sourceType = CommentSourceTypeEnum.DYNAMIC_COMMENT.getType();
        }
        commentWrapper.eq("cc.source_id", sourceId)
                .eq("cc.parent_id", 0)
                .eq("cc.source_type",sourceType)
                .eq("cc.delete_flag", CommonConstant.DELETE_FLAG_UNDELETE)
                .orderByDesc("cc.created_time");
        Page<CommonCommentVo> page = null;
        if( null != pageNum && null != pageSize){
            page = new Page<>(pageNum, pageSize);
        }
        commonComments = commonCommentMapper.selectALlComment(page, commentWrapper, likeType, userId);
        return commonComments;
    }

    @Override
    public void getAllChildComment(Long userId, CommonRatingVo commonRatingVo, List<CommonCommentVo> commonComments, String likeType) {
        // 定义评论总数
        AtomicReference<Long> count = new AtomicReference<>(0L);
        count.updateAndGet(v -> v + commonComments.size());
        List<CommonCommentVo> commonCommentVos = new ArrayList<>();
        for (CommonCommentVo commonComment : commonComments) {
//                CommonCommentVo commonCommentVo = new CommonCommentVo();
//                BeanUtils.copyProperties(commonComment, commonCommentVo);
            // 递归获取所有子评论（扁平化）
            List<CommonCommentVo> allChildComments = getChildCommentsRecursively(commonComment.getId(), userId,likeType);
            count.updateAndGet(v -> v + allChildComments.size());
            // 一级评论本身的商家/用户标识和商家信息
            // setStoreUserInfo(first);

            // 按时间排序后绑定子评论列表
            allChildComments.sort(Comparator.comparing(CommonCommentVo::getCreatedTime));

            commonComment.setChildCommonComments(allChildComments);
            commonCommentVos.add(commonComment);
        }
        commonRatingVo.setCommentCount(count.get());
        commonRatingVo.setChildCommonComments(commonCommentVos);
    }

    /**
     * 动态评论数量 目前给的是动态用的接口，可以根据sorceType返回不同数据
     * @param sourceId
     * @param sourceType
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> getCommitCount(Integer sourceId, Integer sourceType, String userId, String userType) {
        // 返回分享数，喜欢数，评论数
        Map<String, Object> map = new HashMap<>();
        // 计算评论数
        QueryWrapper<CommonComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(null != sourceId, "source_id", sourceId);
        queryWrapper.eq(null != sourceType, "source_type", sourceType);
        queryWrapper.eq("delete_flag", CommonConstant.DELETE_FLAG_UNDELETE);
        //通过当前登录人id和类型 查询举报业务id 不包含已举报的
        List<LifeUserViolation> lifeUserViolations = new ArrayList<>();
        if(sourceType == CommentSourceTypeEnum.DYNAMIC_COMMENT.getType() ){
            if("user".equals(userType)){
                LifeUser lifeUser = lifeUserMapper.selectOne(new LambdaQueryWrapper<LifeUser>().eq(LifeUser::getId,userId));
                if(lifeUser!=null){
                    LambdaQueryWrapper<LifeUserViolation> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(LifeUserViolation::getReportingUserId,lifeUser.getId());
                    lambdaQueryWrapper.eq(LifeUserViolation::getReportingUserType,2);
                    lambdaQueryWrapper.ne(LifeUserViolation::getProcessingStatus,2);
                    lifeUserViolations = lifeUserViolationMapper.selectList(lambdaQueryWrapper);
                }
            } else {
                StoreUser storeUser = storeUserMapper.selectOne(new LambdaQueryWrapper<StoreUser>().eq(StoreUser::getId,userId));
                if(storeUser!=null){
                    LambdaQueryWrapper<LifeUserViolation> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(LifeUserViolation::getReportingUserId,storeUser.getId());
                    lambdaQueryWrapper.eq(LifeUserViolation::getReportingUserType,1);
                    lambdaQueryWrapper.ne(LifeUserViolation::getProcessingStatus,2);
                    lifeUserViolations = lifeUserViolationMapper.selectList(lambdaQueryWrapper);
                }
            }
        }
        List<Integer> businessIds = lifeUserViolations.stream()
                .filter(Objects::nonNull)
                .map(LifeUserViolation::getBusinessId)
                .filter(id -> id != null && !id.toString().isEmpty())
                .collect(Collectors.toList());
        if(businessIds!=null && businessIds.size()>0){
            queryWrapper.notIn("id",businessIds);
        }

        Integer i = commonCommentMapper.selectCount(queryWrapper);
        map.put("commentCount", i);
        getOtherDataWithSourceType(sourceId, sourceType, userId, userType, map);
        return map;
    }

    @Override
    public boolean deleteComment(Long commentId) {
        if (commentId == null) {
            return false;
        }

        try {
            // 首先获取要删除的评论
            CommonComment comment = this.getById(commentId);
            if (comment == null) {
                return false;
            }
            if(comment.getParentId() == 0){
                // 获取所有子评论（包括子评论的子评论）
                List<CommonCommentVo> allChildComments = getChildCommentsRecursively(commentId, null, null);

                // 准备要删除的评论ID列表，包含父评论和所有子评论
                List<Long> commentIdsToDelete = new ArrayList<>();
                commentIdsToDelete.add(commentId); // 添加父评论ID

                // 收集所有子评论的ID
                for (CommonCommentVo child : allChildComments) {
                    commentIdsToDelete.add(child.getId());
                }

                // 批量更新所有相关评论的删除标志
                if (!commentIdsToDelete.isEmpty()) {
                    UpdateWrapper<CommonComment> wrapper = new UpdateWrapper<>();
                    wrapper.in("id", commentIdsToDelete)
                            .set("delete_flag", CommonConstant.DELETE_FLAG_DELETED); // 直接设置数据库字段

                    boolean result = this.update(wrapper);

                    if (result) {
                        log.info("成功删除评论及其子评论，评论ID列表：{}", commentIdsToDelete);
                        return true;
                    } else {
                        log.error("删除评论失败，评论ID列表：{}", commentIdsToDelete);
                        return false;
                    }
                }
            }

            // 只有父评论，没有子评论的情况
            UpdateWrapper<CommonComment> wrapper = new UpdateWrapper<>();
            wrapper.eq("id", commentId)
                   .set("delete_flag", CommonConstant.DELETE_FLAG_DELETED);

            boolean result = this.update(wrapper);
            if (result) {
                log.info("成功删除评论，评论ID：{}", commentId);
                return true;
            } else {
                log.error("删除评论失败，评论ID：{}", commentId);
                return false;
            }

        } catch (Exception e) {
            log.error("删除评论时发生异常，评论ID：{}", commentId, e);
            return false;
        }
    }


    private void getOtherDataWithSourceType(Integer sourceId, Integer sourceType, String userId, String userType, Map<String, Object> map) {
        if ( sourceType == CommentSourceTypeEnum.DYNAMIC_COMMENT.getType() ) {
            // 1.计算分析数和喜欢数
            LifeUserDynamics lifeUserDynamics = lifeUserDynamicsMapper.selectOne(new QueryWrapper<LifeUserDynamics>().eq("id", sourceId));
            if(null != lifeUserDynamics){
                map.put("likeCount",lifeUserDynamics.getDianzanCount());
                map.put("transferCount",lifeUserDynamics.getTransferCount());
                dynamicsIdentityHelper.ensureEntityLegacyPhoneId(lifeUserDynamics);
            } else {
                map.put("likeCount",0);
                map.put("transferCount",0);
            }
            StoreUser storeUser = null;
            if (lifeUserDynamics != null
                    && lifeUserDynamics.getPhoneUserType() != null
                    && lifeUserDynamics.getPhoneUserType() == LifeDynamicsIdentityHelper.TYPE_STORE
                    && lifeUserDynamics.getPhoneRefId() != null) {
                storeUser = storeUserMapper.selectById(lifeUserDynamics.getPhoneRefId());
            }
            if (storeUser != null) {
                map.put("userImage", storeUser.getHeadImg() != null ? storeUser.getHeadImg() : "");
            } else {
                map.put("userImage", "");
            }
            String fansId = "";
            int fansType = 1;
            if ("user".equals(userType)) {
                LifeUser lifeUser = lifeUserMapper.selectById(userId);
                if (lifeUser != null) {
                    fansId = "user_".concat(lifeUser.getUserPhone());
                    fansType = 1;
                }
            } else {
                StoreUser currentStoreUser = storeUserMapper.selectById(userId);
                if (currentStoreUser != null) {
                    fansId = "store_".concat(currentStoreUser.getPhone());
                    fansType = 2;
                }
            }

            // 3.查询当前用户是否喜欢
            StoreLikerScope likerScope = lifeLikeIdentityHelper.resolveFromDianzanId(fansId);
            LambdaQueryWrapper<LifeLikeRecord> likeQueryWrapper = new LambdaQueryWrapper<>();
            likeQueryWrapper.eq(LifeLikeRecord::getType, CommonConstant.LIKE_TYPE_DYNAMICS)
                    .eq(LifeLikeRecord::getHuifuId, sourceId)
                    .eq(LifeLikeRecord::getDeleteFlag, 0);
            lifeLikeIdentityHelper.applyLikerFilter(likeQueryWrapper, likerScope);
            LifeLikeRecord lifeLikeRecord = lifeLikeRecordMapper.selectOne(likeQueryWrapper);
            if(null != lifeLikeRecord){
                map.put("isLike",1);
            } else {
                map.put("isLike",0);
            }
            // 4.查询当前登录人是否关注了动态发布者

            String publisherPhoneId = dynamicsIdentityHelper.resolveComparablePhoneId(lifeUserDynamics);
            LifeFansIdentityQuery.Scope fanScope = LifeFansIdentityQuery.resolve(fansId, typeUtil);
            LifeFansIdentityQuery.Scope followedScope = LifeFansIdentityQuery.resolve(publisherPhoneId, typeUtil);
            LambdaQueryWrapper<LifeFans> fansQuery = new LambdaQueryWrapper<>();
            fansQuery.eq(LifeFans::getDeleteFlag, 0);
            LifeFansIdentityQuery.applyPair(fansQuery, fanScope, followedScope);
            LifeFans lifeFans = lifeFansMapper.selectOne(fansQuery.last("limit 1"));
            if(null != lifeFans){
                map.put("isFans",1);
            } else {
                map.put("isFans",0);
            }
        }
    }

    private List<CommonCommentVo> getChildCommentsRecursively(Long id, Long userId, String likeType) {
        List<CommonCommentVo> allChildComments = new ArrayList<>();

        // 查询直接回复当前评论的所有记录
        QueryWrapper<CommonCommentVo> wrapper = new QueryWrapper<>();
        wrapper.eq("cc.delete_flag", 0)
                .eq("cc.parent_id", id)
                .orderByAsc("cc.created_time");
        List<CommonCommentVo> directChildren = commonCommentMapper.selectALlComment(null,wrapper,likeType, userId);

        if (CollectionUtils.isEmpty(directChildren)) {
            return allChildComments;
        }
        // 处理每个直接子评论
        for (CommonCommentVo child : directChildren) {
            // 设置商家/用户标识
//            setStoreUserInfo(child);
            // 递归获取该子评论的所有子评论
            List<CommonCommentVo> grandChildren = getChildCommentsRecursively(child.getId(), userId,likeType);
            // 将当前子评论添加到结果列表
            allChildComments.add(child);
            // 将该子评论的所有子评论也添加到结果列表（扁平化）
            allChildComments.addAll(grandChildren);
        }

        return allChildComments;
    }

//
//    @Override
//    public IPage<CommonComment> getCommentList(Integer pageNum, Integer pageSize, Integer sourceType, Long sourceId, Long parentId, Integer commentType, Integer auditStatus) {
//        Page<CommonComment> page = new Page<>(pageNum, pageSize);
//        LambdaQueryWrapper<CommonComment> wrapper = new LambdaQueryWrapper<>();
//
//        if (sourceType != null) {
//            wrapper.eq(CommonComment::getSourceType, sourceType);
//        }
//        if (sourceId != null) {
//            wrapper.eq(CommonComment::getSourceId, sourceId);
//        }
//        if (parentId != null) {
//            wrapper.eq(CommonComment::getParentId, parentId);
//        }
//        if (commentType != null) {
//            wrapper.eq(CommonComment::getCommentType, commentType);
//        }
//        if (auditStatus != null) {
//            wrapper.eq(CommonComment::getAuditStatus, auditStatus);
//        }
//
//        wrapper.eq(CommonComment::getIsShow, 1);
//        wrapper.orderByDesc(CommonComment::getCreatedTime);
//
//        return this.page(page, wrapper);
//    }
//
//    @Override
//    public List<CommonComment> getRootComments(Integer sourceType, Long sourceId) {
//        LambdaQueryWrapper<CommonComment> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(CommonComment::getSourceType, sourceType)
//                .eq(CommonComment::getSourceId, sourceId)
//                .eq(CommonComment::getParentId, 0)
//                .eq(CommonComment::getIsShow, 1)
//                .eq(CommonComment::getAuditStatus, 1)
//                .orderByDesc(CommonComment::getCreatedTime);
//
//        return this.list(wrapper);
//    }
//
//    @Override
//    public List<CommonComment> getReplyList(Long parentId) {
//        LambdaQueryWrapper<CommonComment> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(CommonComment::getParentId, parentId)
//                .eq(CommonComment::getIsShow, 1)
//                .eq(CommonComment::getAuditStatus, 1)
//                .orderByAsc(CommonComment::getCreatedTime);
//
//        return this.list(wrapper);
//    }
//
//    @Override
//    public void incrementReplyCount(Long parentId) {
//        LambdaUpdateWrapper<CommonComment> updateWrapper = new LambdaUpdateWrapper<>();
//        updateWrapper.eq(CommonComment::getId, parentId)
//                .setSql("reply_count = reply_count + 1");
//        this.update(updateWrapper);
//    }
}

