package shop.alien.store.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
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.core.toolkit.StringUtils;
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.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.StoreStaffReviewDto;
import shop.alien.entity.store.vo.*;
import shop.alien.mapper.*;
import shop.alien.store.service.StoreStaffCommentService;
import shop.alien.store.service.StoreStaffReviewService;
import shop.alien.store.util.ai.AiContentModerationUtil;
import shop.alien.store.util.StoreLikeRecordIdentityHelper;
import shop.alien.store.util.StoreLikeRecordIdentityHelper.StoreLikerScope;
import shop.alien.util.common.DistanceUtil;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 员工评价 服务实现类
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Transactional
@Service
@RequiredArgsConstructor
public class StoreStaffReviewServiceImpl extends ServiceImpl<StoreStaffReviewMapper, StoreStaffReview> implements StoreStaffReviewService {

    private static final String LIKE_TYPE_REVIEW = "9"; // 员工评价点赞类型

    private final StoreStaffReviewMapper storeStaffReviewMapper;
    private final StoreStaffCommentService storeStaffCommentService;
    private final StoreStaffCommentMapper storeStaffCommentMapper;
    private final LifeLikeRecordMapper lifeLikeRecordMapper;
    private final StoreLikeRecordIdentityHelper lifeLikeIdentityHelper;
    private final StoreStaffConfigMapper storeStaffConfigMapper;
    private final StoreInfoMapper storeInfoMapper;
    private final StoreUserMapper storeUserMapper;
    private final AiContentModerationUtil aiContentModerationUtil;

    @Override
    public R<StoreStaffReview> createReview(StoreStaffReviewDto reviewDto) {
        log.info("创建员工评价, reviewDto={}", reviewDto);

        // 参数校验
        R<String> validateResult = validateReviewDto(reviewDto);
        if (!validateResult.isSuccess()) {
            return R.fail(validateResult.getMsg());
        }

        // 先审文本再入库：AI 不通过不落库，不计入评价/后续评论数等
        if (StringUtils.isNotEmpty(reviewDto.getReviewContent())) {
            AiContentModerationUtil.AuditResult auditResult =
                    aiContentModerationUtil.auditContent(reviewDto.getReviewContent(), null);
            if (!auditResult.isPassed()) {
                String displayReason = buildAiTextAuditFailMessage(auditResult.getFailureReason());
                log.warn("员工评价AI文本审核未通过, 未写入评价表, rawReason={}, displayReason={}",
                        auditResult.getFailureReason(), displayReason);
                return R.fail(displayReason);
            }
        }

        StoreStaffReview review = buildReviewFromDto(reviewDto);
        boolean success = this.save(review);
        if (!success) {
            log.error("创建评价失败，入库失败");
            return R.fail("创建评价失败");
        }

        StoreStaffReview approved = this.getById(review.getId());
        if (approved != null) {
            approved.setAuditStatus(1);
            approved.setAuditReason(null);
            this.updateById(approved);
            updateStaffServiceScore(review.getStaffUserId());
        }

        log.info("创建评价成功, 评价ID={}", review.getId());
        StoreStaffReview latest = this.getById(review.getId());
        return R.data(latest != null ? latest : review, "提交成功");
    }

    @Override
    public R<IPage<StoreStaffReviewVo>> getReviewList(int pageNum, int pageSize, Integer staffUserId, Integer userId, Integer currentUserId) {
        log.info("分页查询评价列表, pageNum={}, pageSize={}, staffUserId={}, userId={}, currentUserId={}",
                pageNum, pageSize, staffUserId, userId, currentUserId);

        Page<StoreStaffReviewVo> page = new Page<>(pageNum, pageSize);
        IPage<StoreStaffReviewVo> result = storeStaffReviewMapper.getReviewListWithUser(page, staffUserId, userId, currentUserId);

        // 处理评价图片JSON字符串转换为列表
        result.getRecords().forEach(this::parseReviewImages);

        return R.data(result);
    }

    @Override
    public R<StoreStaffReviewDetailVo> getReviewDetail(Integer reviewId, Integer currentUserId, Double longitude, Double latitude) {
        log.info("获取评价详情, reviewId={}, currentUserId={}, longitude={}, latitude={}", reviewId, currentUserId, longitude, latitude);

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

        // 查询评价详情
        StoreStaffReviewVo reviewVo = storeStaffReviewMapper.getReviewDetailById(reviewId, currentUserId);
        if (reviewVo == null) {
            return R.fail("评价不存在");
        }

        // 处理评价图片
        parseReviewImages(reviewVo);

        // 查询评论列表
        List<StoreStaffCommentVo> comments = storeStaffCommentMapper.getCommentListByReviewId(reviewId, currentUserId);

        // 为每个评论查询回复列表
        if (!CollectionUtils.isEmpty(comments)) {
            comments.forEach(comment -> {
                List<StoreStaffCommentVo> replies = storeStaffCommentMapper.getReplyListByHeadId(comment.getId(), currentUserId);
                comment.setReplyList(replies != null ? replies : new ArrayList<>());
            });
        }

        // 查询人员信息
        StoreStaffConfig staffInfo = null;
        Integer storeId = null;
        if (reviewVo.getStaffUserId() != null) {
            try {
                staffInfo = storeStaffConfigMapper.selectById(reviewVo.getStaffUserId());
                if (staffInfo != null) {
                    storeId = staffInfo.getStoreId();
                }
            } catch (Exception e) {
                log.warn("查询人员信息失败, staffUserId={}, error={}", reviewVo.getStaffUserId(), e.getMessage());
            }
        }

        // 查询店铺信息（包括店铺头像、评分和距离）
        StoreStaffReviewDetailVo.StoreInfoForStaffReviewVo storeInfoVo = null;
        if (storeId != null) {
            try {
                // 查询店铺基本信息
                StoreInfo storeInfo = storeInfoMapper.selectById(storeId);
                if (storeInfo != null) {
                    storeInfoVo = new StoreStaffReviewDetailVo.StoreInfoForStaffReviewVo();
                    storeInfoVo.setStoreId(storeId);
                    storeInfoVo.setStoreName(storeInfo.getStoreName());
                    
                    // 设置店铺评分（平均评分）
                    if (storeInfo.getScoreAvg() != null) {
                        storeInfoVo.setScore(storeInfo.getScoreAvg());
                    } else {
                        storeInfoVo.setScore(null);
                    }
                    
                    // 查询店铺头像（来自store_user表的head_img字段）
                    LambdaQueryWrapper<StoreUser> userWrapper = new LambdaQueryWrapper<>();
                    userWrapper.eq(StoreUser::getStoreId, storeId)
                              .eq(StoreUser::getDeleteFlag, 0);
                    StoreUser storeUser = storeUserMapper.selectOne(userWrapper);
                    if (storeUser != null && storeUser.getHeadImg() != null && !storeUser.getHeadImg().trim().isEmpty()) {
                        storeInfoVo.setHeadImg(storeUser.getHeadImg());
                    } else {
                        storeInfoVo.setHeadImg(null);
                    }
                    
                    // 计算距离（如果提供了用户经纬度）
                    if (longitude != null && latitude != null && storeInfo.getStorePosition() != null && !storeInfo.getStorePosition().trim().isEmpty()) {
                        try {
                            String[] positionArray = storeInfo.getStorePosition().split(",");
                            if (positionArray.length >= 2) {
                                double storeLon = Double.parseDouble(positionArray[0].trim());
                                double storeLat = Double.parseDouble(positionArray[1].trim());
                                // 计算距离（单位：公里）
                                double distanceKm = DistanceUtil.haversineCalculateDistance(longitude, latitude, storeLon, storeLat);
                                storeInfoVo.setDistance(distanceKm);
                            } else {
                                storeInfoVo.setDistance(null);
                            }
                        } catch (Exception e) {
                            log.warn("计算店铺距离失败, storeId={}, error={}", storeId, e.getMessage());
                            storeInfoVo.setDistance(null);
                        }
                    } else {
                        storeInfoVo.setDistance(null);
                    }
                }
            } catch (Exception e) {
                log.warn("查询店铺信息失败, storeId={}, error={}", storeId, e.getMessage());
            }
        }

        // 构建返回结果
        StoreStaffReviewDetailVo detailVo = new StoreStaffReviewDetailVo();
        detailVo.setReview(reviewVo);
        detailVo.setCommentList(comments != null ? comments : new ArrayList<>());
        detailVo.setStaffInfo(staffInfo);
        detailVo.setStoreInfo(storeInfoVo);

        return R.data(detailVo);
    }

    @Override
    public R<Boolean> likeReview(Integer reviewId, Integer userId) {
        log.info("点赞评价, reviewId={}, userId={}", reviewId, userId);

        // 参数校验
        R<String> validateResult = validateLikeParams(reviewId, userId);
        if (!validateResult.isSuccess()) {
            return R.fail(validateResult.getMsg());
        }

        // 验证评价是否存在且已展示通过（与列表、详情 SQL 一致，防止未通过审核的评价仍被点赞刷数）
        StoreStaffReview review = this.getById(reviewId);
        if (review == null || review.getDeleteFlag() == 1) {
            return R.fail("评价不存在或已删除");
        }
        if (review.getAuditStatus() == null || review.getAuditStatus() != 1) {
            return R.fail("评价不存在");
        }

        // 检查是否已点赞
        if (isLiked(reviewId, userId, LIKE_TYPE_REVIEW)) {
            return R.data(true, "已点赞");
        }

        // 执行点赞
        return doLike(reviewId, userId, LIKE_TYPE_REVIEW, review);
    }

    @Override
    public R<Boolean> cancelLikeReview(Integer reviewId, Integer userId) {
        log.info("取消点赞评价, reviewId={}, userId={}", reviewId, userId);

        // 参数校验
        R<String> validateResult = validateLikeParams(reviewId, userId);
        if (!validateResult.isSuccess()) {
            return R.fail(validateResult.getMsg());
        }

        // 执行取消点赞
        return doCancelLike(reviewId, userId, LIKE_TYPE_REVIEW, StoreStaffReview.class);
    }

    @Override
    public R<Boolean> deleteReview(Integer reviewId, Integer userId) {
        log.info("用户删除评价, reviewId={}, userId={}", reviewId, userId);

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

        // 查询评价
        StoreStaffReview 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("管理员删除评价, reviewId={}", reviewId);

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

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

        return deleteReviewInternal(reviewId, null, review);
    }

    /**
     * 校验评价DTO参数
     */
    private R<String> validateReviewDto(StoreStaffReviewDto reviewDto) {
        if (reviewDto == null) {
            return R.fail("评价信息不能为空");
        }
        if (reviewDto.getUserId() == null) {
            return R.fail("用户ID不能为空");
        }
        if (reviewDto.getStaffUserId() == null) {
            return R.fail("员工用户ID不能为空");
        }
        return R.success("校验评论参数成功");
    }

    /**
     * 人员评价走服务端 moderate 文本审核，失败时对用户与库内 audit_reason 统一为「AI审核失败」为主文案。
     */
    private static String buildAiTextAuditFailMessage(String rawReason) {
        if (!org.springframework.util.StringUtils.hasText(rawReason)) {
            return "AI审核失败";
        }
        String t = rawReason.trim();
        if ("审核异常".equals(t)) {
            return "AI审核失败（服务调用异常）";
        }
        return "AI审核失败：" + t;
    }

    /**
     * 构建评价对象
     */
    private StoreStaffReview buildReviewFromDto(StoreStaffReviewDto reviewDto) {
        StoreStaffReview review = new StoreStaffReview();
        review.setUserId(reviewDto.getUserId());
        review.setStaffUserId(reviewDto.getStaffUserId());
        review.setOverallRating(reviewDto.getOverallRating());
        review.setServiceAttitudeRating(reviewDto.getServiceAttitudeRating());
        review.setResponseTimeRating(reviewDto.getResponseTimeRating());
        review.setProfessionalAbilityRating(reviewDto.getProfessionalAbilityRating());
        review.setReviewContent(reviewDto.getReviewContent());
        review.setIsAnonymous(reviewDto.getIsAnonymous() != null ? reviewDto.getIsAnonymous() : 0);
        review.setLikeCount(0);
        review.setCommentCount(0);
        review.setCreatedUserId(reviewDto.getUserId());
        review.setCreatedTime(new Date());

        // 处理评价图片
        if (reviewDto.getReviewImages() != null && !reviewDto.getReviewImages().isEmpty()) {
            JSONArray jsonArray = new JSONArray();
            jsonArray.addAll(reviewDto.getReviewImages());
            review.setReviewImages(jsonArray.toString());
        }

        return review;
    }

    /**
     * 解析评价图片JSON字符串为列表
     */
    private void parseReviewImages(StoreStaffReviewVo vo) {
        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("解析评价图片失败, reviewId={}, error={}", vo.getId(), e.getMessage());
                vo.setReviewImages(new ArrayList<>());
            }
        } else {
            vo.setReviewImages(new ArrayList<>());
        }
    }

    /**
     * 校验点赞参数
     */
    private R<String> validateLikeParams(Integer id, Integer userId) {
        if (id == null) {
            return R.fail("ID不能为空");
        }
        if (userId == null) {
            return R.fail("用户ID不能为空");
        }
        return R.success("校验评论参数成功");
    }

    /**
     * 检查是否已点赞
     */
    private boolean isLiked(Integer targetId, Integer userId, String type) {
        StoreLikerScope likerScope = lifeLikeIdentityHelper.fromLifeUserId(userId);
        LambdaQueryWrapper<LifeLikeRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LifeLikeRecord::getType, type)
                .eq(LifeLikeRecord::getHuifuId, String.valueOf(targetId))
                .eq(LifeLikeRecord::getDeleteFlag, 0);
        lifeLikeIdentityHelper.applyLikerFilter(queryWrapper, likerScope);
        List<LifeLikeRecord> records = lifeLikeRecordMapper.selectList(queryWrapper);
        return !CollectionUtils.isEmpty(records);
    }

    /**
     * 执行点赞操作
     */
    private R<Boolean> doLike(Integer reviewId, Integer userId, String type, StoreStaffReview review) {
        try {
            // 插入点赞记录
            LifeLikeRecord likeRecord = new LifeLikeRecord();
            likeRecord.setDianzanId(String.valueOf(userId));
            lifeLikeIdentityHelper.normalizeBeforeSave(likeRecord);
            likeRecord.setHuifuId(String.valueOf(reviewId));
            likeRecord.setType(type);
            likeRecord.setCreatedTime(new Date());
            likeRecord.setCreatedUserId(userId);
            lifeLikeRecordMapper.insert(likeRecord);

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

            if (result > 0) {
                log.info("点赞成功, reviewId={}", reviewId);
                return R.data(true, "点赞成功");
            } else {
                return R.fail("点赞失败");
            }
        } catch (Exception e) {
            log.error("点赞操作异常, reviewId={}, userId={}, error={}", reviewId, userId, e.getMessage(), e);
            return R.fail("点赞失败");
        }
    }

    /**
     * 执行取消点赞操作
     */
    private <T> R<Boolean> doCancelLike(Integer targetId, Integer userId, String type, Class<T> entityClass) {
        try {
            // 查询点赞记录
            StoreLikerScope likerScope = lifeLikeIdentityHelper.fromLifeUserId(userId);
            LambdaQueryWrapper<LifeLikeRecord> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LifeLikeRecord::getType, type)
                    .eq(LifeLikeRecord::getHuifuId, String.valueOf(targetId))
                    .eq(LifeLikeRecord::getDeleteFlag, 0);
            lifeLikeIdentityHelper.applyLikerFilter(queryWrapper, likerScope);
            List<LifeLikeRecord> records = lifeLikeRecordMapper.selectList(queryWrapper);

            if (CollectionUtils.isEmpty(records)) {
                return R.data(true, "未点赞");
            }

            // 删除点赞记录（逻辑删除）
            records.forEach(record -> lifeLikeRecordMapper.deleteById(record.getId()));

            // 更新点赞数
            if (entityClass == StoreStaffReview.class) {
                LambdaUpdateWrapper<StoreStaffReview> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(StoreStaffReview::getId, targetId);
                updateWrapper.setSql("like_count = GREATEST(0, like_count - 1)");
                storeStaffReviewMapper.update(null, updateWrapper);
            }

            log.info("取消点赞成功, targetId={}", targetId);
            return R.data(true, "取消点赞成功");
        } catch (Exception e) {
            log.error("取消点赞操作异常, targetId={}, userId={}, error={}", targetId, userId, e.getMessage(), e);
            return R.fail("取消点赞失败");
        }
    }

    /**
     * 内部删除评价方法
     */
    private R<Boolean> deleteReviewInternal(Integer reviewId, Integer userId, StoreStaffReview review) {
        // 查询该评价下的所有评论
        LambdaQueryWrapper<StoreStaffComment> commentWrapper = new LambdaQueryWrapper<>();
        commentWrapper.eq(StoreStaffComment::getReviewId, reviewId)
                .eq(StoreStaffComment::getDeleteFlag, 0);
        List<StoreStaffComment> comments = storeStaffCommentService.list(commentWrapper);

        // 保存员工ID，用于后续更新评分
        Integer staffUserId = review.getStaffUserId();

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

        if (num > 0) {
            // 级联删除该评价下的所有评论和回复
            comments.forEach(comment -> deleteCommentAndReplies(comment, userId));

            // 更新员工评分
            updateStaffServiceScore(staffUserId);

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

    /**
     * 更新员工服务评分
     * 计算公式：员工评分 = overallRating平均值 (保留1位小数)
     *
     * @param staffUserId 员工用户ID
     */
    private void updateStaffServiceScore(Integer staffUserId) {
        if (staffUserId == null) {
            log.warn("更新员工评分失败：员工ID为空");
            return;
        }

        try {
            // 计算平均评分（1-5星）
            BigDecimal averageRating = storeStaffReviewMapper.getAverageRatingByStaffUserId(staffUserId);

            BigDecimal serviceScore;
            if (averageRating != null) {
                // 保留1位小数，四舍五入
                serviceScore = averageRating.setScale(1, RoundingMode.HALF_UP);
                // 确保在0-5范围内
                if (serviceScore.compareTo(BigDecimal.ZERO) < 0) {
                    serviceScore = BigDecimal.ZERO;
                } else if (serviceScore.compareTo(new BigDecimal("5.0")) > 0) {
                    serviceScore = new BigDecimal("5.0");
                }
            } else {
                // 如果没有评价，设置为0.0
                serviceScore = BigDecimal.ZERO;
                log.info("员工暂无评价，将评分设置为0.0, 员工ID={}", staffUserId);
            }

            // 更新员工评分
            LambdaUpdateWrapper<StoreStaffConfig> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(StoreStaffConfig::getId, staffUserId);
            updateWrapper.set(StoreStaffConfig::getServiceScore, serviceScore);
            int result = storeStaffConfigMapper.update(null, updateWrapper);

            if (result > 0) {
                log.info("更新员工评分成功, 员工ID={}, 平均评分={}, 服务评分={}", staffUserId, averageRating, serviceScore);
            } else {
                log.warn("更新员工评分失败，员工ID={}", staffUserId);
            }
        } catch (Exception e) {
            log.error("更新员工评分异常，员工ID={}, 错误信息={}", staffUserId, e.getMessage(), e);
        }
    }

    /**
     * 删除评论及其回复
     */
    private void deleteCommentAndReplies(StoreStaffComment comment, Integer userId) {
        // 删除评论下的所有回复（逻辑删除）
        LambdaUpdateWrapper<StoreStaffComment> replyUpdateWrapper = new LambdaUpdateWrapper<>();
        replyUpdateWrapper.eq(StoreStaffComment::getHeadId, comment.getId())
                .eq(StoreStaffComment::getHeadType, 1) // 1表示回复类型
                .eq(StoreStaffComment::getDeleteFlag, 0);
        replyUpdateWrapper.set(StoreStaffComment::getDeleteFlag, 1);
        if (userId != null) {
            replyUpdateWrapper.set(StoreStaffComment::getUpdatedUserId, userId);
        }
        replyUpdateWrapper.set(StoreStaffComment::getUpdatedTime, new Date());
        storeStaffCommentService.update(replyUpdateWrapper);

        // 删除评论
        comment.setDeleteFlag(1);
        if (userId != null) {
            comment.setUpdatedUserId(userId);
        }
        comment.setUpdatedTime(new Date());
        storeStaffCommentService.updateById(comment);
    }

    @Override
    public R<StoreStaffReviewListWithStaffVo> getReviewListByStaffId(int pageNum, int pageSize, Integer staffUserId, Integer currentUserId) {
        log.info("根据人员ID查询评价列表, pageNum={}, pageSize={}, staffUserId={}, currentUserId={}",
                pageNum, pageSize, staffUserId, currentUserId);

        if (staffUserId == null) {
            return R.fail("人员ID不能为空");
        }

        // 查询人员信息
        StoreStaffConfig staffInfo = null;
        try {
            staffInfo = storeStaffConfigMapper.selectById(staffUserId);
            if (staffInfo == null) {
                log.warn("人员信息不存在, staffUserId={}", staffUserId);
            }
        } catch (Exception e) {
            log.warn("查询人员信息失败, staffUserId={}, error={}", staffUserId, e.getMessage());
        }

        // 查询评价列表
        Page<StoreStaffReviewVo> page = new Page<>(pageNum, pageSize);
        IPage<StoreStaffReviewVo> reviewList = storeStaffReviewMapper.getReviewListWithUser(page, staffUserId, null, currentUserId);

        // 处理评价图片JSON字符串转换为列表
        reviewList.getRecords().forEach(this::parseReviewImages);

        // 构建返回结果
        StoreStaffReviewListWithStaffVo result = new StoreStaffReviewListWithStaffVo();
        result.setStaffInfo(staffInfo);
        result.setReviewList(reviewList);

        return R.data(result);
    }

    @Override
    public R<StoreStaffReviewStatisticsVo> getStaffReviewStatistics(Integer staffUserId) {
        log.info("获取员工评价统计数据, staffUserId={}", staffUserId);

        if (staffUserId == null) {
            return R.fail("员工ID不能为空");
        }

        try {
            StoreStaffReviewStatisticsVo statistics = new StoreStaffReviewStatisticsVo();

            // 统计全部评价数量
            Integer totalCount = storeStaffReviewMapper.getTotalReviewCountByStaffUserId(staffUserId);
            statistics.setTotalCount(totalCount != null ? totalCount : 0);

            // 统计好评数量
            Integer goodCount = storeStaffReviewMapper.getGoodReviewCountByStaffUserId(staffUserId);
            statistics.setGoodCount(goodCount != null ? goodCount : 0);

            // 统计中评数量
            Integer mediumCount = storeStaffReviewMapper.getMediumReviewCountByStaffUserId(staffUserId);
            statistics.setMediumCount(mediumCount != null ? mediumCount : 0);

            // 统计差评数量
            Integer badCount = storeStaffReviewMapper.getBadReviewCountByStaffUserId(staffUserId);
            statistics.setBadCount(badCount != null ? badCount : 0);

            // 统计有图评价数量
            Integer imageCount = storeStaffReviewMapper.getImageReviewCountByStaffUserId(staffUserId);
            statistics.setImageCount(imageCount != null ? imageCount : 0);

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

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

    @Override
    public R<IPage<StoreStaffReviewVo>> getReviewListByStaffAndType(int pageNum, int pageSize, Integer staffUserId, Integer type, Integer currentUserId) {
        log.info("根据员工ID和类型分页查询评价列表, pageNum={}, pageSize={}, staffUserId={}, type={}, currentUserId={}",
                pageNum, pageSize, staffUserId, type, currentUserId);

        if (staffUserId == null) {
            return R.fail("员工ID不能为空");
        }

        Page<StoreStaffReviewVo> page = new Page<>(pageNum, pageSize);
        IPage<StoreStaffReviewVo> result = storeStaffReviewMapper.getReviewListByStaffAndType(page, staffUserId, type, currentUserId);

        // 处理评价图片JSON字符串转换为列表
        if (result.getRecords() != null) {
            for (StoreStaffReviewVo 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);
    }
}
