package shop.alien.lawyer.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import shop.alien.entity.result.R;
import shop.alien.entity.store.*;
import shop.alien.entity.store.dto.OrderReviewDto;
import shop.alien.entity.store.vo.LawyerReviewStatisticsVo;
import shop.alien.entity.store.vo.OrderReviewDetailVo;
import shop.alien.entity.store.vo.OrderReviewVo;
import shop.alien.entity.store.vo.PendingReviewVo;
import shop.alien.entity.store.vo.WebSocketVo;
import shop.alien.lawyer.config.WebSocketProcess;
import shop.alien.lawyer.service.OrderReviewService;
import shop.alien.lawyer.service.ReviewCommentService;
import shop.alien.mapper.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 订单评价 服务实现类
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Transactional
@Service
@RequiredArgsConstructor
public class OrderReviewServiceImpl extends ServiceImpl<OrderReviewMapper, OrderReview> implements OrderReviewService {

    private final OrderReviewMapper orderReviewMapper;
    private final LawyerConsultationOrderMapper lawyerConsultationOrderMapper;
    private final ReviewCommentService reviewCommentService;
    private final ReviewCommentMapper reviewCommentMapper;
    private final LifeLikeRecordMapper lifeLikeRecordMapper;
    private final LawyerUserMapper lawyerUserMapper;
    private final LifeNoticeMapper lifeNoticeMapper;
    private final WebSocketProcess webSocketProcess;
    private final LifeUserMapper lifeUserMapper;

    /**
     * 系统发送者ID常量
     */
    private static final String SYSTEM_SENDER_ID = "system";

    /**
     * 差评阈值（0-2.5分=差评）
     */
    private static final double BAD_REVIEW_THRESHOLD = 3.0;

    /**
     * 律师接收者ID前缀
     */
    private static final String LAWYER_RECEIVER_PREFIX = "lawyer_";

    /**
     * 通知类型：系统通知
     */
    private static final Integer NOTICE_TYPE_SYSTEM = 1;

    /**
     * 业务类型：律师模块通知
     */
    private static final Integer BUSINESS_TYPE_LAWYER = 1;

    /**
     * 未读状态
     */
    private static final Integer IS_READ_UNREAD = 0;

    @Override
    public R<OrderReview> createReview(OrderReviewDto reviewDto) {
        log.info("OrderReviewServiceImpl.createReview?reviewDto={}", reviewDto);


        // 参数校验
        if (reviewDto == null) {
            return R.fail("评价信息不能为空");
        }
        if (reviewDto.getOrderId() == null) {
            return R.fail("订单ID不能为空");
        }
        Integer userId = reviewDto.getUserId();
        if (userId == null) {
            return R.fail("用户ID不能为空");
        }

        // 验证订单是否存在且属于该用户
        LawyerConsultationOrder order = lawyerConsultationOrderMapper.selectById(reviewDto.getOrderId());
        if (order == null) {
            return R.fail("订单不存在");
        }
        if (!order.getClientUserId().equals(userId)) {
            return R.fail("只能评价自己的订单");
        }

        // 检查订单是否已完成
        if (order.getOrderStatus() == null || order.getOrderStatus() != 3) {
            return R.fail("只能对已完成的订单进行评价");
        }

        // 检查是否已经评价过
        LambdaQueryWrapper<OrderReview> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderReview::getOrderId, reviewDto.getOrderId())
                .eq(OrderReview::getDeleteFlag, 0);
        OrderReview existingReview = this.getOne(queryWrapper);
        if (existingReview != null) {
            return R.success("该订单已经评价过了");
        }

        // 创建评价
        OrderReview review = new OrderReview();
        review.setOrderId(reviewDto.getOrderId());
        review.setOrderNumber(reviewDto.getOrderNumber());
        review.setUserId(userId);
        review.setLawyerUserId(order.getLawyerUserId());
        review.setOverallRating(reviewDto.getOverallRating());
        review.setServiceAttitudeRating(reviewDto.getServiceAttitudeRating());
        review.setResponseTimeRating(reviewDto.getResponseTimeRating());
        review.setProfessionalAbilityRating(reviewDto.getProfessionalAbilityRating());
        review.setReviewContent(reviewDto.getReviewContent());
        
        // 处理评价图片
//        if (reviewDto.getReviewImages() != null && !reviewDto.getReviewImages().isEmpty()) {
//            review.setReviewImages(JSON.toJSONString(reviewDto.getReviewImages()));
//        }

        if (reviewDto.getReviewImages() != null && !reviewDto.getReviewImages().isEmpty()) {
            JSONArray jsonArray = new  JSONArray();
            jsonArray.addAll(reviewDto.getReviewImages());
            review.setReviewImages(jsonArray.toString());
        }
        
        review.setIsAnonymous(reviewDto.getIsAnonymous() != null ? reviewDto.getIsAnonymous() : 0);
        review.setLikeCount(0);
        review.setCommentCount(0);
        review.setCreatedUserId(userId);
        review.setCreatedTime(new Date());

        boolean success = this.save(review);
        if (success) {
            log.info("创建评价成功，评价ID={}", review.getId());
            // 更新律师评分
            updateLawyerServiceScore(review.getLawyerUserId());

            // 如果为差评，则给律师发通知提醒
            if (isBadReview(review.getOverallRating())) {
                sendBadReviewNoticeToLawyer(review, order);
            }

            return R.data(review, "提交成功");
        } else {
            log.error("创建评价失败");
            return R.fail("创建评价失败");
        }
    }

    /**
     * 更新律师服务评分和好评/中评/差评数量
     * 计算公式：律师评分 = overallRating平均值 (转换为0-5分)
     * 评分规则：0-2.5分=差评，3-4分=中评，4.5-5分=好评
     *
     * @param lawyerUserId 律师用户ID
     */
    private void updateLawyerServiceScore(Integer lawyerUserId) {
        if (lawyerUserId == null) {
            log.warn("更新律师评分失败：律师ID为空");
            return;
        }

        try {
            // 计算平均评分（1-5星）
            Double averageRating = orderReviewMapper.getAverageRatingByLawyerUserId(lawyerUserId);

            Double serviceScore;
            if (averageRating != null) {
                // 转换为0-5分，保留一位小数（直接截取，不四舍五入）
                serviceScore = Math.floor(averageRating * 10.0) / 10.0;
                // 确保在0-5范围内
                serviceScore = Math.max(0.0, Math.min(5.0, serviceScore));
            } else {
                // 如果没有评价，设置为0.0
                serviceScore = 0.0;
                log.info("律师暂无评价，将评分设置为0.0，律师ID={}", lawyerUserId);
            }

            // 统计好评、中评、差评数量
            Integer goodReviewCount = orderReviewMapper.getGoodReviewCountByLawyerUserId(lawyerUserId);
            Integer mediumReviewCount = orderReviewMapper.getMediumReviewCountByLawyerUserId(lawyerUserId);
            Integer badReviewCount = orderReviewMapper.getBadReviewCountByLawyerUserId(lawyerUserId);

            // 处理空值
            if (goodReviewCount == null) {
                goodReviewCount = 0;
            }
            if (mediumReviewCount == null) {
                mediumReviewCount = 0;
            }
            if (badReviewCount == null) {
                badReviewCount = 0;
            }

            // 更新律师评分和好评/中评/差评数量
            LambdaUpdateWrapper<LawyerUser> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(LawyerUser::getId, lawyerUserId);
            updateWrapper.set(LawyerUser::getServiceScore, serviceScore);
            updateWrapper.set(LawyerUser::getGoodReviewCount, goodReviewCount);
            updateWrapper.set(LawyerUser::getMediumReviewCount, mediumReviewCount);
            updateWrapper.set(LawyerUser::getBadReviewCount, badReviewCount);
            int result = lawyerUserMapper.update(null, updateWrapper);

            if (result > 0) {
                log.info("更新律师评分成功，律师ID={}, 平均评分={}, 服务评分={}, 好评数={}, 中评数={}, 差评数={}",
                        lawyerUserId, averageRating, serviceScore, goodReviewCount, mediumReviewCount, badReviewCount);
            } else {
                log.warn("更新律师评分失败，律师ID={}", lawyerUserId);
            }
        } catch (Exception e) {
            log.error("更新律师评分异常，律师ID={}, 错误信息={}", lawyerUserId, e.getMessage(), e);
        }
    }

    @Override
    public R<IPage<OrderReviewVo>> getReviewList(int pageNum, int pageSize, Integer orderId, Integer lawyerUserId, Integer userId, Integer currentUserId) {
        log.info("OrderReviewServiceImpl.getReviewList?pageNum={}, pageSize={}, orderId={}, lawyerUserId={}, userId={}, currentUserId={}",
                pageNum, pageSize, orderId, lawyerUserId, userId, currentUserId);

        Page<OrderReviewVo> page = new Page<>(pageNum, pageSize);
        IPage<OrderReviewVo> result = orderReviewMapper.getReviewListWithUser(page, orderId, lawyerUserId, userId, currentUserId, null);
        
        // 处理评价图片JSON字符串转换为列表
        if (result.getRecords() != null) {
            for (OrderReviewVo vo : result.getRecords()) {
                // 处理评价图片：从JSON字符串解析为List
                if (vo.getReviewImagesJson() != null && !vo.getReviewImagesJson().trim().isEmpty()) {
                    try {
                        List<String> images = JSON.parseArray(vo.getReviewImagesJson(), String.class);
                        vo.setReviewImages(images != null ? images : new ArrayList<>());
                    } catch (Exception e) {
                        log.warn("解析评价图片失败：{}", e.getMessage());
                        vo.setReviewImages(new ArrayList<>());
                    }
                } else {
                    vo.setReviewImages(new ArrayList<>());
                }
            }
        }

        return R.data(result);
    }

    @Override
    public R<OrderReviewDetailVo> getReviewDetail(Integer reviewId, Integer currentUserId) {
        log.info("OrderReviewServiceImpl.getReviewDetail?reviewId={}, currentUserId={}", reviewId, currentUserId);

        if (reviewId == null) {
            return R.fail("评价ID不能为空");
        }

        // 查询评价详情
        OrderReviewVo reviewVo = orderReviewMapper.getReviewDetailById(reviewId, currentUserId);
        if (reviewVo == null) {
            return R.fail("评价不存在");
        }
        log.debug("查询评价详情，reviewId={}, currentUserId={}, isLiked={}", reviewId, currentUserId, reviewVo.getIsLiked());

        // 处理评价图片：从SQL查询结果中解析JSON字符串
        if (reviewVo.getReviewImagesJson() != null && !reviewVo.getReviewImagesJson().trim().isEmpty()) {
            try {
                List<String> images = JSON.parseArray(reviewVo.getReviewImagesJson(), String.class);
                reviewVo.setReviewImages(images != null ? images : new ArrayList<>());
            } catch (Exception e) {
                log.warn("解析评价图片失败：{}", e.getMessage());
                reviewVo.setReviewImages(new ArrayList<>());
            }
        } else {
            reviewVo.setReviewImages(new ArrayList<>());
        }

        // 查询评论列表
        List<shop.alien.entity.store.vo.ReviewCommentVo> comments = reviewCommentMapper.getCommentListByReviewId(reviewId, currentUserId);
        
        // 为每个评论查询回复列表
        if (comments != null && !comments.isEmpty()) {
            for (shop.alien.entity.store.vo.ReviewCommentVo comment : comments) {
                List<shop.alien.entity.store.vo.ReviewCommentVo> replies = reviewCommentMapper.getReplyListByHeadId(comment.getId(), currentUserId);
                comment.setReplies(replies);
            }
        }
        
        // 查询总评论数（包括首评论和子评论）
        Integer totalCommentCount = reviewCommentMapper.getTotalCommentCountByReviewId(reviewId);
        if (totalCommentCount == null) {
            totalCommentCount = 0;
        }
        
        // 构建返回结果
        if(reviewVo.getUserId() != null){
            LifeUser lifeUser = lifeUserMapper.selectOne(new LambdaQueryWrapper<LifeUser>().eq(LifeUser :: getId, reviewVo.getUserId()));
            reviewVo.setUserPhone(lifeUser.getUserPhone());
        }
        OrderReviewDetailVo detailVo = new OrderReviewDetailVo();
        detailVo.setReview(reviewVo);
        detailVo.setComments(comments != null ? comments : new ArrayList<>());
        detailVo.setTotalCommentCount(totalCommentCount);
        // 设置评价的点赞数和是否已点赞（从 reviewVo 中获取）
        detailVo.setLikeCount(reviewVo.getLikeCount() != null ? reviewVo.getLikeCount() : 0);
        detailVo.setIsLiked(reviewVo.getIsLiked() != null ? reviewVo.getIsLiked() : 0);

        return R.data(detailVo);
    }

    @Override
    public R<Boolean> deleteReview(Integer reviewId, Integer userId) {
        log.info("OrderReviewServiceImpl.deleteReview?reviewId={}, userId={}", reviewId, userId);

        if (reviewId == null) {
            return R.fail("评价ID不能为空");
        }

        if (userId == null) {
            return R.fail("用户ID不能为空");
        }

        // 查询评价
        OrderReview review = this.getById(reviewId);
        if (review == null) {
            return R.fail("评价不存在");
        }

        // 验证是否为评价用户（只能删除自己的评价）
        if (!review.getUserId().equals(userId)) {
            return R.fail("只能删除自己的评价");
        }

        return deleteReviewInternal(reviewId, userId, review);
    }

    @Override
    public R<Boolean> deleteReviewByAdmin(Integer reviewId) {
        log.info("OrderReviewServiceImpl.deleteReviewByAdmin?reviewId={}", reviewId);

        if (reviewId == null) {
            return R.fail("评价ID不能为空");
        }


        // 查询评价
        OrderReview review = this.getById(reviewId);
        if (review == null) {
            return R.fail("评价不存在");
        }

        return deleteReviewInternal(reviewId, null, review);
    }

    /**
     * 内部删除评价方法（删除评价时，会级联删除该评价下的所有评论和回复）
     *
     * @param reviewId 评价ID
     * @param userId 用户ID（可为null，管理员删除时为空）
     * @param review 评价对象
     * @return R<Boolean>
     */
    private R<Boolean> deleteReviewInternal(Integer reviewId, Integer userId, OrderReview review) {

        // 查询该评价下的所有评论
        LambdaQueryWrapper<ReviewComment> commentWrapper = new LambdaQueryWrapper<>();
        commentWrapper.eq(ReviewComment::getReviewId, reviewId)
                .eq(ReviewComment::getDeleteFlag, 0);
        List<ReviewComment> comments = reviewCommentService.list(commentWrapper);

        // 删除评价（逻辑删除）
        int num = orderReviewMapper.deleteById(reviewId);

        if (num > 0) {
            // 级联删除该评价下的所有评论和回复
            for (ReviewComment comment : comments) {
                // 删除评论下的所有回复（逻辑删除）
                LambdaUpdateWrapper<ReviewComment> replyUpdateWrapper = new LambdaUpdateWrapper<>();
                replyUpdateWrapper.eq(ReviewComment::getHeadId, comment.getId())
                        .eq(ReviewComment::getHeadType, 1)
                        .eq(ReviewComment::getDeleteFlag, 0);
                replyUpdateWrapper.set(ReviewComment::getDeleteFlag, 1);
                if (userId != null) {
                    replyUpdateWrapper.set(ReviewComment::getUpdatedUserId, userId);
                }
                replyUpdateWrapper.set(ReviewComment::getUpdatedTime, new Date());
                reviewCommentService.remove(replyUpdateWrapper);
                
                // 删除评论
                comment.setDeleteFlag(1);
                if (userId != null) {
                    comment.setUpdatedUserId(userId);
                }
                comment.setUpdatedTime(new Date());
                reviewCommentService.removeById(comment.getId());
            }
            
            // 更新律师评分
            updateLawyerServiceScore(review.getLawyerUserId());

            // 管理员删除时，更新订单的 is_appealed 字段为 1
            if (userId == null && review.getOrderId() != null) {
                try {
                    LambdaUpdateWrapper<LawyerConsultationOrder> orderUpdateWrapper = new LambdaUpdateWrapper<>();
                    orderUpdateWrapper.eq(LawyerConsultationOrder::getId, review.getOrderId())
                            .set(LawyerConsultationOrder::getIsAppealed, 1);
                    int updateResult = lawyerConsultationOrderMapper.update(null, orderUpdateWrapper);
                    if (updateResult > 0) {
                        log.info("管理员删除评价时，已更新订单的申诉状态，评价ID={}, 订单ID={}", reviewId, review.getOrderId());
                    } else {
                        log.warn("管理员删除评价时，更新订单申诉状态失败，评价ID={}, 订单ID={}", reviewId, review.getOrderId());
                    }
                } catch (Exception e) {
                    log.error("管理员删除评价时，更新订单申诉状态异常，评价ID={}, 订单ID={}, 错误信息={}",
                            reviewId, review.getOrderId(), e.getMessage(), e);
                    // 更新订单申诉状态失败不影响删除评价的操作
                }
            }

            if (userId != null) {
                log.info("用户删除评价成功，评价ID={}, 操作人ID={}", reviewId, userId);
            } else {
                log.info("管理员删除评价成功，评价ID={}", reviewId);
            }
            return R.data(true, "删除成功");
        } else {
            log.error("删除评价失败，评价ID={}", reviewId);
            return R.fail("删除评价失败");
        }
    }

    @Override
    public R<OrderReviewVo> getReviewByOrderId(Integer orderId, Integer currentUserId) {
        log.info("OrderReviewServiceImpl.getReviewByOrderId?orderId={}, currentUserId={}", orderId, currentUserId);

        if (orderId == null) {
            return R.fail("订单ID不能为空");
        }

        OrderReviewVo reviewVo = orderReviewMapper.getReviewByOrderId(orderId, currentUserId);
        if (reviewVo == null) {
            return R.fail("该订单暂无评价");
        }

        // 处理评价图片
        OrderReview review = this.getOne(new LambdaQueryWrapper<OrderReview>()
                .eq(OrderReview::getOrderId, orderId)
                .eq(OrderReview::getDeleteFlag, 0));
        if (review != null && review.getReviewImages() != null) {
            try {
                List<String> images = JSON.parseArray(review.getReviewImages(), String.class);
                reviewVo.setReviewImages(images);
            } catch (Exception e) {
                log.warn("解析评价图片失败：{}", e.getMessage());
            }
        }

        return R.data(reviewVo);
    }

    @Override
    public R<IPage<PendingReviewVo>> getPendingReviewList(int pageNum, int pageSize, Integer userId) {
        log.info("OrderReviewServiceImpl.getPendingReviewList?pageNum={}, pageSize={}, userId={}",
                pageNum, pageSize, userId);

        if (userId == null) {
            return R.fail("用户ID不能为空");
        }

        Page<PendingReviewVo> page = new Page<>(pageNum, pageSize);
        IPage<PendingReviewVo> result = orderReviewMapper.getPendingReviewList(page, userId);

        return R.data(result);
    }

    @Override
    public R<IPage<OrderReviewVo>> getMyReviewList(int pageNum, int pageSize, Integer userId, Integer currentUserId) {
        log.info("OrderReviewServiceImpl.getMyReviewList?pageNum={}, pageSize={}, userId={}, currentUserId={}",
                pageNum, pageSize, userId, currentUserId);

        if (userId == null) {
            return R.fail("用户ID不能为空");
        }

        Page<OrderReviewVo> page = new Page<>(pageNum, pageSize);
        IPage<OrderReviewVo> result = orderReviewMapper.getReviewListWithUser(page, null, null, userId, currentUserId, true);

        // 处理评价图片：将JSON字符串转换为List<String>
        if (result.getRecords() != null) {
            for (OrderReviewVo vo : result.getRecords()) {
                // 从数据库查询原始的reviewImages字符串
                if (vo.getId() != null) {
                    OrderReview review = this.getById(vo.getId());
                    if (review != null && review.getReviewImages() != null && !review.getReviewImages().trim().isEmpty()) {
                        try {
                            // 解析JSON数组字符串为List<String>
                            List<String> imagesList = JSON.parseArray(review.getReviewImages(), String.class);
                            vo.setReviewImages(imagesList != null ? imagesList : new ArrayList<>());
                        } catch (Exception e) {
                            log.warn("解析评价图片失败，reviewId={}, error={}", vo.getId(), e.getMessage());
                            vo.setReviewImages(new ArrayList<>());
                        }
                    } else {
                        // 如果没有图片，设置为空列表
                        vo.setReviewImages(new ArrayList<>());
                    }
                } else {
                    // 如果ID为空，设置为空列表
                    vo.setReviewImages(new ArrayList<>());
                }
            }
        }

        return R.data(result);
    }

    @Override
    public R<Boolean> likeReview(Integer reviewId, Integer userId) {
        log.info("OrderReviewServiceImpl.likeReview?reviewId={}, userId={}", reviewId, userId);

        if (reviewId == null) {
            return R.fail("评价ID不能为空");
        }
        if (userId == null) {
            return R.fail("用户ID不能为空");
        }

        // 验证评价是否存在
        OrderReview review = this.getById(reviewId);
        if (review == null || review.getDeleteFlag() == 1) {
            return R.fail("评价不存在或已删除");
        }

        // 检查是否已点赞
        LambdaQueryWrapper<LifeLikeRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LifeLikeRecord::getType, "7")
                .eq(LifeLikeRecord::getDianzanId, String.valueOf(userId))
                .eq(LifeLikeRecord::getHuifuId, String.valueOf(reviewId))
                .eq(LifeLikeRecord::getDeleteFlag, 0);
        List<LifeLikeRecord> records = lifeLikeRecordMapper.selectList(queryWrapper);

        if (CollectionUtils.isEmpty(records)) {
            // 插入点赞记录
            LifeLikeRecord likeRecord = new LifeLikeRecord();
            likeRecord.setDianzanId(String.valueOf(userId));
            likeRecord.setHuifuId(String.valueOf(reviewId));
            likeRecord.setType("7");
            likeRecord.setCreatedTime(new Date());
            likeRecord.setCreatedUserId(userId);
            lifeLikeRecordMapper.insert(likeRecord);

            // 更新评价点赞数
            LambdaUpdateWrapper<OrderReview> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(OrderReview::getId, reviewId);
            updateWrapper.setSql("like_count = like_count + 1");
            int result = orderReviewMapper.update(null, updateWrapper);

            if (result > 0) {
                log.info("点赞评价成功，评价ID={}", reviewId);
                return R.data(true, "点赞成功");
            } else {
                return R.fail("点赞失败");
            }
        } else {
            return R.data(true, "已点赞");
        }
    }

    @Override
    public R<Boolean> cancelLikeReview(Integer reviewId, Integer userId) {
        log.info("OrderReviewServiceImpl.cancelLikeReview?reviewId={}, userId={}", reviewId, userId);

        if (reviewId == null) {
            return R.fail("评价ID不能为空");
        }
        if (userId == null) {
            return R.fail("用户ID不能为空");
        }

        // 查询点赞记录
        LambdaQueryWrapper<LifeLikeRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LifeLikeRecord::getType, "7")
                .eq(LifeLikeRecord::getDianzanId, String.valueOf(userId))
                .eq(LifeLikeRecord::getHuifuId, String.valueOf(reviewId))
                .eq(LifeLikeRecord::getDeleteFlag, 0);
        List<LifeLikeRecord> records = lifeLikeRecordMapper.selectList(queryWrapper);

        if (!CollectionUtils.isEmpty(records)) {
            // 删除点赞记录（逻辑删除）
            for (LifeLikeRecord record : records) {
                int updateResult = lifeLikeRecordMapper.deleteById(record.getId());
                log.info("逻辑删除点赞记录，recordId={}, updateResult={}", record.getId(), updateResult);
            }

            // 更新评价点赞数（移除 gt 条件，确保即使为 0 也能正确更新）
            LambdaUpdateWrapper<OrderReview> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(OrderReview::getId, reviewId);
            updateWrapper.setSql("like_count = GREATEST(0, like_count - 1)");
            int result = orderReviewMapper.update(null, updateWrapper);

            if (result > 0) {
                log.info("取消点赞评价成功，评价ID={}", reviewId);
                return R.data(true, "取消点赞成功");
            } else {
                return R.fail("取消点赞失败");
            }
        } else {
            return R.data(true, "未点赞");
        }
    }

    @Override
    public R<IPage<OrderReviewVo>> getReviewListByLawyerAndType(int pageNum, int pageSize, Integer lawyerUserId, Integer type, Integer currentUserId) {
        log.info("OrderReviewServiceImpl.getReviewListByLawyerAndType?pageNum={}, pageSize={}, lawyerUserId={}, type={}, currentUserId={}",
                pageNum, pageSize, lawyerUserId, type, currentUserId);

        if (lawyerUserId == null) {
            return R.fail("律师ID不能为空");
        }

        Page<OrderReviewVo> page = new Page<>(pageNum, pageSize);
        IPage<OrderReviewVo> result = orderReviewMapper.getReviewListByLawyerAndType(page, lawyerUserId, type, currentUserId);

        // 处理评价图片JSON字符串转换为列表
        if (result.getRecords() != null) {
            for (OrderReviewVo vo : result.getRecords()) {
                // 处理评价图片：从JSON字符串解析为List
                if (vo.getReviewImagesJson() != null && !vo.getReviewImagesJson().trim().isEmpty()) {
                    try {
                        List<String> images = JSON.parseArray(vo.getReviewImagesJson(), String.class);
                        vo.setReviewImages(images != null ? images : new ArrayList<>());
                    } catch (Exception e) {
                        log.warn("解析评价图片失败：{}", e.getMessage());
                        vo.setReviewImages(new ArrayList<>());
                    }
                } else {
                    vo.setReviewImages(new ArrayList<>());
                }
            }
        }

        return R.data(result);
    }

    @Override
    public R<LawyerReviewStatisticsVo> getLawyerReviewStatistics(Integer lawyerUserId) {
        log.info("OrderReviewServiceImpl.getLawyerReviewStatistics?lawyerUserId={}", lawyerUserId);

        if (lawyerUserId == null) {
            return R.fail("律师ID不能为空");
        }

        try {
            LawyerReviewStatisticsVo statistics = new LawyerReviewStatisticsVo();

            // 统计全部评价数量
            Integer totalCount = orderReviewMapper.getTotalReviewCountByLawyerUserId(lawyerUserId);
            statistics.setTotalCount(totalCount != null ? totalCount : 0);

            // 统计好评数量
            Integer goodCount = orderReviewMapper.getGoodReviewCountByLawyerUserId(lawyerUserId);
            statistics.setGoodCount(goodCount != null ? goodCount : 0);

            // 统计中评数量
            Integer mediumCount = orderReviewMapper.getMediumReviewCountByLawyerUserId(lawyerUserId);
            statistics.setMediumCount(mediumCount != null ? mediumCount : 0);

            // 统计差评数量
            Integer badCount = orderReviewMapper.getBadReviewCountByLawyerUserId(lawyerUserId);
            statistics.setBadCount(badCount != null ? badCount : 0);

            // 统计有图评价数量
            Integer imageCount = orderReviewMapper.getImageReviewCountByLawyerUserId(lawyerUserId);
            statistics.setImageCount(imageCount != null ? imageCount : 0);

            log.info("获取律师评价统计数据成功，律师ID={}, 全部={}, 好评={}, 中评={}, 差评={}, 有图={}",
                    lawyerUserId, statistics.getTotalCount(), statistics.getGoodCount(),
                    statistics.getMediumCount(), statistics.getBadCount(), statistics.getImageCount());

            return R.data(statistics);
        } catch (Exception e) {
            log.error("获取律师评价统计数据异常，律师ID={}, 错误信息={}", lawyerUserId, e.getMessage(), e);
            return R.fail("获取统计数据失败");
        }
    }

    @Override
    public R<OrderReviewVo> getOrderEvaluation(Integer orderId) {
        log.info("OrderReviewServiceImpl.getOrderEvaluation?orderId={}", orderId);

        if (orderId == null) {
            return R.fail("订单ID不能为空");
        }

        OrderReviewVo reviewVo = orderReviewMapper.getOrderEvaluation(orderId);
        if (reviewVo == null) {
            return R.fail("该订单暂无评价");
        }

        // 处理评价图片：从JSON字符串解析为List
        if (reviewVo.getReviewImagesJson() != null && !reviewVo.getReviewImagesJson().trim().isEmpty()) {
            try {
                List<String> images = JSON.parseArray(reviewVo.getReviewImagesJson(), String.class);
                reviewVo.setReviewImages(images != null ? images : new ArrayList<>());
            } catch (Exception e) {
                log.warn("解析评价图片失败：{}", e.getMessage());
                reviewVo.setReviewImages(new ArrayList<>());
            }
        } else {
            reviewVo.setReviewImages(new ArrayList<>());
        }

        return R.data(reviewVo);
    }

    /**
     * 判断是否为差评
     * 评分规则：0-2.5分=差评
     *
     * @param overallRating 总体评分
     * @return true表示差评，false表示非差评
     */
    private boolean isBadReview(Double overallRating) {
        return overallRating != null && overallRating < BAD_REVIEW_THRESHOLD;
    }

    /**
     * 发送差评通知给律师
     *
     * @param review 评价对象
     * @param order  订单对象
     */
    private void sendBadReviewNoticeToLawyer(OrderReview review, LawyerConsultationOrder order) {
        log.info("发送差评通知给律师，评价ID={}，订单ID={}，律师ID={}", 
                review.getId(), review.getOrderId(), review.getLawyerUserId());

        try {
            // 获取律师信息
            LawyerUser lawyerUser = lawyerUserMapper.selectById(review.getLawyerUserId());
            if (lawyerUser == null || StringUtils.isBlank(lawyerUser.getPhone())) {
                log.warn("发送差评通知失败，律师不存在或手机号为空，律师ID={}", review.getLawyerUserId());
                return;
            }

            // 构建接收者ID
            String receiverId = LAWYER_RECEIVER_PREFIX + lawyerUser.getPhone();

            // 获取订单编号
            String orderNumber = review.getOrderNumber();
            if (StringUtils.isBlank(orderNumber) && order != null) {
                orderNumber = order.getOrderNumber();
            }
            if (StringUtils.isBlank(orderNumber)) {
                orderNumber = "未知";
            }

            // 构建通知消息
            String message = String.format("编号为%s的订单有一条差评，您可查看评价内容是否属实，如不属实，可向平台进行申诉。", orderNumber);

            // 创建通知对象
            LifeNotice lifeNotice = createBadReviewNotice(review.getId(), receiverId, orderNumber, message);

            // 保存通知
            int insertResult = lifeNoticeMapper.insert(lifeNotice);
            if (insertResult > 0) {
                log.info("发送差评通知成功，评价ID={}，订单编号={}，接收人ID={}", 
                        review.getId(), orderNumber, receiverId);
                
                // 发送WebSocket消息
                sendWebSocketMessage(receiverId, lifeNotice);
            } else {
                log.warn("发送差评通知失败：保存通知失败，评价ID={}，订单编号={}", 
                        review.getId(), orderNumber);
            }
        } catch (Exception e) {
            log.error("发送差评通知异常，评价ID={}，订单ID={}，异常信息：{}", 
                    review.getId(), review.getOrderId(), e.getMessage(), e);
        }
    }

    /**
     * 创建差评通知对象
     *
     * @param businessId 业务ID（评价ID）
     * @param receiverId 接收人ID（律师接收者ID）
     * @param orderNumber 订单编号
     * @param message 通知消息
     * @return 通知对象
     */
    private LifeNotice createBadReviewNotice(Integer businessId, String receiverId, String orderNumber, String message) {
        LifeNotice lifeNotice = new LifeNotice();
        lifeNotice.setSenderId(SYSTEM_SENDER_ID);
        lifeNotice.setBusinessId(businessId);
        lifeNotice.setReceiverId(receiverId);
        lifeNotice.setTitle("差评通知");
        lifeNotice.setNoticeType(NOTICE_TYPE_SYSTEM);
        lifeNotice.setIsRead(IS_READ_UNREAD);
        lifeNotice.setBusinessType(BUSINESS_TYPE_LAWYER);

        // 构建通知内容JSON
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("title", "差评通知");
        jsonObject.put("message", message);
        lifeNotice.setContext(jsonObject.toJSONString());

        return lifeNotice;
    }

    /**
     * 发送WebSocket消息
     *
     * @param receiverId 接收人ID
     * @param lifeNotice 通知对象
     */
    private void sendWebSocketMessage(String receiverId, LifeNotice lifeNotice) {
        try {
            WebSocketVo webSocketVo = new WebSocketVo();
            webSocketVo.setSenderId(SYSTEM_SENDER_ID);
            webSocketVo.setReceiverId(receiverId);
            webSocketVo.setCategory("notice");
            webSocketVo.setNoticeType("1");
            webSocketVo.setIsRead(IS_READ_UNREAD);
            webSocketVo.setText(JSON.toJSONString(lifeNotice));
            webSocketProcess.sendMessage(receiverId, JSON.toJSONString(webSocketVo));
            log.debug("发送WebSocket消息成功，接收人ID={}", receiverId);
        } catch (Exception e) {
            log.error("发送WebSocket消息异常，接收人ID={}, 异常信息={}", receiverId, e.getMessage(), e);
        }
    }
}

