package shop.alien.lawyer.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LawyerUser;
import shop.alien.entity.store.vo.LawyerDashboardVO;
import shop.alien.entity.store.vo.LawyerOrderStatisticsVO;
import shop.alien.lawyer.service.LawyerStatisticsService;
import shop.alien.lawyer.service.LawyerUserService;
import shop.alien.mapper.LawyerConsultationOrderMapper;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Map;

/**
 * 律师统计 服务实现类
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LawyerStatisticsServiceImpl implements LawyerStatisticsService {

    private final LawyerConsultationOrderMapper lawyerConsultationOrderMapper;
    private final LawyerUserService lawyerUserService;

    /**
     * 金额单位转换：分转元
     */
    private static final int FEN_TO_YUAN = 100;

    /**
     * 日期时间格式
     */
    private static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

    /**
     * 默认小数位数
     */
    private static final int DECIMAL_SCALE = 2;

    /**
     * 默认订单数量（当查询结果为空时）
     */
    private static final Integer DEFAULT_ORDER_COUNT = 0;

    /**
     * 默认收益金额（当查询结果为空时）
     */
    private static final BigDecimal DEFAULT_REVENUE = BigDecimal.ZERO;

    /**
     * Map key：订单数量
     */
    private static final String KEY_ORDER_COUNT = "orderCount";

    /**
     * Map key：总金额
     */
    private static final String KEY_TOTAL_AMOUNT = "totalAmount";

    /**
     * Map key：本月订单量
     */
    private static final String KEY_MONTH_ORDER_COUNT = "monthOrderCount";

    /**
     * Map key：本月收益
     */
    private static final String KEY_MONTH_REVENUE = "monthRevenue";

    /**
     * Map key：总订单量
     */
    private static final String KEY_TOTAL_ORDER_COUNT = "totalOrderCount";

    /**
     * Map key：总收益
     */
    private static final String KEY_TOTAL_REVENUE = "totalRevenue";

    /**
     * 日期格式化器
     */
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern(DATE_TIME_PATTERN);

    /**
     * 获取律师订单统计数据
     * <p>
     * 统计律师的订单数据，包括：
     * 1. 本月订单量和本月收益
     * 2. 总订单量和总收益
     * 3. 进行中订单统计
     * 4. 待接单订单统计
     * 5. 已退款订单统计
     * </p>
     * <p>
     * 处理流程：
     * 1. 参数校验：律师用户ID必须大于0
     * 2. 查询本月统计数据（订单量、收益）
     * 3. 查询总统计数据（订单量、收益）
     * 4. 查询各状态订单统计数据（进行中、待接单、已退款）
     * 5. 组装并返回统计数据
     * </p>
     *
     * @param lawyerUserId 律师用户ID，必须大于0
     * @return 订单统计数据，包含本月数据、总数据和各状态订单统计
     * @throws IllegalArgumentException 当律师用户ID无效时抛出
     * @throws RuntimeException        当查询异常时抛出
     * @author system
     * @since 2025-01-XX
     */
    @Override
    public R<LawyerOrderStatisticsVO> getOrderStatistics(Integer lawyerUserId) {
        log.info("获取律师订单统计数据开始，lawyerUserId={}", lawyerUserId);

        // 参数校验
        validateLawyerUserId(lawyerUserId);

        try {
            // 创建统计对象
            LawyerOrderStatisticsVO statistics = createStatisticsVO();

            // 构建统计数据
            buildStatisticsData(statistics, lawyerUserId);

            // 记录成功日志
            logStatisticsSuccess(lawyerUserId, statistics);

            return R.data(statistics);
        } catch (IllegalArgumentException e) {
            log.warn("获取律师订单统计数据参数校验失败，lawyerUserId={}，错误信息：{}", lawyerUserId, e.getMessage());
            return R.fail(e.getMessage());
        } catch (RuntimeException e) {
            log.error("获取律师订单统计数据异常，lawyerUserId={}，异常信息：{}", lawyerUserId, e.getMessage(), e);
            return R.fail("获取统计数据失败：" + e.getMessage());
        } catch (Exception e) {
            log.error("获取律师订单统计数据未知异常，lawyerUserId={}，异常信息：{}", lawyerUserId, e.getMessage(), e);
            return R.fail("获取统计数据失败，请稍后重试");
        }
    }

    /**
     * 校验律师用户ID
     * <p>
     * 检查律师用户ID是否为空或无效
     * </p>
     *
     * @param lawyerUserId 律师用户ID
     * @throws IllegalArgumentException 当律师用户ID为空或无效时抛出
     */
    private void validateLawyerUserId(Integer lawyerUserId) {
        if (lawyerUserId == null) {
            log.warn("获取律师订单统计数据参数校验失败：律师用户ID为null");
            throw new IllegalArgumentException("律师用户ID不能为空");
        }

        if (lawyerUserId <= 0) {
            log.warn("获取律师订单统计数据参数校验失败：律师用户ID无效，lawyerUserId={}", lawyerUserId);
            throw new IllegalArgumentException("律师用户ID必须大于0");
        }
    }

    /**
     * 创建统计数据VO对象
     * <p>
     * 初始化统计数据对象
     * </p>
     *
     * @return 统计数据VO对象
     */
    private LawyerOrderStatisticsVO createStatisticsVO() {
        return new LawyerOrderStatisticsVO();
    }

    /**
     * 构建统计数据
     * <p>
     * 构建所有统计数据，包括本月数据、总数据和各状态订单统计
     * </p>
     *
     * @param statistics   统计数据VO对象
     * @param lawyerUserId 律师用户ID
     */
    private void buildStatisticsData(LawyerOrderStatisticsVO statistics, Integer lawyerUserId) {
        // 统计本月数据
        buildMonthStatistics(statistics, lawyerUserId);

        // 统计总数据
        buildTotalStatistics(statistics, lawyerUserId);

        // 统计各状态订单数据
        buildOrderStatusStatistics(statistics, lawyerUserId);
    }

    /**
     * 构建各状态订单统计数据
     * <p>
     * 统计进行中、待接单、已退款订单的统计信息
     * </p>
     *
     * @param statistics   统计数据VO对象
     * @param lawyerUserId 律师用户ID
     */
    private void buildOrderStatusStatistics(LawyerOrderStatisticsVO statistics, Integer lawyerUserId) {
        // 统计进行中订单
        statistics.setInProgressOrder(queryAndBuildOrderStatusStatistics(
                lawyerUserId, StatisticsType.IN_PROGRESS));

        // 统计待接单订单
        statistics.setPendingAcceptOrder(queryAndBuildOrderStatusStatistics(
                lawyerUserId, StatisticsType.PENDING_ACCEPT));

        // 统计已退款订单
        statistics.setRefundedOrder(queryAndBuildOrderStatusStatistics(
                lawyerUserId, StatisticsType.REFUNDED));
    }

    /**
     * 查询并构建订单状态统计数据
     * <p>
     * 根据统计类型查询对应的统计数据并构建返回对象
     * </p>
     *
     * @param lawyerUserId   律师用户ID
     * @param statisticsType 统计类型
     * @return 订单状态统计对象
     */
    private LawyerOrderStatisticsVO.OrderStatusStatistics queryAndBuildOrderStatusStatistics(
            Integer lawyerUserId, StatisticsType statisticsType) {
        try {
            Map<String, Object> statsMap = queryOrderStatusStatistics(lawyerUserId, statisticsType);
            return buildOrderStatusStatistics(statsMap);
        } catch (Exception e) {
            log.error("查询订单状态统计数据异常，lawyerUserId={}, statisticsType={}，异常信息：{}",
                    lawyerUserId, statisticsType, e.getMessage(), e);
            // 异常时返回默认值，避免影响主流程
            return createDefaultOrderStatusStatistics();
        }
    }

    /**
     * 查询订单状态统计数据
     * <p>
     * 根据统计类型调用对应的Mapper方法查询统计数据
     * </p>
     *
     * @param lawyerUserId   律师用户ID
     * @param statisticsType 统计类型
     * @return 统计数据Map
     */
    private Map<String, Object> queryOrderStatusStatistics(Integer lawyerUserId, StatisticsType statisticsType) {
        switch (statisticsType) {
            case IN_PROGRESS:
                return lawyerConsultationOrderMapper.getInProgressStatistics(lawyerUserId);
            case PENDING_ACCEPT:
                return lawyerConsultationOrderMapper.getPendingAcceptStatistics(lawyerUserId);
            case REFUNDED:
                return lawyerConsultationOrderMapper.getRefundedStatistics(lawyerUserId);
            default:
                log.warn("未知的统计类型，statisticsType={}", statisticsType);
                return null;
        }
    }

    /**
     * 创建默认订单状态统计对象
     * <p>
     * 当查询异常或结果为空时返回默认值
     * </p>
     *
     * @return 默认订单状态统计对象
     */
    private LawyerOrderStatisticsVO.OrderStatusStatistics createDefaultOrderStatusStatistics() {
        LawyerOrderStatisticsVO.OrderStatusStatistics orderStatusStatistics =
                new LawyerOrderStatisticsVO.OrderStatusStatistics();
        orderStatusStatistics.setOrderCount(DEFAULT_ORDER_COUNT);
        orderStatusStatistics.setTotalAmount(DEFAULT_REVENUE);
        return orderStatusStatistics;
    }

    /**
     * 记录统计成功日志
     * <p>
     * 记录统计数据的关键信息，便于问题排查
     * </p>
     *
     * @param lawyerUserId 律师用户ID
     * @param statistics   统计数据VO对象
     */
    private void logStatisticsSuccess(Integer lawyerUserId, LawyerOrderStatisticsVO statistics) {
        log.info("获取律师订单统计数据成功，lawyerUserId={}, monthOrderCount={}, monthRevenue={}, "
                        + "totalOrderCount={}, totalRevenue={}, inProgressCount={}, pendingAcceptCount={}, refundedCount={}",
                lawyerUserId,
                statistics.getMonthOrderCount(),
                statistics.getMonthRevenue(),
                statistics.getTotalOrderCount(),
                statistics.getTotalRevenue(),
                statistics.getInProgressOrder() != null ? statistics.getInProgressOrder().getOrderCount() : 0,
                statistics.getPendingAcceptOrder() != null ? statistics.getPendingAcceptOrder().getOrderCount() : 0,
                statistics.getRefundedOrder() != null ? statistics.getRefundedOrder().getOrderCount() : 0);
    }

    /**
     * 构建本月统计数据
     * <p>
     * 查询并设置本月的订单量和收益数据
     * </p>
     *
     * @param statistics   统计对象
     * @param lawyerUserId 律师用户ID
     */
    private void buildMonthStatistics(LawyerOrderStatisticsVO statistics, Integer lawyerUserId) {
        try {
            // 获取当前月份时间范围
            String[] timeRange = getCurrentMonthTimeRange();

            // 查询本月统计数据
            Map<String, Object> monthStats = queryMonthStatistics(lawyerUserId, timeRange);

            // 设置统计数据
            setMonthStatisticsFromMap(statistics, monthStats);

            log.debug("构建本月统计数据成功，lawyerUserId={}, monthOrderCount={}, monthRevenue={}",
                    lawyerUserId, statistics.getMonthOrderCount(), statistics.getMonthRevenue());
        } catch (Exception e) {
            log.error("构建本月统计数据异常，lawyerUserId={}，异常信息：{}", lawyerUserId, e.getMessage(), e);
            // 异常时设置默认值，避免影响主流程
            setDefaultMonthStatistics(statistics);
        }
    }

    /**
     * 查询本月统计数据
     * <p>
     * 调用Mapper方法查询本月的订单量和收益
     * </p>
     *
     * @param lawyerUserId 律师用户ID
     * @param timeRange    时间范围数组，[0]为开始时间，[1]为结束时间
     * @return 统计数据Map
     */
    private Map<String, Object> queryMonthStatistics(Integer lawyerUserId, String[] timeRange) {
        return lawyerConsultationOrderMapper.getMonthStatistics(
                lawyerUserId, timeRange[0], timeRange[1]);
    }

    /**
     * 从Map中设置本月统计数据
     * <p>
     * 将查询结果Map转换为统计数据并设置到VO对象中
     * </p>
     *
     * @param statistics 统计对象
     * @param monthStats 本月统计数据Map
     */
    private void setMonthStatisticsFromMap(LawyerOrderStatisticsVO statistics, Map<String, Object> monthStats) {
        if (monthStats != null) {
            statistics.setMonthOrderCount(getIntegerValue(monthStats.get(KEY_MONTH_ORDER_COUNT)));
            Long monthRevenueFen = getLongValue(monthStats.get(KEY_MONTH_REVENUE));
            statistics.setMonthRevenue(convertFenToYuan(monthRevenueFen));
        } else {
            setDefaultMonthStatistics(statistics);
        }
    }

    /**
     * 设置默认本月统计数据
     * <p>
     * 当查询结果为空时设置默认值
     * </p>
     *
     * @param statistics 统计对象
     */
    private void setDefaultMonthStatistics(LawyerOrderStatisticsVO statistics) {
        statistics.setMonthOrderCount(DEFAULT_ORDER_COUNT);
        statistics.setMonthRevenue(DEFAULT_REVENUE);
    }

    /**
     * 构建总统计数据
     * <p>
     * 查询并设置总订单量和总收益数据
     * </p>
     *
     * @param statistics   统计对象
     * @param lawyerUserId 律师用户ID
     */
    private void buildTotalStatistics(LawyerOrderStatisticsVO statistics, Integer lawyerUserId) {
        try {
            // 查询总统计数据
            Map<String, Object> totalStats = queryTotalStatistics(lawyerUserId);

            // 设置统计数据
            setTotalStatisticsFromMap(statistics, totalStats);

            log.debug("构建总统计数据成功，lawyerUserId={}, totalOrderCount={}, totalRevenue={}",
                    lawyerUserId, statistics.getTotalOrderCount(), statistics.getTotalRevenue());
        } catch (Exception e) {
            log.error("构建总统计数据异常，lawyerUserId={}，异常信息：{}", lawyerUserId, e.getMessage(), e);
            // 异常时设置默认值，避免影响主流程
            setDefaultTotalStatistics(statistics);
        }
    }

    /**
     * 查询总统计数据
     * <p>
     * 调用Mapper方法查询总的订单量和收益
     * </p>
     *
     * @param lawyerUserId 律师用户ID
     * @return 统计数据Map
     */
    private Map<String, Object> queryTotalStatistics(Integer lawyerUserId) {
        return lawyerConsultationOrderMapper.getTotalStatistics(lawyerUserId);
    }

    /**
     * 从Map中设置总统计数据
     * <p>
     * 将查询结果Map转换为统计数据并设置到VO对象中
     * </p>
     *
     * @param statistics 统计对象
     * @param totalStats 总统计数据Map
     */
    private void setTotalStatisticsFromMap(LawyerOrderStatisticsVO statistics, Map<String, Object> totalStats) {
        if (totalStats != null) {
            statistics.setTotalOrderCount(getIntegerValue(totalStats.get(KEY_TOTAL_ORDER_COUNT)));
            Long totalRevenueFen = getLongValue(totalStats.get(KEY_TOTAL_REVENUE));
            statistics.setTotalRevenue(convertFenToYuan(totalRevenueFen));
        } else {
            setDefaultTotalStatistics(statistics);
        }
    }

    /**
     * 设置默认总统计数据
     * <p>
     * 当查询结果为空时设置默认值
     * </p>
     *
     * @param statistics 统计对象
     */
    private void setDefaultTotalStatistics(LawyerOrderStatisticsVO statistics) {
        statistics.setTotalOrderCount(DEFAULT_ORDER_COUNT);
        statistics.setTotalRevenue(DEFAULT_REVENUE);
    }

    /**
     * 构建订单状态统计数据
     * <p>
     * 将查询结果Map转换为订单状态统计对象
     * </p>
     *
     * @param statsMap 统计数据Map，可能为null
     * @return 订单状态统计对象，如果statsMap为null则返回默认值
     */
    private LawyerOrderStatisticsVO.OrderStatusStatistics buildOrderStatusStatistics(
            Map<String, Object> statsMap) {
        LawyerOrderStatisticsVO.OrderStatusStatistics orderStatusStatistics =
                new LawyerOrderStatisticsVO.OrderStatusStatistics();

        if (statsMap != null) {
            // 设置订单数量
            Integer orderCount = getIntegerValue(statsMap.get(KEY_ORDER_COUNT));
            orderStatusStatistics.setOrderCount(orderCount);

            // 设置总金额（分转元）
            Long amountFen = getLongValue(statsMap.get(KEY_TOTAL_AMOUNT));
            BigDecimal totalAmount = convertFenToYuan(amountFen);
            orderStatusStatistics.setTotalAmount(totalAmount);

            log.debug("构建订单状态统计数据成功，orderCount={}, totalAmount={}", orderCount, totalAmount);
        } else {
            // 设置默认值
            orderStatusStatistics.setOrderCount(DEFAULT_ORDER_COUNT);
            orderStatusStatistics.setTotalAmount(DEFAULT_REVENUE);
            log.debug("订单状态统计数据为空，设置默认值");
        }

        return orderStatusStatistics;
    }

    /**
     * 获取当前月份的时间范围
     * <p>
     * 计算当前月份的第一天00:00:00到下个月第一天的00:00:00的时间范围
     * </p>
     *
     * @return 时间范围数组，[0]为开始时间（本月第一天00:00:00），[1]为结束时间（下月第一天00:00:00）
     */
    private String[] getCurrentMonthTimeRange() {
        try {
            // 获取当前日期
            LocalDate now = LocalDate.now();

            // 计算本月第一天
            LocalDate firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth());

            // 计算下月第一天
            LocalDate firstDayOfNextMonth = now.with(TemporalAdjusters.firstDayOfNextMonth());

            // 转换为日期时间（开始时间为00:00:00，结束时间为00:00:00）
            LocalDateTime startDateTime = firstDayOfMonth.atStartOfDay();
            LocalDateTime endDateTime = firstDayOfNextMonth.atStartOfDay();

            // 格式化为字符串
            String startTimeStr = startDateTime.format(DATE_TIME_FORMATTER);
            String endTimeStr = endDateTime.format(DATE_TIME_FORMATTER);

            log.debug("计算当前月份时间范围，startTime={}, endTime={}", startTimeStr, endTimeStr);

            return new String[]{startTimeStr, endTimeStr};
        } catch (Exception e) {
            log.error("计算当前月份时间范围异常，异常信息：{}", e.getMessage(), e);
            throw new RuntimeException("计算月份时间范围失败：" + e.getMessage(), e);
        }
    }

    /**
     * 将分转换为元（保留2位小数）
     * <p>
     * 将金额从分转换为元，保留2位小数，使用四舍五入方式
     * </p>
     *
     * @param fen 金额（分），单位：分，可能为null或0
     * @return 金额（元），单位：元，保留2位小数，如果fen为null或0则返回BigDecimal.ZERO
     */
    private BigDecimal convertFenToYuan(Long fen) {
        if (fen == null) {
            log.debug("转换分转元：金额为null，返回0");
            return DEFAULT_REVENUE;
        }

        if (fen == 0) {
            log.debug("转换分转元：金额为0，返回0");
            return DEFAULT_REVENUE;
        }

        if (fen < 0) {
            log.warn("转换分转元：金额为负数，fen={}，返回0", fen);
            return DEFAULT_REVENUE;
        }

        try {
            BigDecimal yuan = BigDecimal.valueOf(fen)
                    .divide(BigDecimal.valueOf(FEN_TO_YUAN), DECIMAL_SCALE, RoundingMode.HALF_UP);
            log.debug("转换分转元成功，fen={}, yuan={}", fen, yuan);
            return yuan;
        } catch (Exception e) {
            log.error("转换分转元异常，fen={}，异常信息：{}", fen, e.getMessage(), e);
            // 异常时返回默认值
            return DEFAULT_REVENUE;
        }
    }

    /**
     * 从Map中获取Integer值
     * <p>
     * 支持Integer、Long、Number类型的转换
     * 如果value为null或无法转换，则返回默认值0
     * </p>
     *
     * @param value 对象值，可能为Integer、Long或其他Number类型
     * @return Integer值，如果value为null或无法转换则返回默认值0
     */
    private Integer getIntegerValue(Object value) {
        if (value == null) {
            log.debug("从Map获取Integer值：值为null，返回默认值0");
            return DEFAULT_ORDER_COUNT;
        }

        // 优先处理Integer类型
        if (value instanceof Integer) {
            Integer result = (Integer) value;
            log.debug("从Map获取Integer值成功，value={}, type=Integer", result);
            return result;
        }

        // 处理Long类型
        if (value instanceof Long) {
            Integer result = ((Long) value).intValue();
            log.debug("从Map获取Integer值成功，value={}, type=Long, converted={}", value, result);
            return result;
        }

        // 处理其他Number类型
        if (value instanceof Number) {
            Integer result = ((Number) value).intValue();
            log.debug("从Map获取Integer值成功，value={}, type={}, converted={}",
                    value, value.getClass().getSimpleName(), result);
            return result;
        }

        // 无法转换的类型
        log.warn("无法将对象转换为Integer，value={}, type={}，返回默认值0",
                value, value.getClass().getName());
        return DEFAULT_ORDER_COUNT;
    }

    /**
     * 从Map中获取Long值
     * <p>
     * 支持Long、Integer、Number类型的转换
     * 如果value为null或无法转换，则返回默认值0L
     * </p>
     *
     * @param value 对象值，可能为Long、Integer或其他Number类型
     * @return Long值，如果value为null或无法转换则返回默认值0L
     */
    private Long getLongValue(Object value) {
        if (value == null) {
            log.debug("从Map获取Long值：值为null，返回默认值0L");
            return 0L;
        }

        // 优先处理Long类型
        if (value instanceof Long) {
            Long result = (Long) value;
            log.debug("从Map获取Long值成功，value={}, type=Long", result);
            return result;
        }

        // 处理Integer类型
        if (value instanceof Integer) {
            Long result = ((Integer) value).longValue();
            log.debug("从Map获取Long值成功，value={}, type=Integer, converted={}", value, result);
            return result;
        }

        // 处理其他Number类型
        if (value instanceof Number) {
            Long result = ((Number) value).longValue();
            log.debug("从Map获取Long值成功，value={}, type={}, converted={}",
                    value, value.getClass().getSimpleName(), result);
            return result;
        }

        // 无法转换的类型
        log.warn("无法将对象转换为Long，value={}, type={}，返回默认值0L",
                value, value.getClass().getName());
        return 0L;
    }

    /**
     * 统计类型枚举
     * <p>
     * 用于区分不同的订单状态统计类型
     * </p>
     */
    private enum StatisticsType {
        /**
         * 进行中订单统计
         */
        IN_PROGRESS,

        /**
         * 待接单订单统计
         */
        PENDING_ACCEPT,

        /**
         * 已退款订单统计
         */
        REFUNDED
    }

    @Override
    public R<LawyerDashboardVO> getLawyerDashboard(Integer lawyerUserId) {
        log.info("获取律师仪表板数据开始，lawyerUserId={}", lawyerUserId);

        // 参数校验
        if (lawyerUserId == null || lawyerUserId <= 0) {
            log.warn("获取律师仪表板数据失败：律师用户ID为空或无效，lawyerUserId={}", lawyerUserId);
            return R.fail("律师用户ID不能为空");
        }

        try {
            LawyerDashboardVO dashboard = new LawyerDashboardVO();

            // 获取律师基本信息
            LawyerUser lawyer = lawyerUserService.getById(lawyerUserId);
            if (lawyer == null || lawyer.getDeleteFlag() == 1) {
                log.warn("获取律师仪表板数据失败：律师不存在，lawyerUserId={}", lawyerUserId);
                return R.fail("律师不存在");
            }

            // 设置律师基本信息
            dashboard.setLawyerId(lawyer.getId());
            dashboard.setName(lawyer.getName() != null ? lawyer.getName() : "");
            dashboard.setAvatar(lawyer.getHeadImg() != null ? lawyer.getHeadImg() : "");
            dashboard.setServiceFields(lawyer.getSpecialtyFields() != null ? lawyer.getSpecialtyFields() : "");

            // 统计本月数据
            buildMonthStatisticsForDashboard(dashboard, lawyerUserId);

            // 统计总数据
            buildTotalStatisticsForDashboard(dashboard, lawyerUserId);

            // 统计进行中订单
            dashboard.setInProgressOrder(buildOrderStatusInfo(
                    lawyerConsultationOrderMapper.getInProgressStatistics(lawyerUserId)));

            // 统计待接单订单
            dashboard.setPendingAcceptOrder(buildOrderStatusInfo(
                    lawyerConsultationOrderMapper.getPendingAcceptStatistics(lawyerUserId)));

            // 统计已退款订单
            dashboard.setRefundedOrder(buildOrderStatusInfo(
                    lawyerConsultationOrderMapper.getRefundedStatistics(lawyerUserId)));

            log.info("获取律师仪表板数据成功，lawyerUserId={}, name={}, monthOrderCount={}, monthRevenue={}, "
                            + "totalOrderCount={}, totalRevenue={}",
                    lawyerUserId, dashboard.getName(), dashboard.getMonthOrderCount(), dashboard.getMonthRevenue(),
                    dashboard.getTotalOrderCount(), dashboard.getTotalRevenue());

            return R.data(dashboard);
        } catch (RuntimeException e) {
            log.error("获取律师仪表板数据异常，lawyerUserId={}", lawyerUserId, e);
            return R.fail("获取仪表板数据失败：" + e.getMessage());
        }
    }

    /**
     * 构建本月统计数据（用于仪表板）
     *
     * @param dashboard   仪表板对象
     * @param lawyerUserId 律师用户ID
     */
    private void buildMonthStatisticsForDashboard(LawyerDashboardVO dashboard, Integer lawyerUserId) {
        String[] timeRange = getCurrentMonthTimeRange();
        Map<String, Object> monthStats = lawyerConsultationOrderMapper.getMonthStatistics(
                lawyerUserId, timeRange[0], timeRange[1]);

        if (monthStats != null) {
            dashboard.setMonthOrderCount(getIntegerValue(monthStats.get(KEY_MONTH_ORDER_COUNT)));
            Long monthRevenueFen = getLongValue(monthStats.get(KEY_MONTH_REVENUE));
            dashboard.setMonthRevenue(convertFenToYuan(monthRevenueFen));
        } else {
            dashboard.setMonthOrderCount(0);
            dashboard.setMonthRevenue(BigDecimal.ZERO);
        }
    }

    /**
     * 构建总统计数据（用于仪表板）
     *
     * @param dashboard   仪表板对象
     * @param lawyerUserId 律师用户ID
     */
    private void buildTotalStatisticsForDashboard(LawyerDashboardVO dashboard, Integer lawyerUserId) {
        Map<String, Object> totalStats = lawyerConsultationOrderMapper.getTotalStatistics(lawyerUserId);

        if (totalStats != null) {
            dashboard.setTotalOrderCount(getIntegerValue(totalStats.get(KEY_TOTAL_ORDER_COUNT)));
            Long totalRevenueFen = getLongValue(totalStats.get(KEY_TOTAL_REVENUE));
            dashboard.setTotalRevenue(convertFenToYuan(totalRevenueFen));
        } else {
            dashboard.setTotalOrderCount(0);
            dashboard.setTotalRevenue(BigDecimal.ZERO);
        }
    }

    /**
     * 构建订单状态信息（用于仪表板）
     *
     * @param statsMap 统计数据Map
     * @return 订单状态信息对象
     */
    private LawyerDashboardVO.OrderStatusInfo buildOrderStatusInfo(Map<String, Object> statsMap) {
        LawyerDashboardVO.OrderStatusInfo orderStatusInfo = new LawyerDashboardVO.OrderStatusInfo();

        if (statsMap != null) {
            orderStatusInfo.setOrderCount(getIntegerValue(statsMap.get(KEY_ORDER_COUNT)));
            Long amountFen = getLongValue(statsMap.get(KEY_TOTAL_AMOUNT));
            orderStatusInfo.setTotalAmount(convertFenToYuan(amountFen));
        } else {
            orderStatusInfo.setOrderCount(0);
            orderStatusInfo.setTotalAmount(BigDecimal.ZERO);
        }

        return orderStatusInfo;
    }
}

