package cn.newfeifan.mall.module.service.merchant;

import cn.newfeifan.mall.module.controller.admin.merchant.vo.MerchantPageReqVO;
import cn.newfeifan.mall.module.controller.admin.merchant.vo.MerchantSaveReqVO;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import cn.newfeifan.mall.module.dal.dataobject.merchant.MerchantDO;
import cn.newfeifan.mall.framework.common.pojo.PageResult;
import cn.newfeifan.mall.framework.common.util.object.BeanUtils;

import cn.newfeifan.mall.module.dal.mysql.merchant.MerchantMapper;

import static cn.newfeifan.mall.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.newfeifan.mall.module.enums.ErrorCodeConstants.MERCHANT_NOT_EXISTS;

/**
 * 商户 Service 实现类
 *
 * @author 非繁人
 */
@Service
@Validated
public class MerchantServiceImpl implements MerchantService {

    @Resource
    private MerchantMapper merchantMapper;

    @Override
    public Long createMerchant(MerchantSaveReqVO createReqVO) {
        // 插入
        MerchantDO merchant = BeanUtils.toBean(createReqVO, MerchantDO.class);
        merchantMapper.insert(merchant);
        // 返回
        return merchant.getId();
    }

    @Override
    public void updateMerchant(MerchantSaveReqVO updateReqVO) {
        // 校验存在
        validateMerchantExists(updateReqVO.getId());
        // 更新
        MerchantDO updateObj = BeanUtils.toBean(updateReqVO, MerchantDO.class);
        merchantMapper.updateById(updateObj);
    }

    @Override
    public void deleteMerchant(Long id) {
        // 校验存在
        validateMerchantExists(id);
        // 删除
        merchantMapper.deleteById(id);
    }

    private void validateMerchantExists(Long id) {
        if (merchantMapper.selectById(id) == null) {
            throw exception(MERCHANT_NOT_EXISTS);
        }
    }

    @Override
    public MerchantDO getMerchant(Long id) {
        return merchantMapper.selectById(id);
    }

    @Override
    public PageResult<MerchantDO> getMerchantPage(MerchantPageReqVO pageReqVO) {
        return merchantMapper.selectPage(pageReqVO);
    }

}