package co.yixiang.yshop.module.distributor.service.distributorlevel;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.util.*;

import co.yixiang.yshop.module.distributor.controller.admin.distributorlevel.vo.*;
import co.yixiang.yshop.module.distributor.dal.dataobject.distributorlevel.DistributorLevelDO;
import co.yixiang.yshop.framework.common.pojo.PageResult;

import co.yixiang.yshop.module.distributor.convert.distributorlevel.DistributorLevelConvert;
import co.yixiang.yshop.module.distributor.dal.mysql.distributorlevel.DistributorLevelMapper;

import static co.yixiang.yshop.framework.common.exception.util.ServiceExceptionUtil.exception;
import static co.yixiang.yshop.module.distributor.enums.ErrorCodeConstants.*;

/**
 * 分销商等级 Service 实现类
 *
 * @author admin
 */
@Service
@Validated
public class DistributorLevelServiceImpl implements DistributorLevelService {

    @Resource
    private DistributorLevelMapper levelMapper;

    @Override
    public Long createLevel(DistributorLevelCreateReqVO createReqVO) {
        // 插入
        DistributorLevelDO level = DistributorLevelConvert.INSTANCE.convert(createReqVO);
        levelMapper.insert(level);
        // 返回
        return level.getId();
    }

    @Override
    public void updateLevel(DistributorLevelUpdateReqVO updateReqVO) {
        // 校验存在
        validateLevelExists(updateReqVO.getId());
        // 更新
        DistributorLevelDO updateObj = DistributorLevelConvert.INSTANCE.convert(updateReqVO);
        levelMapper.updateById(updateObj);
    }

    @Override
    public void deleteLevel(Long id) {
        // 校验存在
        validateLevelExists(id);
        // 删除
        levelMapper.deleteById(id);
    }

    private void validateLevelExists(Long id) {
        if (levelMapper.selectById(id) == null) {
            throw exception(LEVEL_NOT_EXISTS);
        }
    }

    @Override
    public DistributorLevelDO getLevel(Long id) {
        return levelMapper.selectById(id);
    }

    @Override
    public List<DistributorLevelDO> getLevelList(Collection<Long> ids) {
        return levelMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<DistributorLevelDO> getLevelPage(DistributorLevelPageReqVO pageReqVO) {
        return levelMapper.selectPage(pageReqVO);
    }

    @Override
    public List<DistributorLevelDO> getLevelList(DistributorLevelExportReqVO exportReqVO) {
        return levelMapper.selectList(exportReqVO);
    }

    @Override
    public DistributorLevelDO getDefaultLevel() {
        return levelMapper.selectOne(DistributorLevelDO::getLevel, 1);
    }

}
