package shop.alien.store.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.ImmutableList;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import shop.alien.entity.result.R;
import shop.alien.entity.store.*;
import shop.alien.entity.store.vo.CommonCommentVo;
import shop.alien.entity.store.vo.CommonRatingVo;
import shop.alien.entity.store.vo.StoreInfoScoreVo;
import shop.alien.entity.store.vo.WebSocketVo;
import shop.alien.mapper.*;
import shop.alien.store.config.WebSocketProcess;
import shop.alien.store.service.CommonCommentService;
import shop.alien.store.service.CommonRatingService;
import shop.alien.store.util.CommonConstant;
import shop.alien.store.util.ai.AiContentModerationUtil;
import shop.alien.store.util.ai.AiVideoModerationUtil;
import shop.alien.util.common.DateUtils;
import shop.alien.util.common.constant.CommentSourceTypeEnum;
import shop.alien.util.common.constant.RatingBusinessTypeEnum;
import shop.alien.util.common.safe.TextModerationUtil;
import shop.alien.util.common.safe.TextReviewServiceEnum;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 评价表 服务实现类
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional
public class CommonRatingServiceImpl extends ServiceImpl<CommonRatingMapper, CommonRating> implements CommonRatingService {

    @Autowired
    private TextModerationUtil textModerationUtil;

    private final  CommonRatingMapper commonRatingMapper;
    private final StoreInfoMapper storeInfoMapper;
    private final StoreUserMapper storeUserMapper;
    private final LifeNoticeMapper lifeNoticeMapper;
    private final WebSocketProcess webSocketProcess;
    private final LifeUserMapper lifeUserMapper;
    private final CommonCommentMapper commonCommentMapper;
    private final LifeLikeRecordMapper lifeLikeRecordMapper;
    private final LifeCollectMapper lifeCollectMapper;
    private final LifeFansMapper lifeFansMapper;
    private final TagsSynonymMapper tagsSynonymMapper;
    private final CommonCommentService commonCommentService;
    private final StoreCommentAppealMapper storeCommentAppealMapper;
    private final AiContentModerationUtil aiContentModerationUtil;
    @Qualifier("commonVideoTaskExecutor")
    private final ExecutorService commonVideoTaskExecutor;
    private final AiVideoModerationUtil aiVideoModerationUtil;

    public static final List<String> SERVICES_LIST = ImmutableList.of(
            TextReviewServiceEnum.COMMENT_DETECTION_PRO.getService(),
            TextReviewServiceEnum.LLM_QUERY_MODERATION.getService()
    );



    @Override
    public Integer saveCommonRating(CommonRating commonRating) {
        // 1. 文本审核 + 视频审核（评价有图片和视频）
        try {
            // 手动存评分1,2,3
            if (StringUtils.isNotEmpty(commonRating.getOtherScore())) {
                JSONObject parse = JSONObject.parse(commonRating.getOtherScore());
                commonRating.setScoreOne(parse.getDouble("scoreOne"));
                commonRating.setScoreTwo(parse.getDouble("scoreTwo"));
                commonRating.setScoreThree(parse.getDouble("scoreThree"));
            }
            int i = this.save(commonRating) ? 0 : 1;
            // 一次遍历完成分类，避免多次流式处理
            Map<String, List<String>> urlCategoryMap = StoreRenovationRequirementServiceImpl.classifyUrls(Arrays.asList(commonRating.getImageUrls().split(",")));
            AiContentModerationUtil.AuditResult auditResult = aiContentModerationUtil.auditContent(commonRating.getContent(), urlCategoryMap.get("image"));
            if (!auditResult.isPassed()) {
                // 审核不通过
                CommonRating rating = this.getById(commonRating.getId());
                rating.setAuditStatus(2);
                rating.setAuditReason(auditResult.getFailureReason());
                this.saveOrUpdate(rating);
            } else{
                CompletableFuture.runAsync(() -> {
                    AiVideoModerationUtil.VideoAuditResult videoAuditResult = null;
                    try {
                        // 调用审核接口，增加超时控制（避免接口挂死）
                        videoAuditResult = CompletableFuture.supplyAsync(
                                () -> aiVideoModerationUtil.auditVideos(urlCategoryMap.get("video")),
                                commonVideoTaskExecutor
                        ).get();

                        // 审核不通过则更新状态和原因
                        if (Objects.nonNull(videoAuditResult) && !videoAuditResult.isPassed()) {
                            // 重新查询最新的rating，避免并发覆盖
                            CommonRating rating = this.getById(commonRating.getId());
                            if (Objects.isNull(rating)) {
                                log.error("视频审核后更新失败，rating，ID：{}", rating.getId());
                                return;
                            }
                            rating.setAuditStatus(2);
                            // 失败原因
                            rating.setAuditReason(videoAuditResult.getFailureReason());
                            this.saveOrUpdate(rating);
                            log.info("视频审核不通过，已更新状态，requirementID：{}，原因：{}",
                                    rating.getId(), videoAuditResult.getFailureReason());
                        } else if (Objects.nonNull(videoAuditResult) && videoAuditResult.isPassed()) {
                            // 审核通过也更新状态（可选，根据业务需求）
                            CommonRating rating = this.getById(commonRating.getId());
                            if (Objects.nonNull(rating)) {
                                rating.setAuditStatus(1);
//                                latestRequirement.setAuditReason(null);
                                this.saveOrUpdate(rating);
                                // 对不同的businessType进行不同的处理，
                                doBusinessWithType(commonRating);
                                log.info("视频审核通过，已更新状态，requirementID：{}", rating.getId());
                            }
                        }
                    } catch (Exception e) {
                        log.error("视频审核接口调用异常，commonRating：{}", commonRating.getId(), e);
                        CommonRating rating = this.getById(commonRating.getId());
                        if (Objects.nonNull(rating)) {
                            rating.setAuditStatus(2);
                            rating.setAuditReason("视频审核接口调用异常：" + e.getMessage()); // 实际需捕获具体异常信息
                            this.saveOrUpdate(rating);
                        }
                    }
                }, commonVideoTaskExecutor);
            }
            return i;
        } catch (Exception e) {
            log.error("CommonRatingService.saveCommonRating ERROR Msg={}", e.getMessage());
            return 1;
        }
    }

    /**
     * 根据不同的businessType进行不同的处理
     * @param commonRating 评价信息
     */
    private void doBusinessWithType(CommonRating commonRating) throws Exception {
        Integer businessId = commonRating.getBusinessId();
        Double score = commonRating.getScore();
        if(1 == commonRating.getBusinessType()){
            // 更新门店评价信息
            StoreInfoScoreVo storeInfoScoreVo = commonRatingMapper.getCommentCountAndScoreInfo(commonRating.getBusinessType(),businessId);
            double total = storeInfoScoreVo.getTotal();
            double scoreAvg = (total == 0 ? 0 : storeInfoScoreVo.getScore() / total);
            double scoreOne = (total == 0 ? 0 : storeInfoScoreVo.getScoreOne() / total);
            double scoreTwo = (total == 0 ? 0 : storeInfoScoreVo.getScoreTwo() / total);
            double scoreThree = (total == 0 ? 0 : storeInfoScoreVo.getScoreThree() / total);
            StoreInfo storeInfo = new StoreInfo();
            storeInfo.setId(businessId);
            storeInfo.setScoreAvg(new BigDecimal(scoreAvg).setScale(2, RoundingMode.HALF_UP).doubleValue());
            storeInfo.setScoreOne(new BigDecimal(scoreOne).setScale(2, RoundingMode.HALF_UP).doubleValue());
            storeInfo.setScoreTwo(new BigDecimal(scoreTwo).setScale(2, RoundingMode.HALF_UP).doubleValue());
            storeInfo.setScoreThree(new BigDecimal(scoreThree).setScale(2, RoundingMode.HALF_UP).doubleValue());
            storeInfoMapper.updateById(storeInfo);
            StoreUser storeUser = storeUserMapper.selectOne(new LambdaQueryWrapper<StoreUser>().eq(StoreUser::getStoreId, storeInfo.getId()).eq(StoreUser::getDeleteFlag, 0));

            // 如果差评，则发送差评提醒
            if(score != null && score >= 0.5 && score <= 2.5){
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String commonDate = simpleDateFormat.format(new Date());
                LifeNotice lifeMessage = new LifeNotice();
                lifeMessage.setReceiverId("store_" + storeUser.getPhone());
                String text = "在"+commonDate+"，您的店铺有一条差评记录，您可查看评价内容是否属实，如不属实，可向平台进行申诉。";
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("message", text);
                lifeMessage.setContext(jsonObject.toJSONString());
                lifeMessage.setTitle("差评通知");
                lifeMessage.setSenderId("system");
                lifeMessage.setIsRead(0);
                lifeMessage.setNoticeType(1);
                lifeNoticeMapper.insert(lifeMessage);

                WebSocketVo websocketVo = new WebSocketVo();
                websocketVo.setSenderId("system");
                websocketVo.setReceiverId("store_" + storeUser.getPhone());
                websocketVo.setCategory("notice");
                websocketVo.setNoticeType("1");
                websocketVo.setIsRead(0);
                websocketVo.setText(JSONObject.from(lifeMessage).toJSONString());
                webSocketProcess.sendMessage("store_" + storeUser.getPhone(), JSONObject.from(websocketVo).toJSONString());
            }
        }

    }
    @Override
    public R getRatingList(Integer pageNum, Integer pageSize, Integer businessType, Long businessId, Long userId, Integer auditStatus, Integer searchScore, Integer days, Integer replyStatus, Integer tagId) {
        Page<CommonRating> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<CommonRating> wrapper = new LambdaQueryWrapper<>();
        
        // 业务类型筛选
        if (businessType != null) {
            wrapper.eq(CommonRating::getBusinessType, businessType);
        }
        // 业务ID筛选
        if (businessId != null) {
            wrapper.eq(CommonRating::getBusinessId, businessId);
        }
        // 审核状态筛选
        if (auditStatus != null) {
            wrapper.eq(CommonRating::getAuditStatus, auditStatus);
        }
        // 评分等级筛选
        if (searchScore != null) {
            if(searchScore == 1){
                // 1-好评
                wrapper.ge(CommonRating::getScore, 4.5);
            }else if(searchScore == 2){
                // 2-中评
                wrapper.ge(CommonRating::getScore, 3.0);
                wrapper.le(CommonRating::getScore, 4.0);
            }else if(searchScore == 3){
                // 3-差评
                wrapper.ge(CommonRating::getScore, 0.5);
                wrapper.le(CommonRating::getScore, 2.5);
            }else if(searchScore == 4){
                // 4-有图
                wrapper.isNotNull(CommonRating::getImageUrls);
                wrapper.ne(CommonRating::getImageUrls, "");
                wrapper.apply("TRIM({0}) <> ''", "image_urls");
            }
        }
        // 时间范围筛选
        if (days != null && days > 0) {
            Date date = DateUtils.calcDays(new Date(), -days);
            wrapper.ge(CommonRating::getCreatedTime, date);
        }
        // 回复状态筛选（使用EXISTS子查询在数据库层面筛选）
        if (replyStatus != null && (replyStatus == 1 || replyStatus == 2)) {
            if (replyStatus == 1) {
                // 已回复：存在商户评论
                wrapper.apply("EXISTS (SELECT 1 FROM common_comment cc WHERE cc.source_type = 1 " +
                             "AND cc.source_id = common_rating.id AND cc.comment_type = 2 " +
                             "AND cc.is_show = 1 AND cc.audit_status = 1 AND cc.delete_flag = 0)");
            } else if (replyStatus == 2) {
                // 未回复：不存在商户评论
                wrapper.apply("NOT EXISTS (SELECT 1 FROM common_comment cc WHERE cc.source_type = 1 " +
                             "AND cc.source_id = common_rating.id AND cc.comment_type = 2 " +
                             "AND cc.is_show = 1 AND cc.audit_status = 1 AND cc.delete_flag = 0)");
            }
        }
        // 标签筛选
        if (tagId != null) {
            // 1. 查询标签关联的评论ID列表（tags_synonym.comment_id 关联 common_comment.id）
            LambdaQueryWrapper<TagsSynonym> tagWrapper = new LambdaQueryWrapper<>();
            tagWrapper.eq(TagsSynonym::getMainTagId, tagId)
                     .eq(TagsSynonym::getDeleteFlag, 0)
                     .isNotNull(TagsSynonym::getCommentId);  // 确保comment_id不为空
            List<TagsSynonym> tagsSynonymList = tagsSynonymMapper.selectList(tagWrapper);

            if (CollectionUtils.isNotEmpty(tagsSynonymList)) {
                // 2. 提取评论ID列表（common_comment.id）
                List<Long> commentIdList = tagsSynonymList.stream()
                        .filter(synonym -> synonym != null && synonym.getCommentId() != null)
                        .map(synonym -> synonym.getCommentId().longValue())
                        .distinct()
                        .collect(Collectors.toList());

                if (CollectionUtils.isNotEmpty(commentIdList)) {
                    // 3. 通过评论ID查询common_comment表，获取source_id（评价ID）
                    LambdaQueryWrapper<CommonComment> commentWrapper = new LambdaQueryWrapper<>();
                    commentWrapper.in(CommonComment::getId, commentIdList)
                                 .eq(CommonComment::getSourceType, CommentSourceTypeEnum.STORE_COMMENT.getType())  // source_type=1表示评价的评论
                                 .eq(CommonComment::getIsShow, 1)
                                 .eq(CommonComment::getAuditStatus, 1);
                    List<CommonComment> comments = commonCommentMapper.selectList(commentWrapper);

                    if (CollectionUtils.isNotEmpty(comments)) {
                        // 4. 提取评价ID列表（common_comment.source_id = common_rating.id）
                        List<Long> ratingIdList = comments.stream()
                                .filter(comment -> comment.getSourceId() != null)
                                .map(CommonComment::getSourceId)
                                .distinct()
                                .collect(Collectors.toList());

                        if (CollectionUtils.isNotEmpty(ratingIdList)) {
                            wrapper.in(CommonRating::getId, ratingIdList);
                        } else {
                            // 如果没有匹配的评价ID，返回空结果
                            wrapper.eq(CommonRating::getId, -1);
                        }
                    } else {
                        // 如果没有匹配的评论，返回空结果
                        wrapper.eq(CommonRating::getId, -1);
                    }
                } else {
                    // 如果没有评论ID，返回空结果
                    wrapper.eq(CommonRating::getId, -1);
                }
            } else {
                // 如果没有标签关联，返回空结果
                wrapper.eq(CommonRating::getId, -1);
            }
        }

        wrapper.eq(CommonRating::getIsShow, 1);
        wrapper.orderByDesc(CommonRating::getId);
        IPage<CommonRating> page1 = this.page(page, wrapper);

        // 处理回复状态筛选
        return doListBusinessWithType(page1, businessType, userId, replyStatus);
    }

    @Override
    public Object getRatingCount(Integer businessId, Integer businessType) {
        // 查询全部评价记录
        LambdaQueryWrapper<CommonRating> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CommonRating::getBusinessId, businessId);
        wrapper.eq(CommonRating::getBusinessType, businessType);
        wrapper.eq(CommonRating::getIsShow, 1);
        List<CommonRating> commonRatings = commonRatingMapper.selectList(wrapper);
        List<Long> collect = commonRatings.stream().map(x -> x.getId()).collect(Collectors.toList());
        // 如果为空直接返回
        Map<String, Object> ratingCount = new HashMap<>();
        if(commonRatings.isEmpty()){
            return ratingCount;
        }
        // 获取评价统计信息（总评论数、有图评论数、好评数、中评数、差评数）
        ratingCount = commonRatingMapper.getRatingCount(new QueryWrapper<CommonRating>().in("id", collect));

        // 计算好评、中评、差评占比
        // 注意：数据库返回的 count 可能是 BigDecimal、Long 或 Integer 类型，需要安全转换
        int goodCount = getIntValue(ratingCount.get("goodCount"));
        int midCount = getIntValue(ratingCount.get("midCount"));
        int badCount = getIntValue(ratingCount.get("badCount"));
        int totalCount = goodCount + midCount + badCount;

        if (totalCount > 0) {
            // 计算占比（保留2位小数）
            Double goodPercent = Math.round((goodCount * 100.0 / totalCount) * 100.0) / 100.0;
            Double midPercent = Math.round((midCount * 100.0 / totalCount) * 100.0) / 100.0;
            Double badPercent = Math.round((badCount * 100.0 / totalCount) * 100.0) / 100.0;

            ratingCount.put("goodPercent", goodPercent);
            ratingCount.put("midPercent", midPercent);
            ratingCount.put("badPercent", badPercent);
        } else {
            ratingCount.put("goodPercent", 0.0);
            ratingCount.put("midPercent", 0.0);
            ratingCount.put("badPercent", 0.0);
        }

        if(RatingBusinessTypeEnum.STORE_RATING.getBusinessType() == businessType){
            // 1店铺评分
            StoreInfo storeInfo = storeInfoMapper.selectById(businessId);
            ratingCount.put("storeScore", storeInfo.getScoreAvg());

            // 2统计评价数量
            AtomicReference<Integer> count = new AtomicReference<>(0);
            count.updateAndGet(v -> v + collect.size());
            // 1.查询评价的评论的记录
            LambdaQueryWrapper<CommonComment> commentWrapper = new LambdaQueryWrapper<CommonComment>()
                    .eq(CommonComment::getSourceType, CommentSourceTypeEnum.STORE_COMMENT.getType())
                    .in(CommonComment::getSourceId, collect);
            List<Long> collect1 = commonCommentMapper.selectList(commentWrapper).stream().map(x -> x.getId()).collect(Collectors.toList());
            if(!collect1.isEmpty()) {
                count.updateAndGet(v -> v + collect1.size());
                // 2.在再评论的表中查询评论的回复（根评论）
                Integer allCommentsOnCommentsNum = getAllCommentsOnCommentsNum(collect1);
                count.updateAndGet(v -> v + allCommentsOnCommentsNum);
            }
            ratingCount.put("totalCount", count.get());

            // 3用户图片
            List<Long> collect2 = commonRatings.stream().filter(i -> i.getScore() >= 4.5).map(CommonRating::getUserId).distinct().limit(6).collect(Collectors.toList());
            if(!collect2.isEmpty()) {
                List<LifeUser> lifeUsers = lifeUserMapper.selectList(new QueryWrapper<LifeUser>().lambda().in(LifeUser::getId, collect2));
                ratingCount.put("img", lifeUsers.stream().map(LifeUser::getUserImage).collect(Collectors.toList()));
            } else {
                ratingCount.put("img", new ArrayList<>());
            }

            // 4. 计算回复率（已回复的评价数 / 总评价数）
            LambdaQueryWrapper<CommonComment> repliedWrapper = new LambdaQueryWrapper<>();
            repliedWrapper.eq(CommonComment::getSourceType, CommentSourceTypeEnum.STORE_COMMENT.getType())
                         .in(CommonComment::getSourceId, collect)
                         .eq(CommonComment::getCommentType, 2)  // 商户评论
                         .eq(CommonComment::getParentId, 0)     // 根评论（直接回复评价）
                         .eq(CommonComment::getDeleteFlag, 0);  // 未删除

            // 获取已回复的评价ID列表（去重）
            Set<Long> repliedRatingIds = commonCommentMapper.selectList(repliedWrapper).stream()
                    .map(CommonComment::getSourceId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toSet());

            int repliedCount = repliedRatingIds.size();
            ratingCount.put("repliedCount", repliedCount);

            // 计算回复率（保留2位小数）
            Double replyRate = 0.0;
            int ratingTotalCount = collect.size();
            if (ratingTotalCount > 0) {
                replyRate = Math.round((repliedCount * 100.0 / ratingTotalCount) * 100.0) / 100.0;
            }
            ratingCount.put("replyRate", replyRate);

        }
        return ratingCount;
    }

    @Override
    public Object getRatingDetail(Integer ratingId, Long userId) {
        CommonRating commonRating = commonRatingMapper.selectById(ratingId);
        if(commonRating == null){
            throw new IllegalArgumentException("评价不存在");
        }
        CommonRatingVo commonRatingVo = new CommonRatingVo();
        BeanUtils.copyProperties(commonRating, commonRatingVo);
        LifeUser ratingUser = lifeUserMapper.selectById(Integer.parseInt(commonRating.getUserId().toString()));
        if (ratingUser == null){
            throw new IllegalArgumentException("评价用户不存在");
        }
        // 设置评价用户信息
        commonRatingVo.setUserImage(ratingUser.getUserImage());
        commonRatingVo.setUserName(ratingUser.getUserName());
        commonRatingVo.setPhone(ratingUser.getUserPhone());
        // 查询当前用户点赞列表(仅评价)
        setIsLike(ratingId, userId, commonRatingVo);
        LifeUser loginUser = lifeUserMapper.selectById(userId);
        if (loginUser == null){
            throw new IllegalArgumentException("登录用户不存在");
        }
        // 查询当前用户关注列表
        List<LifeFans> lifeFans = lifeFansMapper.selectList(new QueryWrapper<LifeFans>().lambda()
                .eq(LifeFans::getFollowedId, "user_".concat(ratingUser.getUserPhone()))
                .eq(LifeFans::getFansId, "user_".concat(loginUser.getUserPhone()))
                .eq(LifeFans::getFansType, "1")
                .eq(LifeFans::getDeleteFlag, 0));
        // 设置是否关注
        commonRatingVo.setIsFollow(lifeFans.size() > 0 ? 1 : 0);
        // 根据业务类型处理
        extractedWithBusinessType(ratingId, userId, commonRatingVo);
        return commonRatingVo;
    }

    /**
     * 设置是否点赞
     * @param ratingId 评价id
     * @param userId 用户id
     * @param commonRatingVo 评价vo
     */
    private void setIsLike(Integer ratingId, Long userId, CommonRatingVo commonRatingVo) {
        List<LifeLikeRecord> lifeLikeRecords = lifeLikeRecordMapper.selectList(new QueryWrapper<LifeLikeRecord>().lambda()
                .eq(LifeLikeRecord::getDianzanId, userId)
                .eq(LifeLikeRecord::getHuifuId, ratingId)
                .eq(LifeLikeRecord::getDeleteFlag, 0)
                .eq(LifeLikeRecord::getType, CommonConstant.RATING_LIKE));
        if(lifeLikeRecords.size() > 0){
            commonRatingVo.setIsLike(1);
        } else {
            commonRatingVo.setIsLike(0);
        }
    }

    /**
     * 根据业务类型处理
     * @param ratingId 评价id
     * @param userId 用户id
     * @param commonRatingVo 评价vo
     */
    private void extractedWithBusinessType(Integer ratingId, Long userId, CommonRatingVo commonRatingVo) {
        if(commonRatingVo.getBusinessType().equals(RatingBusinessTypeEnum.STORE_RATING.getBusinessType())){
            // 1店铺信息
            StoreInfo storeInfo = storeInfoMapper.selectById(commonRatingVo.getBusinessId());
            if(storeInfo == null){
                throw new IllegalArgumentException("店铺不存在");
            }
            if( null != storeInfo) {
                commonRatingVo.setStoreName(storeInfo.getStoreName());
                commonRatingVo.setStoreEvaluate(storeInfo.getStoreEvaluate());
                commonRatingVo.setStoreScore(storeInfo.getScoreAvg());
                commonRatingVo.setScoreOne(storeInfo.getScoreOne());
                commonRatingVo.setScoreTwo(storeInfo.getScoreTwo());
                commonRatingVo.setScoreThree(storeInfo.getScoreThree());
            }
            // 1.1 查询是否收藏该店铺
            LambdaQueryWrapper<LifeCollect> collectWrapper = new LambdaQueryWrapper<LifeCollect>()
                    .eq(LifeCollect::getUserId, userId)
                    .eq(LifeCollect::getStoreId, storeInfo.getId())
                    .eq(LifeCollect::getDeleteFlag, 0);
            LifeCollect lifeCollect = lifeCollectMapper.selectOne(collectWrapper);
            if(lifeCollect != null){
                commonRatingVo.setIsCollect(1);
            } else {
                commonRatingVo.setIsCollect(0);
            }
            // 2查询一级评价
            List<CommonCommentVo> commonComments = commonCommentService.getFirstLevelComment(CommentSourceTypeEnum.STORE_COMMENT.getType(), ratingId,null,null, userId,CommonConstant.COMMENT_LIKE);
            commonCommentService.getAllChildComment(userId, commonRatingVo, commonComments,CommonConstant.COMMENT_LIKE);
        }
    }

    @NotNull
    private Integer getAllCommentsOnCommentsNum(List<Long> collect1) {
        LambdaQueryWrapper<CommonComment> commentReplyWrapper = new LambdaQueryWrapper<CommonComment>()
                .in(CommonComment::getParentId, collect1);
        List<Long> collect2 = commonCommentMapper.selectList(commentReplyWrapper).stream().map(x -> x.getId()).collect(Collectors.toList());
        if(collect2.isEmpty()){
            return 0;
        } else {
            return collect2.size() + getAllCommentsOnCommentsNum(collect2);
        }
    }

    /**
     * 根据业务类型处理评价列表
     *
     * @param page1       评价分页数据
     * @param businessType 业务类型
     * @param userId      用户ID
     * @param replyStatus 回复状态(0:全部, 1:已回复, 2:未回复)
     * @return R<IPage<CommonRatingVo>>
     */
    private R<IPage<CommonRatingVo>> doListBusinessWithType(IPage<CommonRating> page1, Integer businessType, Long userId, Integer replyStatus) {
        if(businessType == RatingBusinessTypeEnum.STORE_RATING.getBusinessType()){
            IPage<CommonRatingVo> result = new Page<>(page1.getCurrent(), page1.getSize(), page1.getTotal());
            List<CommonRatingVo> resultList = new ArrayList<>();
            if(page1.getRecords().isEmpty()){
                result.setRecords(resultList);
                return R.data(result);
            }

            // 1. 查询评价用户信息
            Set<Long> userIdSet = page1.getRecords().stream()
                    .map(CommonRating::getUserId)
                    .collect(Collectors.toSet());
            List<LifeUser> lifeUsers = new ArrayList<>();
            Map<Integer, LifeUser> lifeUserMap = new HashMap<>();
            if (!userIdSet.isEmpty()){
                lifeUsers = lifeUserMapper.selectList(
                        new QueryWrapper<LifeUser>().lambda()
                                .in(LifeUser::getId, userIdSet));
                lifeUserMap = lifeUsers.stream()
                        .collect(Collectors.toMap(LifeUser::getId, Function.identity()));
            }

            // 2. 查询当前用户点赞列表(仅评价)
            List<LifeLikeRecord> lifeLikeRecords = new ArrayList<>();
            Map<String, LifeLikeRecord> likeRecordMap = new HashMap<>();
            if (userId != null) {
                lifeLikeRecords = lifeLikeRecordMapper.selectList(
                        new QueryWrapper<LifeLikeRecord>().lambda()
                        .eq(LifeLikeRecord::getDianzanId, userId)
                        .eq(LifeLikeRecord::getType, CommonConstant.RATING_LIKE));
                likeRecordMap = lifeLikeRecords.stream()
                        .collect(Collectors.toMap(LifeLikeRecord::getHuifuId, Function.identity()));
            }

            // 3. 查询评价的评论记录个数和商户回复状态
            Set<Long> ratingIdSet = page1.getRecords().stream()
                    .map(CommonRating::getId)
                    .collect(Collectors.toSet());

            // 查询所有评论（用于统计评论数）
            LambdaQueryWrapper<CommonComment> commentWrapper = new LambdaQueryWrapper<>();
            commentWrapper.eq(CommonComment::getSourceType, CommentSourceTypeEnum.STORE_COMMENT.getType())
                         .in(CommonComment::getSourceId, ratingIdSet)
                         .eq(CommonComment::getIsShow, 1)
                         .eq(CommonComment::getAuditStatus, 1);
            List<CommonComment> allComments = commonCommentMapper.selectList(commentWrapper);

            // 评价ID -> 该评价下的总评论数
            Map<Long, Long> ratingCommentCountMap = allComments.stream()
                    .collect(Collectors.groupingBy(CommonComment::getSourceId, Collectors.counting()));

            // 查询每个评价的最新一条商户回复（comment_type=2, parent_id=0）
            Map<Long, CommonCommentVo> latestMerchantReplyMap = new HashMap<>();
            if (!ratingIdSet.isEmpty()) {
                QueryWrapper<CommonCommentVo> merchantReplyWrapper = new QueryWrapper<>();
                merchantReplyWrapper.eq("cc.source_type", CommentSourceTypeEnum.STORE_COMMENT.getType())
                                   .in("cc.source_id", ratingIdSet)
                                   .eq("cc.comment_type", 2)  // 商户评论
                                   .eq("cc.parent_id", 0)     // 直接回复评价的根评论
                                   .eq("cc.is_show", 1)
                                   .eq("cc.audit_status", 1)
                                   .eq("cc.delete_flag", 0)
                                   .orderByDesc("cc.created_time");

                // 查询所有商户回复（包含用户信息）
                List<CommonCommentVo> merchantReplies = commonCommentMapper.selectALlComment(
                        null,
                    merchantReplyWrapper,
                    CommonConstant.COMMENT_LIKE,
                    userId != null ? userId : 0L
                );

                // 按评价ID分组，每组只取最新的一条（已按时间倒序排序）
                if (CollectionUtils.isNotEmpty(merchantReplies)) {
                    for (CommonCommentVo reply : merchantReplies) {
                        Long ratingId = reply.getSourceId();
                        // 如果该评价还没有设置回复，则设置（因为已经按时间倒序，第一条就是最新的）
                        if (ratingId != null && !latestMerchantReplyMap.containsKey(ratingId)) {
                            latestMerchantReplyMap.put(ratingId, reply);
                        }
                    }
                }
            }

            // 4. 查询申诉信息（关联 store_comment_appeal 表）
            Map<Long, StoreCommentAppeal> appealMap = new HashMap<>();
            if (!ratingIdSet.isEmpty()) {
                // 将 Long 类型的评价ID转换为 Integer 类型（因为 comment_id 是 Integer）
                List<Integer> ratingIdList = ratingIdSet.stream()
                        .map(Long::intValue)
                        .collect(Collectors.toList());
                
                // 查询申诉记录（comment_id 关联 common_rating.id）
                LambdaQueryWrapper<StoreCommentAppeal> appealWrapper = new LambdaQueryWrapper<>();
                appealWrapper.in(StoreCommentAppeal::getCommentId, ratingIdList)
                            .eq(StoreCommentAppeal::getDeleteFlag, 0);
                List<StoreCommentAppeal> appeals = storeCommentAppealMapper.selectList(appealWrapper);
                
                // 构建评价ID -> 申诉记录的映射（一个评价可能有多条申诉，取最新的一条）
                if (CollectionUtils.isNotEmpty(appeals)) {
                    // 按评价ID分组，每组只取最新的一条申诉记录
                    Map<Integer, StoreCommentAppeal> tempAppealMap = new HashMap<>();
                    for (StoreCommentAppeal appeal : appeals) {
                        Integer commentId = appeal.getCommentId();
                        if (commentId != null) {
                            // 如果该评价还没有申诉记录，或者当前申诉记录更新，则更新
                            if (!tempAppealMap.containsKey(commentId) || 
                                (appeal.getUpdatedTime() != null && 
                                 tempAppealMap.get(commentId).getUpdatedTime() != null &&
                                 appeal.getUpdatedTime().after(tempAppealMap.get(commentId).getUpdatedTime()))) {
                                tempAppealMap.put(commentId, appeal);
                            }
                        }
                    }
                    // 转换为 Long 类型的 key
                    for (Map.Entry<Integer, StoreCommentAppeal> entry : tempAppealMap.entrySet()) {
                        appealMap.put(entry.getKey().longValue(), entry.getValue());
                    }
                }
            }

            // 5. 组装评价列表数据
            for (CommonRating record : page1.getRecords()) {
                CommonRatingVo commonRatingVo = new CommonRatingVo();
                BeanUtil.copyProperties(record, commonRatingVo);

                // 设置用户信息
                if(lifeUserMap.containsKey(Integer.parseInt(record.getUserId().toString()))){
                    LifeUser lifeUser = lifeUserMap.get(Integer.parseInt(record.getUserId().toString()));
                    commonRatingVo.setUserImage(lifeUser.getUserImage());
                    commonRatingVo.setUserName(lifeUser.getUserName());
                }

                // 设置点赞状态
                commonRatingVo.setIsLike(0);
                if(likeRecordMap.containsKey(record.getId().toString())){
                    commonRatingVo.setIsLike(1);
                }

                // 设置评论数
                commonRatingVo.setCommentCount(ratingCommentCountMap.getOrDefault(record.getId(), 0L));

                // 设置商户最新回复（同一评价下，商家只显示最新的一条回复）
                CommonCommentVo latestMerchantReply = latestMerchantReplyMap.get(record.getId());
                if (latestMerchantReply != null) {
                    // 只设置一条最新的商户回复
                    commonRatingVo.setChildCommonComments(Collections.singletonList(latestMerchantReply));
                } else {
                    // 没有商户回复，设置为空列表
                    commonRatingVo.setChildCommonComments(new ArrayList<>());
                }

                // 设置申诉状态和申诉标识
                StoreCommentAppeal appeal = appealMap.get(record.getId());
                if (appeal != null) {
                    // 已申诉，设置申诉状态
                    commonRatingVo.setAppealStatus(appeal.getAppealStatus());
                    commonRatingVo.setAppealFlag(1);
                } else {
                    // 未申诉
                    commonRatingVo.setAppealStatus(null);
                    commonRatingVo.setAppealFlag(0);
                }

                resultList.add(commonRatingVo);
            }

            result.setRecords(resultList);
            return R.data(result);
        }
        // 如果不是店铺评价类型，返回空结果
        IPage<CommonRatingVo> emptyResult = new Page<>(page1.getCurrent(), page1.getSize(), 0);
        return R.data(emptyResult);
    }
    /**
     * 删除评价后更新店铺评分
     * 
     * @param businessId 店铺ID
     */
    @Override
    public void updateStoreScoreAfterDelete(Integer businessId) {
        if (businessId == null) {
            return;
        }
        
        try {
            // 查询该店铺的所有有效评价
            LambdaQueryWrapper<CommonRating> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CommonRating::getBusinessType, 1)
                   .eq(CommonRating::getBusinessId, businessId)
                   .eq(CommonRating::getDeleteFlag, 0)
                   .eq(CommonRating::getIsShow, 1)
                   .eq(CommonRating::getAuditStatus, 1);
            List<CommonRating> ratings = commonRatingMapper.selectList(wrapper);
            
            int total = ratings.size();
            if (total == 0) {
                // 没有评价，设置默认评分为0
                StoreInfo storeInfo = new StoreInfo();
                storeInfo.setId(businessId);
                storeInfo.setScoreAvg(0.0);
                storeInfo.setScoreOne(0.0);
                storeInfo.setScoreTwo(0.0);
                storeInfo.setScoreThree(0.0);
                storeInfoMapper.updateById(storeInfo);
                log.info("店铺无有效评价，重置评分为0，businessId={}", businessId);
                return;
            }
            
            // 计算平均评分
            double scoreSum = ratings.stream().mapToDouble(r -> r.getScore() != null ? r.getScore() : 0.0).sum();
            double scoreOneSum = ratings.stream().mapToDouble(r -> r.getScoreOne() != null ? r.getScoreOne() : 0.0).sum();
            double scoreTwoSum = ratings.stream().mapToDouble(r -> r.getScoreTwo() != null ? r.getScoreTwo() : 0.0).sum();
            double scoreThreeSum = ratings.stream().mapToDouble(r -> r.getScoreThree() != null ? r.getScoreThree() : 0.0).sum();
            
            double scoreAvg = Math.round((scoreSum / total) * 100.0) / 100.0;
            double scoreOne = Math.round((scoreOneSum / total) * 100.0) / 100.0;
            double scoreTwo = Math.round((scoreTwoSum / total) * 100.0) / 100.0;
            double scoreThree = Math.round((scoreThreeSum / total) * 100.0) / 100.0;
            
            StoreInfo storeInfo = new StoreInfo();
            storeInfo.setId(businessId);
            storeInfo.setScoreAvg(scoreAvg);
            storeInfo.setScoreOne(scoreOne);
            storeInfo.setScoreTwo(scoreTwo);
            storeInfo.setScoreThree(scoreThree);
            storeInfoMapper.updateById(storeInfo);
            
            log.info("更新店铺评分成功，businessId={}，评价数={}，scoreAvg={}", businessId, total, scoreAvg);
        } catch (Exception e) {
            log.error("更新店铺评分失败，businessId={}，error={}", businessId, e.getMessage());
        }
    }

/*
    @Override
    public Double getAverageScore(Integer businessType, Long businessId) {
        LambdaQueryWrapper<CommonRating> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CommonRating::getBusinessType, businessType)
                .eq(CommonRating::getBusinessId, businessId)
                .eq(CommonRating::getIsShow, 1)
                .eq(CommonRating::getAuditStatus, 1);
        
        return this.list(wrapper).stream()
                .map(CommonRating::getScore)
                .filter(score -> score != null)
                .mapToDouble(BigDecimal::doubleValue)
                .average()
                .orElse(0.0);
    }

    @Override
    public Long getRatingCount(Integer businessType, Long businessId) {
        LambdaQueryWrapper<CommonRating> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CommonRating::getBusinessType, businessType)
                .eq(CommonRating::getBusinessId, businessId)
                .eq(CommonRating::getIsShow, 1)
                .eq(CommonRating::getAuditStatus, 1);
        
        return (long) this.count(wrapper);
    }*/

    /**
     * 安全地将数据库返回的数值类型转换为 int
     * 支持 BigDecimal、Long、Integer、Number 等类型
     *
     * @param value 数据库返回的数值对象
     * @return int 值，如果为 null 或无法转换则返回 0
     */
    private int getIntValue(Object value) {
        if (value == null) {
            return 0;
        }

        if (value instanceof Number) {
            return ((Number) value).intValue();
        }

        // 尝试字符串转换
        try {
            if (value instanceof String) {
                return Integer.parseInt((String) value);
            }
        } catch (NumberFormatException e) {
            log.warn("无法将值转换为 int: {}", value, e);
        }

        return 0;
    }
}

