package com.dora.service.impl;

import com.dora.dto.AdminGiftCodeDto;
import com.dora.dto.ApiResponse;
import com.dora.entity.GiftCode;
import com.dora.mapper.GiftCodeMapper;
import com.dora.mapper.GiftCodeUsageMapper;
import com.dora.service.AdminGiftCodeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 管理端礼品码服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminGiftCodeServiceImpl implements AdminGiftCodeService {

    private static final String GIFT_CODE_NOT_EXISTS = "礼品码不存在";

    private final GiftCodeMapper giftCodeMapper;
    private final GiftCodeUsageMapper giftCodeUsageMapper;

    @Override
    public ApiResponse<AdminGiftCodeDto.GiftCodeListResponse> getGiftCodeList(AdminGiftCodeDto.GiftCodeListRequest request) {
        try {
            log.info("查询礼品码列表参数: page={}, size={}, keyword={}, type={}, isActive={}, createTimeStart={}, createTimeEnd={}, sortField={}, sortOrder={}", 
                    request.getPage(), request.getSize(), request.getKeyword(), request.getType(), 
                    request.getIsActive(), request.getCreateTimeStart(), request.getCreateTimeEnd(), 
                    request.getSortField(), request.getSortOrder());
            
            // 先查看数据库中实际的礼品码数据（调试用）
            List<GiftCode> allGiftCodes = giftCodeMapper.selectAllForDebug();
            log.info("数据库中前10条礼品码数据: {}", allGiftCodes.size());
            for (GiftCode giftCode : allGiftCodes) {
                log.info("礼品码数据: id={}, code={}, name={}, is_deleted={}, is_active={}", 
                        giftCode.getId(), giftCode.getCode(), giftCode.getName(), 
                        giftCode.getIsDeleted(), giftCode.getIsActive());
            }
            
            // 计算偏移量
            long offset = (long) (request.getPage() - 1) * request.getSize();

            // 查询礼品码列表
            List<GiftCode> giftCodes = giftCodeMapper.selectPageList(
                    request.getKeyword(),
                    request.getType(),
                    request.getIsActive(),
                    request.getCreateTimeStart(),
                    request.getCreateTimeEnd(),
                    request.getSortField(),
                    request.getSortOrder(),
                    offset,
                    request.getSize()
            );

            log.info("查询到礼品码数量: {}", giftCodes.size());

            // 统计总数
            Long total = giftCodeMapper.countPageList(
                    request.getKeyword(),
                    request.getType(),
                    request.getIsActive(),
                    request.getCreateTimeStart(),
                    request.getCreateTimeEnd()
            );

            log.info("礼品码总数: {}", total);

            // 转换为DTO
            List<AdminGiftCodeDto.GiftCodeListItem> list = new ArrayList<>();
            for (GiftCode giftCode : giftCodes) {
                AdminGiftCodeDto.GiftCodeListItem item = convertToListItem(giftCode);
                list.add(item);
            }

            AdminGiftCodeDto.GiftCodeListResponse response = new AdminGiftCodeDto.GiftCodeListResponse();
            response.setList(list);
            response.setTotal(total);
            response.setPage(request.getPage());
            response.setSize(request.getSize());

            return ApiResponse.success(response);

        } catch (Exception e) {
            log.error("查询礼品码列表失败", e);
            return ApiResponse.error("查询礼品码列表失败: " + e.getMessage());
        }
    }

    @Override
    public ApiResponse<AdminGiftCodeDto.GiftCodeDetailResponse> getGiftCodeDetail(Long id) {
        try {
            GiftCode giftCode = giftCodeMapper.selectById(id);
            if (giftCode == null) {
                return ApiResponse.error(404, GIFT_CODE_NOT_EXISTS);
            }

            AdminGiftCodeDto.GiftCodeDetailResponse response = convertToDetailResponse(giftCode);
            return ApiResponse.success(response);

        } catch (Exception e) {
            log.error("查询礼品码详情失败, id: {}", id, e);
            return ApiResponse.error("查询礼品码详情失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse<String> createGiftCode(AdminGiftCodeDto.CreateGiftCodeRequest request) {
        try {
            // 验证请求参数
            String validateResult = validateCreateRequest(request);
            if (validateResult != null) {
                return ApiResponse.error(400, validateResult);
            }

            // 检查礼品码是否已存在
            int existCount = giftCodeMapper.countByCode(request.getCode(), null);
            if (existCount > 0) {
                return ApiResponse.error(400, "礼品码已存在");
            }

            // 创建礼品码
            GiftCode giftCode = new GiftCode();
            giftCode.setCode(request.getCode());
            giftCode.setName(request.getName());
            giftCode.setDescription(request.getDescription());
            giftCode.setType(request.getType());
            giftCode.setPoints(request.getPoints());
            giftCode.setPointsExpireDays(request.getPointsExpireDays());
            giftCode.setTargetRole(request.getTargetRole());
            giftCode.setDurationDays(request.getDurationDays());
            giftCode.setTotalCount(request.getTotalCount());
            giftCode.setUsedCount(0);
            giftCode.setIsActive(1);
            giftCode.setExpireTime(request.getExpireTime());

            int result = giftCodeMapper.insert(giftCode);
            if (result <= 0) {
                return ApiResponse.error("创建礼品码失败");
            }

            log.info("创建礼品码成功, code: {}, id: {}", request.getCode(), giftCode.getId());
            return ApiResponse.success("创建礼品码成功");

        } catch (Exception e) {
            log.error("创建礼品码失败", e);
            return ApiResponse.error("创建礼品码失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse<String> updateGiftCode(AdminGiftCodeDto.UpdateGiftCodeRequest request) {
        try {
            // 验证请求参数
            String validateResult = validateUpdateRequest(request);
            if (validateResult != null) {
                return ApiResponse.error(400, validateResult);
            }

            // 检查礼品码是否存在
            GiftCode existGiftCode = giftCodeMapper.selectById(request.getId());
            if (existGiftCode == null) {
                return ApiResponse.error(404, GIFT_CODE_NOT_EXISTS);
            }

            // 更新礼品码
            GiftCode giftCode = new GiftCode();
            giftCode.setId(request.getId());
            giftCode.setName(request.getName());
            giftCode.setDescription(request.getDescription());
            giftCode.setPoints(request.getPoints());
            giftCode.setPointsExpireDays(request.getPointsExpireDays());
            giftCode.setTargetRole(request.getTargetRole());
            giftCode.setDurationDays(request.getDurationDays());
            giftCode.setTotalCount(request.getTotalCount());
            giftCode.setExpireTime(request.getExpireTime());

            int result = giftCodeMapper.updateById(giftCode);
            if (result <= 0) {
                return ApiResponse.error("更新礼品码失败");
            }

            log.info("更新礼品码成功, id: {}", request.getId());
            return ApiResponse.success("更新礼品码成功");

        } catch (Exception e) {
            log.error("更新礼品码失败", e);
            return ApiResponse.error("更新礼品码失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse<String> updateGiftCodeStatus(AdminGiftCodeDto.UpdateGiftCodeStatusRequest request) {
        try {
            // 检查礼品码是否存在
            GiftCode giftCode = giftCodeMapper.selectById(request.getId());
            if (giftCode == null) {
                return ApiResponse.error(404, GIFT_CODE_NOT_EXISTS);
            }

            int result = giftCodeMapper.updateStatus(request.getId(), request.getIsActive());
            if (result <= 0) {
                return ApiResponse.error("更新礼品码状态失败");
            }

            String statusName = request.getIsActive() == 1 ? "启用" : "禁用";
            log.info("{}礼品码成功, id: {}, code: {}", statusName, request.getId(), giftCode.getCode());
            return ApiResponse.success(statusName + "礼品码成功");

        } catch (Exception e) {
            log.error("更新礼品码状态失败", e);
            return ApiResponse.error("更新礼品码状态失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse<String> deleteGiftCode(Long id) {
        try {
            // 检查礼品码是否存在
            GiftCode giftCode = giftCodeMapper.selectById(id);
            if (giftCode == null) {
                return ApiResponse.error(404, GIFT_CODE_NOT_EXISTS);
            }

            // 检查是否有使用记录
            int usageCount = giftCodeUsageMapper.countByUserAndCode(null, id);
            if (usageCount > 0) {
                return ApiResponse.error(400, "该礼品码已有使用记录，无法删除");
            }

            int result = giftCodeMapper.deleteById(id);
            if (result <= 0) {
                return ApiResponse.error("删除礼品码失败");
            }

            log.info("删除礼品码成功, id: {}, code: {}", id, giftCode.getCode());
            return ApiResponse.success("删除礼品码成功");

        } catch (Exception e) {
            log.error("删除礼品码失败, id: {}", id, e);
            return ApiResponse.error("删除礼品码失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse<String> batchOperateGiftCodes(AdminGiftCodeDto.BatchOperationRequest request) {
        try {
            if (request.getIds() == null || request.getIds().isEmpty()) {
                return ApiResponse.error(400, "礼品码ID列表不能为空");
            }

            int result = 0;
            String operation = request.getOperation();
            String operationName = "";

            switch (operation) {
                case "enable":
                    result = giftCodeMapper.batchUpdateStatus(request.getIds(), 1);
                    operationName = "启用";
                    break;
                case "disable":
                    result = giftCodeMapper.batchUpdateStatus(request.getIds(), 0);
                    operationName = "禁用";
                    break;
                case "delete":
                    result = giftCodeMapper.batchDeleteByIds(request.getIds());
                    operationName = "删除";
                    break;
                default:
                    return ApiResponse.error(400, "不支持的操作类型");
            }

            if (result <= 0) {
                return ApiResponse.error("批量" + operationName + "礼品码失败");
            }

            log.info("批量{}礼品码成功, 数量: {}", operationName, result);
            return ApiResponse.success("批量" + operationName + "礼品码成功，共" + result + "条记录");

        } catch (Exception e) {
            log.error("批量操作礼品码失败", e);
            return ApiResponse.error("批量操作礼品码失败: " + e.getMessage());
        }
    }

    @Override
    public ApiResponse<AdminGiftCodeDto.UsageListResponse> getUsageList(AdminGiftCodeDto.UsageListRequest request) {
        try {
            // 计算偏移量
            long offset = (long) (request.getPage() - 1) * request.getSize();

            // 查询使用记录列表
            List<Map<String, Object>> usageList = giftCodeUsageMapper.selectPageListWithUserAndGiftCode(
                    request.getGiftCodeId(),
                    request.getUserId(),
                    request.getCode(),
                    request.getType(),
                    request.getStatus(),
                    request.getCreateTimeStart(),
                    request.getCreateTimeEnd(),
                    request.getSortField(),
                    request.getSortOrder(),
                    offset,
                    request.getSize()
            );

            // 统计总数
            Long total = giftCodeUsageMapper.countPageList(
                    request.getGiftCodeId(),
                    request.getUserId(),
                    request.getCode(),
                    request.getType(),
                    request.getStatus(),
                    request.getCreateTimeStart(),
                    request.getCreateTimeEnd()
            );

            // 转换为DTO
            List<AdminGiftCodeDto.UsageListItem> list = new ArrayList<>();
            for (Map<String, Object> usage : usageList) {
                AdminGiftCodeDto.UsageListItem item = convertToUsageListItem(usage);
                list.add(item);
            }

            AdminGiftCodeDto.UsageListResponse response = new AdminGiftCodeDto.UsageListResponse();
            response.setList(list);
            response.setTotal(total);
            response.setPage(request.getPage());
            response.setSize(request.getSize());

            return ApiResponse.success(response);

        } catch (Exception e) {
            log.error("查询使用记录列表失败", e);
            return ApiResponse.error("查询使用记录列表失败: " + e.getMessage());
        }
    }

    @Override
    public ApiResponse<AdminGiftCodeDto.GiftCodeStatisticsResponse> getGiftCodeStatistics() {
        try {
            // 获取礼品码统计信息
            Map<String, Object> giftCodeStats = giftCodeMapper.getStatistics();
            Map<String, Object> usageStats = giftCodeUsageMapper.getUsageStatistics();
            Long thisMonthNewCount = giftCodeMapper.getThisMonthNewCount();
            Long thisMonthUsageCount = giftCodeUsageMapper.getThisMonthUsageCount();

            AdminGiftCodeDto.GiftCodeStatisticsResponse response = new AdminGiftCodeDto.GiftCodeStatisticsResponse();
            response.setTotalCount(getLongFromMap(giftCodeStats, "total_count"));
            response.setActiveCount(getLongFromMap(giftCodeStats, "active_count"));
            response.setInactiveCount(getLongFromMap(giftCodeStats, "inactive_count"));
            response.setPointsCardCount(getLongFromMap(giftCodeStats, "points_card_count"));
            response.setMembershipCardCount(getLongFromMap(giftCodeStats, "membership_card_count"));
            response.setExpiredCount(getLongFromMap(giftCodeStats, "expired_count"));
            response.setTotalUsageCount(getLongFromMap(giftCodeStats, "total_usage_count"));
            response.setSuccessUsageCount(getLongFromMap(usageStats, "success_usage_count"));
            response.setFailedUsageCount(getLongFromMap(usageStats, "failed_usage_count"));
            response.setThisMonthNewCount(thisMonthNewCount != null ? thisMonthNewCount : 0L);
            response.setThisMonthUsageCount(thisMonthUsageCount != null ? thisMonthUsageCount : 0L);

            return ApiResponse.success(response);

        } catch (Exception e) {
            log.error("获取礼品码统计信息失败", e);
            return ApiResponse.error("获取礼品码统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 验证创建请求参数
     */
    private String validateCreateRequest(AdminGiftCodeDto.CreateGiftCodeRequest request) {
        if (request.getType() == 1) {
            // 积分卡
            if (request.getPoints() == null || request.getPoints() <= 0) {
                return "积分卡的积分数量必须大于0";
            }
            if (request.getPointsExpireDays() == null || request.getPointsExpireDays() <= 0) {
                return "积分卡的积分有效期必须大于0";
            }
        } else if (request.getType() == 2) {
            // 会员卡
            if (request.getTargetRole() == null || request.getTargetRole() <= 0 || request.getTargetRole() > 3) {
                return "会员卡的目标角色等级必须在1-3之间";
            }
            if (request.getDurationDays() == null || request.getDurationDays() <= 0) {
                return "会员卡的会员有效期必须大于0";
            }
        }
        return null;
    }

    /**
     * 验证更新请求参数
     */
    private String validateUpdateRequest(AdminGiftCodeDto.UpdateGiftCodeRequest request) {
        GiftCode existGiftCode = giftCodeMapper.selectById(request.getId());
        if (existGiftCode == null) {
            return GIFT_CODE_NOT_EXISTS;
        }

        if (existGiftCode.getType() == 1) {
            // 积分卡
            if (request.getPoints() != null && request.getPoints() <= 0) {
                return "积分卡的积分数量必须大于0";
            }
            if (request.getPointsExpireDays() != null && request.getPointsExpireDays() <= 0) {
                return "积分卡的积分有效期必须大于0";
            }
        } else if (existGiftCode.getType() == 2) {
            // 会员卡
            if (request.getTargetRole() != null && (request.getTargetRole() <= 0 || request.getTargetRole() > 3)) {
                return "会员卡的目标角色等级必须在1-3之间";
            }
            if (request.getDurationDays() != null && request.getDurationDays() <= 0) {
                return "会员卡的会员有效期必须大于0";
            }
        }

        if (request.getTotalCount() != null && request.getTotalCount() < existGiftCode.getUsedCount()) {
            return "总可用次数不能小于已使用次数";
        }

        return null;
    }

    /**
     * 转换为列表项DTO
     */
    private AdminGiftCodeDto.GiftCodeListItem convertToListItem(GiftCode giftCode) {
        AdminGiftCodeDto.GiftCodeListItem item = new AdminGiftCodeDto.GiftCodeListItem();
        item.setId(giftCode.getId());
        item.setCode(giftCode.getCode());
        item.setName(giftCode.getName());
        item.setType(giftCode.getType());
        item.setTypeName(getTypeName(giftCode.getType()));
        item.setPoints(giftCode.getPoints());
        item.setTargetRole(giftCode.getTargetRole());
        item.setTotalCount(giftCode.getTotalCount());
        item.setUsedCount(giftCode.getUsedCount());
        item.setRemainingCount(giftCode.getTotalCount() - giftCode.getUsedCount());
        item.setIsActive(giftCode.getIsActive());
        item.setStatusName(getStatusName(giftCode.getIsActive()));
        item.setExpireTime(giftCode.getExpireTime());
        item.setCreateTime(giftCode.getCreateTime());
        return item;
    }

    /**
     * 转换为详情响应DTO
     */
    private AdminGiftCodeDto.GiftCodeDetailResponse convertToDetailResponse(GiftCode giftCode) {
        AdminGiftCodeDto.GiftCodeDetailResponse response = new AdminGiftCodeDto.GiftCodeDetailResponse();
        response.setId(giftCode.getId());
        response.setCode(giftCode.getCode());
        response.setName(giftCode.getName());
        response.setDescription(giftCode.getDescription());
        response.setType(giftCode.getType());
        response.setTypeName(getTypeName(giftCode.getType()));
        response.setPoints(giftCode.getPoints());
        response.setPointsExpireDays(giftCode.getPointsExpireDays());
        response.setTargetRole(giftCode.getTargetRole());
        response.setTargetRoleName(getRoleName(giftCode.getTargetRole()));
        response.setDurationDays(giftCode.getDurationDays());
        response.setTotalCount(giftCode.getTotalCount());
        response.setUsedCount(giftCode.getUsedCount());
        response.setRemainingCount(giftCode.getTotalCount() - giftCode.getUsedCount());
        
        if (giftCode.getTotalCount() > 0) {
            response.setUsageRate((double) giftCode.getUsedCount() / giftCode.getTotalCount() * 100);
        } else {
            response.setUsageRate(0.0);
        }
        
        response.setIsActive(giftCode.getIsActive());
        response.setStatusName(getStatusName(giftCode.getIsActive()));
        response.setExpireTime(giftCode.getExpireTime());
        response.setCreateTime(giftCode.getCreateTime());
        response.setUpdateTime(giftCode.getUpdateTime());
        return response;
    }

    /**
     * 转换为使用记录列表项DTO
     */
    private AdminGiftCodeDto.UsageListItem convertToUsageListItem(Map<String, Object> usage) {
        AdminGiftCodeDto.UsageListItem item = new AdminGiftCodeDto.UsageListItem();
        item.setId(getLongFromMap(usage, "id"));
        item.setGiftCodeId(getLongFromMap(usage, "gift_code_id"));
        item.setUserId(getLongFromMap(usage, "user_id"));
        item.setUsername((String) usage.get("username"));
        item.setCode((String) usage.get("code"));
        item.setGiftCodeName((String) usage.get("gift_code_name"));
        item.setType(getIntegerFromMap(usage, "type"));
        item.setTypeName(getTypeName(getIntegerFromMap(usage, "type")));
        item.setPoints(getIntegerFromMap(usage, "points"));
        item.setTargetRole(getIntegerFromMap(usage, "target_role"));
        item.setOldRole(getIntegerFromMap(usage, "old_role"));
        item.setNewRole(getIntegerFromMap(usage, "new_role"));
        item.setOldPoints(getIntegerFromMap(usage, "old_points"));
        item.setNewPoints(getIntegerFromMap(usage, "new_points"));
        item.setStatus(getIntegerFromMap(usage, "status"));
        item.setStatusName(getUsageStatusName(getIntegerFromMap(usage, "status")));
        item.setErrorMessage((String) usage.get("error_message"));
        item.setCreateTime((LocalDateTime) usage.get("create_time"));
        return item;
    }

    /**
     * 获取类型名称
     */
    private String getTypeName(Integer type) {
        if (type == null) return "未知";
        switch (type) {
            case 1: return "积分卡";
            case 2: return "会员卡";
            default: return "未知";
        }
    }

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

    /**
     * 获取状态名称
     */
    private String getStatusName(Integer isActive) {
        return isActive != null && isActive == 1 ? "启用" : "禁用";
    }

    /**
     * 获取使用状态名称
     */
    private String getUsageStatusName(Integer status) {
        return status != null && status == 1 ? "成功" : "失败";
    }

    /**
     * 从Map中获取Long值
     */
    private Long getLongFromMap(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) return 0L;
        if (value instanceof Long) return (Long) value;
        if (value instanceof Integer) return ((Integer) value).longValue();
        if (value instanceof String) {
            try {
                return Long.parseLong((String) value);
            } catch (NumberFormatException e) {
                return 0L;
            }
        }
        return 0L;
    }

    /**
     * 从Map中获取Integer值
     */
    private Integer getIntegerFromMap(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) return null;
        if (value instanceof Integer) return (Integer) value;
        if (value instanceof Long) return ((Long) value).intValue();
        if (value instanceof String) {
            try {
                return Integer.parseInt((String) value);
            } catch (NumberFormatException e) {
                return null;
            }
        }
        return null;
    }

    @Override
    public ApiResponse<AdminGiftCodeDto.GiftCodeListResponse> getExpiredGiftCodes(Integer page, Integer size) {
        try {
            log.info("查询已过期礼品码列表: page={}, size={}", page, size);
            
            // 计算偏移量
            long offset = (long) (page - 1) * size;

            // 查询已过期礼品码列表
            List<GiftCode> giftCodes = giftCodeMapper.selectExpiredPageList(offset, size);
            log.info("查询到已过期礼品码数量: {}", giftCodes.size());

            // 统计已过期礼品码总数
            Long total = giftCodeMapper.countExpiredGiftCodes();
            log.info("已过期礼品码总数: {}", total);

            // 转换为DTO
            List<AdminGiftCodeDto.GiftCodeListItem> list = new ArrayList<>();
            for (GiftCode giftCode : giftCodes) {
                AdminGiftCodeDto.GiftCodeListItem item = convertToListItem(giftCode);
                list.add(item);
            }

            AdminGiftCodeDto.GiftCodeListResponse response = new AdminGiftCodeDto.GiftCodeListResponse();
            response.setList(list);
            response.setTotal(total);
            response.setPage(page);
            response.setSize(size);

            return ApiResponse.success(response);

        } catch (Exception e) {
            log.error("查询已过期礼品码列表失败", e);
            return ApiResponse.error("查询已过期礼品码列表失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse<String> fixUsageCountConsistency() {
        try {
            log.info("开始修复礼品码使用次数数据一致性");
            
            // 获取修复前的统计信息
            Map<String, Object> beforeStats = giftCodeMapper.getStatistics();
            Map<String, Object> usageStats = giftCodeUsageMapper.getUsageStatistics();
            
            Long beforeTotalUsage = getLongFromMap(beforeStats, "total_usage_count");
            Long actualSuccessUsage = getLongFromMap(usageStats, "success_usage_count");
            
            log.info("修复前数据 - 礼品码表统计使用次数: {}, 使用记录表成功次数: {}", beforeTotalUsage, actualSuccessUsage);
            
            // 执行数据修复
            int updatedRows = giftCodeMapper.fixUsageCountConsistency();
            log.info("修复完成，更新了 {} 行礼品码数据", updatedRows);
            
            // 获取修复后的统计信息
            Map<String, Object> afterStats = giftCodeMapper.getStatistics();
            Long afterTotalUsage = getLongFromMap(afterStats, "total_usage_count");
            
            log.info("修复后数据 - 礼品码表统计使用次数: {}", afterTotalUsage);
            
            String message = String.format("数据一致性修复完成！更新了 %d 个礼品码的使用次数。修复前: %d，修复后: %d", 
                    updatedRows, beforeTotalUsage != null ? beforeTotalUsage : 0, afterTotalUsage != null ? afterTotalUsage : 0);
            
            return ApiResponse.success(message);
            
        } catch (Exception e) {
            log.error("修复礼品码使用次数数据一致性失败", e);
            return ApiResponse.error("修复数据一致性失败: " + e.getMessage());
        }
    }
}
