package cn.iocoder.yudao.module.member.service.activitymerchant;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.member.controller.admin.activitymerchant.vo.ActivityMerchantPageReqVO;
import cn.iocoder.yudao.module.member.controller.admin.activitymerchant.vo.ActivityMerchantSaveReqVO;
import cn.iocoder.yudao.module.member.dal.dataobject.activitymerchant.ActivityMerchantDO;
import cn.iocoder.yudao.module.member.dal.mysql.activitymerchant.ActivityMerchantMapper;
import cn.iocoder.yudao.module.member.util.MemberConstants;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.ACTIVITY_MERCHANT_NOT_EXISTS;

/**
 * 活动商家 Service 实现类
 *
 * @author 我是秦俊旗
 */
@Service
@Validated
public class ActivityMerchantServiceImpl implements ActivityMerchantService {

    @Resource
    private ActivityMerchantMapper activityMerchantMapper;

    @Override
    public Long createActivityMerchant(ActivityMerchantSaveReqVO createReqVO) {
        // 插入
        ActivityMerchantDO activityMerchant = BeanUtils.toBean(createReqVO, ActivityMerchantDO.class);
        activityMerchantMapper.insert(activityMerchant);
        // 返回
        return activityMerchant.getId();
    }

    @Override
    public void updateActivityMerchant(ActivityMerchantSaveReqVO updateReqVO) {
        // 校验存在
        validateActivityMerchantExists(updateReqVO.getId());
        // 更新
        ActivityMerchantDO updateObj = BeanUtils.toBean(updateReqVO, ActivityMerchantDO.class);
        activityMerchantMapper.updateById(updateObj);
    }

    @Override
    public void deleteActivityMerchant(Long id) {
        // 校验存在
        validateActivityMerchantExists(id);
        // 删除
        activityMerchantMapper.deleteById(id);
    }

    private void validateActivityMerchantExists(Long id) {
        if (activityMerchantMapper.selectById(id) == null) {
            throw exception(ACTIVITY_MERCHANT_NOT_EXISTS);
        }
    }

    @Override
    public ActivityMerchantDO getActivityMerchant(Long id) {
        return activityMerchantMapper.selectById(id);
    }

    @Override
    public PageResult<ActivityMerchantDO> getActivityMerchantPage(ActivityMerchantPageReqVO pageReqVO) {
        return activityMerchantMapper.selectPage(pageReqVO);
    }

    @Override
    public ActivityMerchantDO getByMobile(String mobile) {
        return activityMerchantMapper.selectOne(Wrappers.<ActivityMerchantDO>lambdaQuery()
                .eq(ActivityMerchantDO::getMobile, mobile).last(MemberConstants.LIMIT_ONE));
    }


}