package com.starry.admin.modules.custom.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.starry.admin.modules.custom.mapper.PlayCustomLevelInfoMapper;
import com.starry.admin.modules.custom.module.entity.PlayCustomLevelInfoEntity;
import com.starry.admin.modules.custom.service.IPlayCustomLevelInfoService;
import com.starry.admin.modules.system.module.entity.SysTenantEntity;
import com.starry.common.utils.IdUtils;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * 顾客等级Service业务层处理
 *
 * @author admin
 * @since 2024-05-04
 */
@Service
public class PlayCustomLevelInfoServiceImpl extends ServiceImpl<PlayCustomLevelInfoMapper, PlayCustomLevelInfoEntity>
        implements
            IPlayCustomLevelInfoService {
    @Resource
    private PlayCustomLevelInfoMapper playCustomLevelInfoMapper;

    @Override
    public void initDefaultLevel(SysTenantEntity sysTenantEntity) {
        List<PlayCustomLevelInfoEntity> list = this.selectAll();
        if (list == null || list.isEmpty()) {
            PlayCustomLevelInfoEntity entity = new PlayCustomLevelInfoEntity();
            entity.setLevel(1);
            entity.setName("V1");
            entity.setConsumptionAmount("1");
            entity.setDiscount(100);
            entity.setTenantId(sysTenantEntity.getTenantId());
            this.baseMapper.insert(entity);
        }
    }

    @Override
    public PlayCustomLevelInfoEntity getDefaultLevel() {
        List<PlayCustomLevelInfoEntity> list = this.selectAll();
        if (list != null && !list.isEmpty()) {
            return list.get(0);
        } else {
            PlayCustomLevelInfoEntity entity = new PlayCustomLevelInfoEntity();
            entity.setLevel(1);
            entity.setName("V1");
            entity.setConsumptionAmount("1");
            entity.setDiscount(100);
            this.baseMapper.insert(entity);
            return entity;
        }
    }

    @Override
    public List<PlayCustomLevelInfoEntity> selectAll() {
        LambdaQueryWrapper<PlayCustomLevelInfoEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByAsc(PlayCustomLevelInfoEntity::getLevel);
        return this.baseMapper.selectList(lambdaQueryWrapper);
    }

    /**
     * 查询顾客等级
     *
     * @param id
     *            顾客等级主键
     * @return 顾客等级
     */
    @Override
    public PlayCustomLevelInfoEntity selectPlayCustomLevelInfoById(String id) {
        return this.baseMapper.selectById(id);
    }

    /**
     * 查询顾客等级列表
     *
     * @return 顾客等级
     */
    @Override
    public List<PlayCustomLevelInfoEntity> selectPlayCustomLevelInfoByPage() {
        LambdaQueryWrapper<PlayCustomLevelInfoEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByAsc(PlayCustomLevelInfoEntity::getLevel);
        return this.baseMapper.selectList(lambdaQueryWrapper);
    }

    /**
     * 新增顾客等级
     *
     * @param playCustomLevelInfo
     *            顾客等级
     * @return 结果
     */
    @Override
    public boolean create(PlayCustomLevelInfoEntity playCustomLevelInfo) {
        if (StrUtil.isBlankIfStr(playCustomLevelInfo.getId())) {
            playCustomLevelInfo.setId(IdUtils.getUuid());
        }
        return save(playCustomLevelInfo);
    }

    /**
     * 修改顾客等级
     *
     * @param playCustomLevelInfo
     *            顾客等级
     * @return 结果
     */
    @Override
    public boolean update(PlayCustomLevelInfoEntity playCustomLevelInfo) {
        return updateById(playCustomLevelInfo);
    }

    /**
     * 批量删除顾客等级
     *
     * @param ids
     *            需要删除的顾客等级主键
     * @return 结果
     */
    @Override
    public int deletePlayCustomLevelInfoByIds(String[] ids) {
        return playCustomLevelInfoMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除顾客等级信息
     *
     * @param id
     *            顾客等级主键
     * @return 结果
     */
    @Override
    public int deletePlayCustomLevelInfoById(String id) {
        return playCustomLevelInfoMapper.deleteById(id);
    }

    @Override
    public int selectMaxLevel() {
        QueryWrapper<PlayCustomLevelInfoEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("max(level) as level ");
        PlayCustomLevelInfoEntity entity = this.baseMapper.selectOne(queryWrapper);
        return entity == null ? 0 : entity.getLevel();
    }

    @Override
    public void delMaxLevelByLevel(Integer level) {
        LambdaQueryWrapper<PlayCustomLevelInfoEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PlayCustomLevelInfoEntity::getLevel, level);
        this.baseMapper.delete(queryWrapper);
    }

    @Override
    public PlayCustomLevelInfoEntity matchLevelByConsumption(String tenantId, BigDecimal totalConsumption) {
        BigDecimal consumption = Objects.requireNonNullElse(totalConsumption, BigDecimal.ZERO);
        LambdaQueryWrapper<PlayCustomLevelInfoEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByAsc(PlayCustomLevelInfoEntity::getLevel);
        if (StrUtil.isNotBlank(tenantId)) {
            lambdaQueryWrapper.eq(PlayCustomLevelInfoEntity::getTenantId, tenantId);
        }
        List<PlayCustomLevelInfoEntity> levels = this.baseMapper.selectList(lambdaQueryWrapper);
        if (levels == null || levels.isEmpty()) {
            return null;
        }
        PlayCustomLevelInfoEntity matched = null;
        for (PlayCustomLevelInfoEntity level : levels) {
            BigDecimal threshold = parseConsumptionAmount(level.getConsumptionAmount());
            if (consumption.compareTo(threshold) >= 0) {
                matched = level;
            } else {
                break;
            }
        }
        return matched != null ? matched : levels.get(0);
    }

    private BigDecimal parseConsumptionAmount(String rawValue) {
        if (StrUtil.isBlank(rawValue)) {
            return BigDecimal.ZERO;
        }
        try {
            return new BigDecimal(rawValue.trim());
        } catch (NumberFormatException ex) {
            return BigDecimal.ZERO;
        }
    }
}
