package com.dora.service.impl;

import com.dora.dto.AdminOrderDto;
import com.dora.dto.ApiResponse;
import com.dora.entity.Order;
import com.dora.entity.MembershipPlan;
import com.dora.entity.User;
import com.dora.mapper.OrderMapper;
import com.dora.mapper.OrderMapper.AdminOrderInfo;
import com.dora.mapper.MembershipPlanMapper;
import com.dora.mapper.UserMapper;
import com.dora.service.AdminOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员订单管理服务实现
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class AdminOrderServiceImpl implements AdminOrderService {

    private final OrderMapper orderMapper;
    private final MembershipPlanMapper membershipPlanMapper;
    private final UserMapper userMapper;

    @Override
    public ApiResponse<AdminOrderDto.OrderListResponse> getOrderList(AdminOrderDto.OrderListRequest request) {
        try {
            log.info("获取订单列表，请求参数：{}", request);

            // 参数校验和设置默认值
            if (request.getPage() == null || request.getPage() < 1) {
                request.setPage(1);
            }
            if (request.getSize() == null || request.getSize() < 1 || request.getSize() > 100) {
                request.setSize(20); // 限制每页最大100条，防止性能问题
            }
            
            // 验证排序字段安全性
            if (request.getSortField() != null && !isValidSortField(request.getSortField())) {
                log.warn("无效的排序字段: {}", request.getSortField());
                request.setSortField("create_time"); // 设置默认排序字段
            }
            
            // 验证排序方向
            if (request.getSortOrder() != null && 
                !("asc".equalsIgnoreCase(request.getSortOrder()) || "desc".equalsIgnoreCase(request.getSortOrder()))) {
                log.warn("无效的排序方向: {}", request.getSortOrder());
                request.setSortOrder("desc"); // 设置默认排序方向
            }

            // 验证并处理搜索关键词长度
            if (request.getKeyword() != null && request.getKeyword().length() > 100) {
                log.warn("搜索关键词过长，已截断: {}", request.getKeyword());
                request.setKeyword(request.getKeyword().substring(0, 100));
            }
            
            // 处理日期时间格式
            String processedStartDate = processDateTimeString(request.getStartDate());
            String processedEndDate = processDateTimeString(request.getEndDate());
            
            log.info("处理后的时间参数：原始startDate={}, 处理后={}, 原始endDate={}, 处理后={}", 
                    request.getStartDate(), processedStartDate, request.getEndDate(), processedEndDate);

            // 计算分页偏移量
            int offset = (request.getPage() - 1) * request.getSize();

            // 先查询总数
            Long total = orderMapper.countAdminOrderList(
                request.getStatus(),
                request.getOrderType(),
                request.getKeyword(),
                processedStartDate,
                processedEndDate
            );

            log.info("查询条件：status={}, orderType={}, keyword={}, startDate={}, endDate={}, 总数={}", 
                    request.getStatus(), request.getOrderType(), request.getKeyword(), 
                    processedStartDate, processedEndDate, total);

            List<AdminOrderDto.OrderListItem> orderItems = new ArrayList<>();
            
            // 如果总数大于0，再查询具体数据
            if (total > 0) {
                // 查询订单列表（使用JOIN查询，一次性获取所有数据）
                List<AdminOrderInfo> adminOrderInfos = orderMapper.selectAdminOrderList(
                    request.getStatus(),
                    request.getOrderType(),
                    request.getKeyword(),
                    processedStartDate,
                    processedEndDate,
                    request.getSortField(),
                    request.getSortOrder(),
                    offset,
                    request.getSize()
                );

                // 转换为DTO对象
                for (AdminOrderInfo adminOrderInfo : adminOrderInfos) {
                    AdminOrderDto.OrderListItem item = new AdminOrderDto.OrderListItem();
                    
                    // 订单基本信息
                    item.setId(adminOrderInfo.getId());
                    item.setOrderNo(adminOrderInfo.getOrderNo());
                    item.setUserId(adminOrderInfo.getUserId());
                    item.setOriginalPrice(adminOrderInfo.getOriginalPrice());
                    item.setAmount(adminOrderInfo.getAmount());
                    item.setStatus(adminOrderInfo.getStatus());
                    item.setStatusName(getOrderStatusName(adminOrderInfo.getStatus()));
                    item.setPaymentMethod(getPaymentMethodName(adminOrderInfo.getPaymentMethod()));
                    item.setCreateTime(adminOrderInfo.getCreateTime());
                    item.setPaidAt(adminOrderInfo.getPaidAt());
                    
                    // 用户信息（来自JOIN查询）
                    item.setUsername(adminOrderInfo.getUsername());
                    
                    // 套餐信息（来自JOIN查询）
                    item.setPlanName(adminOrderInfo.getPlanName());
                    
                    orderItems.add(item);
                }
            }

            AdminOrderDto.OrderListResponse response = new AdminOrderDto.OrderListResponse();
            response.setList(orderItems);
            response.setTotal(total);
            response.setPage(request.getPage());
            response.setSize(request.getSize());

            log.info("订单列表查询完成，返回{}条记录，总数{}，页码{}，每页{}", 
                    orderItems.size(), total, request.getPage(), request.getSize());

            return ApiResponse.success(response);

        } catch (Exception e) {
            log.error("获取订单列表失败", e);
            return ApiResponse.error("获取订单列表失败：" + e.getMessage());
        }
    }

    @Override
    public ApiResponse<AdminOrderDto.OrderSummaryResponse> getOrderSummary(AdminOrderDto.OrderSummaryRequest request) {
        try {
            log.info("获取订单汇总，请求参数：{}", request);

            AdminOrderDto.OrderSummaryResponse response = new AdminOrderDto.OrderSummaryResponse();
            
            // 获取当前时间，用于计算各种时间范围
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime todayStart = now.toLocalDate().atStartOfDay();
            LocalDateTime todayEnd = todayStart.plusDays(1);
            LocalDateTime weekStart = todayStart.minusDays(now.getDayOfWeek().getValue() - 1);
            LocalDateTime monthStart = now.toLocalDate().withDayOfMonth(1).atStartOfDay();
            
            // 根据请求参数调整时间范围
            if (request.getStartDate() != null && request.getEndDate() != null) {
                try {
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    todayStart = LocalDate.parse(request.getStartDate(), formatter).atStartOfDay();
                    todayEnd = LocalDate.parse(request.getEndDate(), formatter).plusDays(1).atStartOfDay();
                } catch (Exception e) {
                    log.warn("日期格式解析失败，使用默认时间范围: {}", e.getMessage());
                }
            }
            
            // 查询真实数据
            // 1. 总收入和总订单数
            BigDecimal totalRevenue = orderMapper.getTotalRevenue();
            Long totalOrders = orderMapper.getTotalOrders();
            
            // 2. 今日数据
            BigDecimal todayRevenue = orderMapper.getRevenueByDateRange(todayStart, todayEnd);
            Long todayOrders = orderMapper.getOrderCountByDateRange(todayStart, todayEnd);
            
            // 3. 本周数据
            BigDecimal weekRevenue = orderMapper.getRevenueByDateRange(weekStart, todayEnd);
            
            // 4. 本月数据
            BigDecimal monthRevenue = orderMapper.getRevenueByDateRange(monthStart, todayEnd);
            
            // 5. 新增会员数据（根据period参数决定时间范围）
            LocalDateTime periodStart;
            LocalDateTime periodEnd = now;
            
            switch (request.getPeriod().toLowerCase()) {
                case "daily":
                    periodStart = todayStart;
                    periodEnd = todayEnd;
                    break;
                case "weekly":
                    periodStart = weekStart;
                    break;
                case "monthly":
                    periodStart = monthStart;
                    break;
                default:
                    periodStart = todayStart;
                    periodEnd = todayEnd;
            }
            
            Long newVipUsers = orderMapper.getNewVipUsersByDateRange(periodStart, periodEnd);
            Long newSvipUsers = orderMapper.getNewSvipUsersByDateRange(periodStart, periodEnd);
            
            // 设置响应数据
            response.setTotalRevenue(totalRevenue != null ? totalRevenue : BigDecimal.ZERO);
            response.setTotalOrders(totalOrders != null ? totalOrders : 0L);
            response.setNewVipUsers(newVipUsers != null ? newVipUsers : 0L);
            response.setNewSvipUsers(newSvipUsers != null ? newSvipUsers : 0L);
            response.setTodayRevenue(todayRevenue != null ? todayRevenue : BigDecimal.ZERO);
            response.setTodayOrders(todayOrders != null ? todayOrders : 0L);
            response.setWeekRevenue(weekRevenue != null ? weekRevenue : BigDecimal.ZERO);
            response.setMonthRevenue(monthRevenue != null ? monthRevenue : BigDecimal.ZERO);

            log.info("订单汇总数据查询完成 - 总收入: {}, 总订单: {}, 今日收入: {}, 今日订单: {}", 
                    response.getTotalRevenue(), response.getTotalOrders(), 
                    response.getTodayRevenue(), response.getTodayOrders());

            return ApiResponse.success(response);

        } catch (Exception e) {
            log.error("获取订单汇总失败", e);
            return ApiResponse.error("获取订单汇总失败：" + e.getMessage());
        }
    }

    @Override
    public ApiResponse<AdminOrderDto.OrderDetailResponse> getOrderDetail(Long orderId) {
        try {
            log.info("获取订单详情，订单ID：{}", orderId);

            Order order = orderMapper.selectById(orderId);
            if (order == null) {
                return ApiResponse.error("订单不存在");
            }

            AdminOrderDto.OrderDetailResponse response = new AdminOrderDto.OrderDetailResponse();
            
            // 订单详细信息
            AdminOrderDto.OrderDetail orderDetail = new AdminOrderDto.OrderDetail();
            orderDetail.setId(order.getId());
            orderDetail.setOrderNo(order.getOrderNo());
            orderDetail.setOriginalPrice(order.getOriginalPrice());
            orderDetail.setAmount(order.getAmount());
            orderDetail.setDiscountType(order.getDiscountType());
            orderDetail.setDiscountAmount(order.getDiscountAmount());
            orderDetail.setDiscountDescription(order.getDiscountDescription());
            orderDetail.setActualDurationDays(order.getActualDurationDays());
            orderDetail.setStatus(order.getStatus());
            orderDetail.setStatusName(getOrderStatusName(order.getStatus()));
            orderDetail.setPaymentMethod(getPaymentMethodName(order.getPaymentMethod()));
            orderDetail.setCreateTime(order.getCreateTime());
            orderDetail.setPaidAt(order.getPaidAt());
            response.setOrderDetail(orderDetail);

            // 用户信息
            User user = userMapper.selectById(order.getUserId());
            if (user != null) {
                AdminOrderDto.UserInfo userInfo = new AdminOrderDto.UserInfo();
                userInfo.setUserId(user.getId());
                userInfo.setUsername(user.getUsername());
                userInfo.setPhone(user.getPhone());
                userInfo.setRole(user.getRole());
                userInfo.setRoleName(getUserRoleName(user.getRole()));
                response.setUserInfo(userInfo);
            }

            // 套餐信息
            if (order.getPlanId() != null) {
                MembershipPlan plan = membershipPlanMapper.selectById(order.getPlanId());
                if (plan != null) {
                    AdminOrderDto.PlanInfo planInfo = new AdminOrderDto.PlanInfo();
                    planInfo.setPlanId(plan.getId());
                    planInfo.setPlanName(plan.getName());
                    planInfo.setPlanPrice(plan.getPrice());
                    planInfo.setPlanDurationDays(plan.getDurationDays());
                    planInfo.setTargetRole(plan.getTargetRole());
                    planInfo.setTargetRoleName(getUserRoleName(plan.getTargetRole()));
                    response.setPlanInfo(planInfo);
                }
            }

            return ApiResponse.success(response);

        } catch (Exception e) {
            log.error("获取订单详情失败", e);
            return ApiResponse.error("获取订单详情失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse<String> updateOrderStatus(AdminOrderDto.OrderStatusUpdateRequest request) {
        try {
            log.info("更新订单状态，请求参数：{}", request);

            Order order = orderMapper.selectById(request.getOrderId());
            if (order == null) {
                return ApiResponse.error("订单不存在");
            }

            order.setStatus(request.getStatus());
            order.setUpdateTime(LocalDateTime.now());
            
            if (request.getStatus() == 1) { // 已支付
                order.setPaidAt(LocalDateTime.now());
            }

            int result = orderMapper.updateById(order);
            if (result > 0) {
                return ApiResponse.success("订单状态更新成功");
            } else {
                return ApiResponse.error("订单状态更新失败");
            }

        } catch (Exception e) {
            log.error("更新订单状态失败", e);
            return ApiResponse.error("更新订单状态失败：" + e.getMessage());
        }
    }

    @Override
    public ApiResponse<AdminOrderDto.MembershipPlanListResponse> getMembershipPlanList(AdminOrderDto.MembershipPlanListRequest request) {
        try {
            log.info("获取会员套餐列表，请求参数：{}", request);

            List<MembershipPlan> plans;
            if (request.getActiveOnly()) {
                plans = membershipPlanMapper.selectAllActive();
            } else {
                plans = membershipPlanMapper.selectAll();
            }

            List<AdminOrderDto.MembershipPlanItem> planItems = new ArrayList<>();
            for (MembershipPlan plan : plans) {
                AdminOrderDto.MembershipPlanItem item = new AdminOrderDto.MembershipPlanItem();
                item.setId(plan.getId());
                item.setName(plan.getName());
                item.setDescription(plan.getDescription());
                item.setPrice(plan.getPrice());
                item.setDurationDays(plan.getDurationDays());
                item.setTargetRole(plan.getTargetRole());
                item.setTargetRoleName(getUserRoleName(plan.getTargetRole()));
                item.setDiscountPercentage(plan.getDiscountPercentage());
                item.setIsActive(plan.getIsActive());
                item.setCreateTime(plan.getCreateTime());
                item.setUpdateTime(plan.getUpdateTime());
                planItems.add(item);
            }

            AdminOrderDto.MembershipPlanListResponse response = new AdminOrderDto.MembershipPlanListResponse();
            response.setList(planItems);
            response.setTotal((long) planItems.size());

            return ApiResponse.success(response);

        } catch (Exception e) {
            log.error("获取会员套餐列表失败", e);
            return ApiResponse.error("获取会员套餐列表失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse<String> createMembershipPlan(AdminOrderDto.MembershipPlanCreateRequest request) {
        try {
            log.info("创建会员套餐，请求参数：{}", request);

            MembershipPlan plan = new MembershipPlan();
            plan.setName(request.getName());
            plan.setDescription(request.getDescription());
            plan.setPrice(request.getPrice());
            plan.setDurationDays(request.getDurationDays());
            plan.setTargetRole(request.getTargetRole());
            plan.setDiscountPercentage(request.getDiscountPercentage());
            plan.setIsActive(request.getIsActive());
            plan.setCreateTime(LocalDateTime.now());
            plan.setUpdateTime(LocalDateTime.now());
            plan.setIsDeleted(0);

            int result = membershipPlanMapper.insert(plan);
            if (result > 0) {
                return ApiResponse.success("会员套餐创建成功");
            } else {
                return ApiResponse.error("会员套餐创建失败");
            }

        } catch (Exception e) {
            log.error("创建会员套餐失败", e);
            return ApiResponse.error("创建会员套餐失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse<String> updateMembershipPlan(AdminOrderDto.MembershipPlanUpdateRequest request) {
        try {
            log.info("更新会员套餐，请求参数：{}", request);

            MembershipPlan plan = membershipPlanMapper.selectById(request.getId());
            if (plan == null) {
                return ApiResponse.error("套餐不存在");
            }

            plan.setName(request.getName());
            plan.setDescription(request.getDescription());
            plan.setPrice(request.getPrice());
            plan.setDurationDays(request.getDurationDays());
            plan.setTargetRole(request.getTargetRole());
            plan.setDiscountPercentage(request.getDiscountPercentage());
            plan.setIsActive(request.getIsActive());
            plan.setUpdateTime(LocalDateTime.now());

            int result = membershipPlanMapper.updateById(plan);
            if (result > 0) {
                return ApiResponse.success("会员套餐更新成功");
            } else {
                return ApiResponse.error("会员套餐更新失败");
            }

        } catch (Exception e) {
            log.error("更新会员套餐失败", e);
            return ApiResponse.error("更新会员套餐失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse<String> deleteMembershipPlan(Long id) {
        try {
            log.info("删除会员套餐，套餐ID：{}", id);

            MembershipPlan plan = membershipPlanMapper.selectById(id);
            if (plan == null) {
                return ApiResponse.error("套餐不存在");
            }

            // 软删除
            plan.setIsDeleted(1);
            plan.setUpdateTime(LocalDateTime.now());

            int result = membershipPlanMapper.updateById(plan);
            if (result > 0) {
                return ApiResponse.success("会员套餐删除成功");
            } else {
                return ApiResponse.error("会员套餐删除失败");
            }

        } catch (Exception e) {
            log.error("删除会员套餐失败", e);
            return ApiResponse.error("删除会员套餐失败：" + e.getMessage());
        }
    }

    @Override
    public ApiResponse<AdminOrderDto.MembershipPlanDetailResponse> getMembershipPlanDetail(Long id) {
        try {
            log.info("获取套餐详情，套餐ID：{}", id);

            MembershipPlan plan = membershipPlanMapper.selectById(id);
            if (plan == null) {
                return ApiResponse.error("套餐不存在");
            }

            AdminOrderDto.MembershipPlanDetailResponse response = new AdminOrderDto.MembershipPlanDetailResponse();
            
            // 套餐详细信息
            AdminOrderDto.MembershipPlanItem planDetail = new AdminOrderDto.MembershipPlanItem();
            planDetail.setId(plan.getId());
            planDetail.setName(plan.getName());
            planDetail.setDescription(plan.getDescription());
            planDetail.setPrice(plan.getPrice());
            planDetail.setDurationDays(plan.getDurationDays());
            planDetail.setTargetRole(plan.getTargetRole());
            planDetail.setTargetRoleName(getUserRoleName(plan.getTargetRole()));
            planDetail.setDiscountPercentage(plan.getDiscountPercentage());
            planDetail.setIsActive(plan.getIsActive());
            planDetail.setCreateTime(plan.getCreateTime());
            planDetail.setUpdateTime(plan.getUpdateTime());
            response.setPlanDetail(planDetail);

            // 查询真实的统计信息
            AdminOrderDto.PlanStatistics statistics = new AdminOrderDto.PlanStatistics();
            
            // 总购买次数和总收入
            Long totalPurchases = orderMapper.getPlanPurchaseCount(id);
            BigDecimal totalRevenue = orderMapper.getPlanTotalRevenue(id);
            
            // 本月购买次数和收入
            LocalDateTime monthStart = LocalDate.now().withDayOfMonth(1).atStartOfDay();
            LocalDateTime monthEnd = LocalDate.now().plusDays(1).atStartOfDay();
            Long monthlyPurchases = orderMapper.getPlanPurchaseCountByDateRange(id, monthStart, monthEnd);
            BigDecimal monthlyRevenue = orderMapper.getPlanRevenueByDateRange(id, monthStart, monthEnd);
            
            statistics.setTotalPurchases(totalPurchases != null ? totalPurchases : 0L);
            statistics.setTotalRevenue(totalRevenue != null ? totalRevenue : BigDecimal.ZERO);
            statistics.setMonthlyPurchases(monthlyPurchases != null ? monthlyPurchases : 0L);
            statistics.setMonthlyRevenue(monthlyRevenue != null ? monthlyRevenue : BigDecimal.ZERO);
            response.setStatistics(statistics);

            return ApiResponse.success(response);

        } catch (Exception e) {
            log.error("获取套餐详情失败", e);
            return ApiResponse.error("获取套餐详情失败：" + e.getMessage());
        }
    }

    @Override
    public ApiResponse<AdminOrderDto.TransactionStatisticsResponse> getTransactionStatistics(AdminOrderDto.TransactionStatisticsRequest request) {
        try {
            log.info("获取交易统计，请求参数：{}", request);

            AdminOrderDto.TransactionStatisticsResponse response = new AdminOrderDto.TransactionStatisticsResponse();
            
            // 1. 查询真实的总体统计数据
            BigDecimal totalAmount = orderMapper.getTotalRevenue();
            Long totalCount = orderMapper.getTotalOrders();
            BigDecimal successAmount = totalAmount; // 成功金额就是总收入
            Long successCount = orderMapper.getOrderCountByDateRange(
                LocalDateTime.of(2020, 1, 1, 0, 0), 
                LocalDateTime.now().plusDays(1)
            );
            Long failedCount = orderMapper.getFailedOrderCount();
            BigDecimal refundAmount = orderMapper.getRefundAmount();
            Long refundCount = orderMapper.getRefundOrderCount();
            
            // 2. 设置总体统计数据
            response.setTotalAmount(totalAmount != null ? totalAmount : BigDecimal.ZERO);
            response.setTotalCount(totalCount != null ? totalCount : 0L);
            response.setSuccessAmount(successAmount != null ? successAmount : BigDecimal.ZERO);
            response.setSuccessCount(successCount != null ? successCount : 0L);
            response.setFailedCount(failedCount != null ? failedCount : 0L);
            response.setRefundAmount(refundAmount != null ? refundAmount : BigDecimal.ZERO);
            response.setRefundCount(refundCount != null ? refundCount : 0L);

            // 3. 查询每日统计数据
            List<AdminOrderDto.DailyStatistics> dailyStats = new ArrayList<>();
            LocalDate endDate = LocalDate.now();
            LocalDate startDate = endDate.minusDays(6); // 查询最近7天
            
            // 根据period调整时间范围
            if ("weekly".equals(request.getPeriod())) {
                startDate = endDate.minusDays(13); // 最近14天
            } else if ("monthly".equals(request.getPeriod())) {
                startDate = endDate.minusDays(29); // 最近30天
            }
            
            // 查询数据库获取每日统计
            List<Map<String, Object>> dbStats = orderMapper.getDailyTransactionStats(
                startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                endDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
            );
            
            // 创建一个Map方便查找
            Map<String, Map<String, Object>> statsMap = new HashMap<>();
            for (Map<String, Object> stat : dbStats) {
                String date = stat.get("date").toString();
                statsMap.put(date, stat);
            }
            
            // 填充每日数据，确保没有数据的日期也显示（为0）
            LocalDate currentDate = startDate;
            while (!currentDate.isAfter(endDate)) {
                String dateStr = currentDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                AdminOrderDto.DailyStatistics daily = new AdminOrderDto.DailyStatistics();
                daily.setDate(dateStr);
                
                Map<String, Object> stat = statsMap.get(dateStr);
                if (stat != null) {
                    daily.setAmount(new BigDecimal(stat.get("amount").toString()));
                    daily.setCount(Long.valueOf(stat.get("count").toString()));
                    daily.setNewUsers(Long.valueOf(stat.get("new_users").toString()));
                } else {
                    // 没有数据的日期设置为0
                    daily.setAmount(BigDecimal.ZERO);
                    daily.setCount(0L);
                    daily.setNewUsers(0L);
                }
                
                dailyStats.add(daily);
                currentDate = currentDate.plusDays(1);
            }
            
            response.setDailyStats(dailyStats);

            log.info("交易统计查询完成 - 总金额: {}, 总订单: {}, 成功订单: {}, 失败订单: {}", 
                    response.getTotalAmount(), response.getTotalCount(), 
                    response.getSuccessCount(), response.getFailedCount());

            return ApiResponse.success(response);

        } catch (Exception e) {
            log.error("获取交易统计失败", e);
            return ApiResponse.error("获取交易统计失败：" + e.getMessage());
        }
    }

    /**
     * 获取订单状态名称
     */
    private String getOrderStatusName(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 0: return "待支付";
            case 1: return "已完成";      // 修复：与数据库定义一致
            case 2: return "已取消";
            case 3: return "支付失败";    // 修复：与数据库定义一致
            default: return "未知";
        }
    }

    /**
     * 获取用户角色名称
     */
    private String getUserRoleName(Integer role) {
        if (role == null) return "未知";
        switch (role) {
            case 0: return "游客";
            case 1: return "普通";
            case 2: return "VIP";
            case 3: return "SVIP";
            default: return "未知";
        }
    }

    /**
     * 获取支付方式名称
     */
    private String getPaymentMethodName(Integer paymentMethod) {
        if (paymentMethod == null) return "未支付";
        switch (paymentMethod) {
            case 1: return "支付宝";      // 修复：1对应支付宝
            case 2: return "微信支付";    // 修复：2对应微信支付
            case 3: return "银行卡";
            default: return "其他";
        }
    }

    /**
     * 验证排序字段是否安全
     * @param sortField 排序字段
     * @return 是否为有效的排序字段
     */
    private boolean isValidSortField(String sortField) {
        // 只允许特定的排序字段，防止SQL注入
        return sortField != null && (
            "create_time".equals(sortField) ||
            "amount".equals(sortField) ||
            "status".equals(sortField) ||
            "paid_at".equals(sortField) ||
            "username".equals(sortField)
        );
    }
    
    /**
     * 处理日期时间字符串，支持多种格式
     * @param dateTimeString 日期时间字符串
     * @return 处理后的日期时间字符串（适合数据库查询）
     */
    private String processDateTimeString(String dateTimeString) {
        if (dateTimeString == null || dateTimeString.trim().isEmpty()) {
            return null;
        }
        
        String trimmed = dateTimeString.trim();
        
        try {
            // 如果已经是标准的日期时间格式（包含T），直接返回
            if (trimmed.contains("T")) {
                // 验证格式是否正确
                DateTimeFormatter.ISO_LOCAL_DATE_TIME.parse(trimmed);
                return trimmed;
            }
            
            // 如果是日期格式（如 2024-01-01），需要特殊处理
            if (trimmed.matches("\\d{4}-\\d{2}-\\d{2}")) {
                // 检查是否为开始时间还是结束时间（简单判断：包含start的为开始时间）
                // 注：这里直接返回日期，让数据库的DATE()函数或BETWEEN来处理
                return trimmed;
            }
            
            // 其他格式尝试解析
            return trimmed;
            
        } catch (Exception e) {
            log.warn("日期时间格式解析失败，使用原始值: {}, 错误: {}", dateTimeString, e.getMessage());
            return trimmed;
        }
    }
}
