package com.dora.service.impl;

import com.dora.entity.PointsPackage;
import com.dora.mapper.PointsPackageMapper;
import com.dora.service.AdminPointsPackageService;
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.List;

/**
 * 管理端积分套餐服务实现类
 * 
 * @author 1818AI
 * @since 2025-10-24
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminPointsPackageServiceImpl implements AdminPointsPackageService {

    private final PointsPackageMapper pointsPackageMapper;

    @Override
    public List<PointsPackage> getAllPackages() {
        log.info("管理员查询所有积分套餐");
        List<PointsPackage> packages = pointsPackageMapper.selectAll();
        log.info("查询到 {} 个积分套餐", packages.size());
        return packages;
    }

    @Override
    public PointsPackage getPackageById(Long id) {
        log.info("管理员查询积分套餐详情 - id: {}", id);
        PointsPackage pointsPackage = pointsPackageMapper.selectById(id);
        if (pointsPackage == null) {
            log.warn("积分套餐不存在 - id: {}", id);
            throw new RuntimeException("积分套餐不存在");
        }
        return pointsPackage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PointsPackage createPackage(PointsPackage pointsPackage) {
        log.info("管理员创建积分套餐 - name: {}, points: {}, price: {}", 
                pointsPackage.getName(), pointsPackage.getPoints(), pointsPackage.getPrice());

        // 参数验证
        validatePackage(pointsPackage);

        // 计算总积分
        int totalPoints = pointsPackage.getPoints() + (pointsPackage.getBonusPoints() != null ? pointsPackage.getBonusPoints() : 0);
        pointsPackage.setTotalPoints(totalPoints);

        // 设置默认值
        if (pointsPackage.getBonusPoints() == null) {
            pointsPackage.setBonusPoints(0);
        }
        if (pointsPackage.getPointsExpireDays() == null) {
            pointsPackage.setPointsExpireDays(365);
        }
        if (pointsPackage.getSortOrder() == null) {
            pointsPackage.setSortOrder(0);
        }
        if (pointsPackage.getIsHot() == null) {
            pointsPackage.setIsHot(0);
        }
        if (pointsPackage.getIsActive() == null) {
            pointsPackage.setIsActive(1);
        }

        pointsPackage.setCreateTime(LocalDateTime.now());
        pointsPackage.setUpdateTime(LocalDateTime.now());
        pointsPackage.setIsDeleted(0);

        int result = pointsPackageMapper.insert(pointsPackage);
        if (result <= 0) {
            log.error("创建积分套餐失败");
            throw new RuntimeException("创建积分套餐失败");
        }

        log.info("成功创建积分套餐 - id: {}, name: {}", pointsPackage.getId(), pointsPackage.getName());
        return pointsPackage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PointsPackage updatePackage(Long id, PointsPackage pointsPackage) {
        log.info("管理员更新积分套餐 - id: {}, name: {}", id, pointsPackage.getName());

        // 检查套餐是否存在
        PointsPackage existingPackage = pointsPackageMapper.selectById(id);
        if (existingPackage == null) {
            log.warn("积分套餐不存在 - id: {}", id);
            throw new RuntimeException("积分套餐不存在");
        }

        // 参数验证
        validatePackage(pointsPackage);

        // 设置ID和更新时间
        pointsPackage.setId(id);
        pointsPackage.setUpdateTime(LocalDateTime.now());

        // 计算总积分
        int totalPoints = pointsPackage.getPoints() + (pointsPackage.getBonusPoints() != null ? pointsPackage.getBonusPoints() : 0);
        pointsPackage.setTotalPoints(totalPoints);

        // 设置默认值
        if (pointsPackage.getBonusPoints() == null) {
            pointsPackage.setBonusPoints(0);
        }
        if (pointsPackage.getPointsExpireDays() == null) {
            pointsPackage.setPointsExpireDays(365);
        }
        if (pointsPackage.getSortOrder() == null) {
            pointsPackage.setSortOrder(0);
        }
        if (pointsPackage.getIsHot() == null) {
            pointsPackage.setIsHot(0);
        }
        if (pointsPackage.getIsActive() == null) {
            pointsPackage.setIsActive(1);
        }

        int result = pointsPackageMapper.updateById(pointsPackage);
        if (result <= 0) {
            log.error("更新积分套餐失败 - id: {}", id);
            throw new RuntimeException("更新积分套餐失败");
        }

        log.info("成功更新积分套餐 - id: {}, name: {}", id, pointsPackage.getName());
        return pointsPackage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePackageStatus(Long id, Integer isActive) {
        log.info("管理员更新积分套餐状态 - id: {}, isActive: {}", id, isActive);

        // 检查套餐是否存在
        PointsPackage existingPackage = pointsPackageMapper.selectById(id);
        if (existingPackage == null) {
            log.warn("积分套餐不存在 - id: {}", id);
            throw new RuntimeException("积分套餐不存在");
        }

        // 验证状态值
        if (isActive == null || (isActive != 0 && isActive != 1)) {
            log.warn("无效的状态值 - isActive: {}", isActive);
            throw new RuntimeException("无效的状态值，必须为0或1");
        }

        int result = pointsPackageMapper.updateStatus(id, isActive);
        if (result <= 0) {
            log.error("更新积分套餐状态失败 - id: {}", id);
            throw new RuntimeException("更新积分套餐状态失败");
        }

        log.info("成功更新积分套餐状态 - id: {}, isActive: {}", id, isActive);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deletePackage(Long id) {
        log.info("管理员删除积分套餐 - id: {}", id);

        // 检查套餐是否存在
        PointsPackage existingPackage = pointsPackageMapper.selectById(id);
        if (existingPackage == null) {
            log.warn("积分套餐不存在 - id: {}", id);
            throw new RuntimeException("积分套餐不存在");
        }

        int result = pointsPackageMapper.deleteById(id);
        if (result <= 0) {
            log.error("删除积分套餐失败 - id: {}", id);
            throw new RuntimeException("删除积分套餐失败");
        }

        log.info("成功删除积分套餐 - id: {}", id);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePackageSort(List<Long> packageIds) {
        log.info("管理员批量更新积分套餐排序 - packageIds: {}", packageIds);

        if (packageIds == null || packageIds.isEmpty()) {
            log.warn("套餐ID列表为空");
            throw new RuntimeException("套餐ID列表不能为空");
        }

        try {
            for (int i = 0; i < packageIds.size(); i++) {
                Long packageId = packageIds.get(i);
                
                // 检查套餐是否存在
                PointsPackage existingPackage = pointsPackageMapper.selectById(packageId);
                if (existingPackage == null) {
                    log.warn("积分套餐不存在 - id: {}", packageId);
                    continue; // 跳过不存在的套餐
                }

                // 更新排序，从1开始
                existingPackage.setSortOrder(i + 1);
                existingPackage.setUpdateTime(LocalDateTime.now());
                pointsPackageMapper.updateById(existingPackage);
            }

            log.info("成功更新积分套餐排序");
            return true;
        } catch (Exception e) {
            log.error("批量更新积分套餐排序失败", e);
            throw new RuntimeException("批量更新积分套餐排序失败：" + e.getMessage());
        }
    }

    @Override
    public PackageStatsResponse getPackageStats() {
        log.info("管理员查询积分套餐统计信息");

        Long totalPackages = pointsPackageMapper.countAll();
        Long activePackages = pointsPackageMapper.countActive();
        
        // 查询热门套餐数量
        List<PointsPackage> hotPackages = pointsPackageMapper.selectHotPackages(100); // 查询所有热门套餐
        Long hotPackagesCount = (long) hotPackages.size();

        PackageStatsResponse stats = new PackageStatsResponse(totalPackages, activePackages, hotPackagesCount);
        
        log.info("积分套餐统计 - 总数: {}, 上架: {}, 热门: {}", totalPackages, activePackages, hotPackagesCount);
        
        return stats;
    }

    // ==================== 私有方法 ====================

    /**
     * 验证套餐参数
     */
    private void validatePackage(PointsPackage pointsPackage) {
        if (pointsPackage.getName() == null || pointsPackage.getName().trim().isEmpty()) {
            throw new RuntimeException("套餐名称不能为空");
        }
        if (pointsPackage.getName().length() > 64) {
            throw new RuntimeException("套餐名称长度不能超过64个字符");
        }
        if (pointsPackage.getDescription() != null && pointsPackage.getDescription().length() > 255) {
            throw new RuntimeException("套餐描述长度不能超过255个字符");
        }
        if (pointsPackage.getPoints() == null || pointsPackage.getPoints() <= 0) {
            throw new RuntimeException("基础积分数量必须大于0");
        }
        if (pointsPackage.getPrice() == null || pointsPackage.getPrice().compareTo(java.math.BigDecimal.ZERO) <= 0) {
            throw new RuntimeException("套餐价格必须大于0");
        }
        if (pointsPackage.getBonusPoints() != null && pointsPackage.getBonusPoints() < 0) {
            throw new RuntimeException("赠送积分数量不能为负数");
        }
        if (pointsPackage.getPointsExpireDays() != null && pointsPackage.getPointsExpireDays() <= 0) {
            throw new RuntimeException("积分有效期必须大于0天");
        }
        if (pointsPackage.getDiscountLabel() != null && pointsPackage.getDiscountLabel().length() > 32) {
            throw new RuntimeException("优惠标签长度不能超过32个字符");
        }
    }
}
