package com.jeesharp.business.modules.member.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jeesharp.business.modules.member.entity.MemberLevel;
import com.jeesharp.business.modules.member.mapper.MemberLevelMapper;
import com.jeesharp.business.modules.member.service.MemberLevelService;
import com.jeesharp.business.modules.member.vo.MemberLevelQueryVO;
import com.jeesharp.framework.mybatis.core.service.CrudService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 会员等级服务实现类
 *
 * @author jeesharp
 * @version 2024-01-24
 */
@Service
@Transactional(readOnly = true)
public class MemberLevelServiceImpl extends CrudService<MemberLevelMapper, MemberLevel, MemberLevelQueryVO> implements MemberLevelService {

    /**
     * 根据等级编码获取等级信息
     */
    @Override
    public MemberLevel getByLevelCode(String levelCode) {
        if (StrUtil.isBlank(levelCode)) {
            return null;
        }
        LambdaQueryWrapper<MemberLevel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MemberLevel::getLevelCode, levelCode)
                .eq(MemberLevel::getStatus, 1);
        return this.getOne(wrapper);
    }

    /**
     * 根据成长值获取对应等级
     */
    @Override
    public MemberLevel getLevelByGrowthValue(Integer growthValue) {
        if (growthValue == null) {
            growthValue = 0;
        }
        
        LambdaQueryWrapper<MemberLevel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MemberLevel::getStatus, 1)
                .eq(MemberLevel::getIsPaidLevel, 0)
                .le(MemberLevel::getMinGrowthValue, growthValue)
                .orderByDesc(MemberLevel::getLevelSort);
        
        List<MemberLevel> levels = this.list(wrapper);
        
        for (MemberLevel level : levels) {
            // 检查是否在该等级范围内
            if (level.getMaxGrowthValue() == null || growthValue <= level.getMaxGrowthValue()) {
                return level;
            }
        }
        
        // 返回最低等级
        return getByLevelCode("NORMAL");
    }

    @Override
    public List<MemberLevel> listPaidLevels() {
        LambdaQueryWrapper<MemberLevel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MemberLevel::getStatus, 1)
                .eq(MemberLevel::getIsPaidLevel, 1)
                .orderByAsc(MemberLevel::getLevelSort);
        return list(wrapper);
    }
}
