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

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.distributoruser.vo.*;
import co.yixiang.yshop.module.distributor.dal.dataobject.distributoruser.DistributorUserDO;
import co.yixiang.yshop.framework.common.pojo.PageResult;

import co.yixiang.yshop.module.distributor.convert.distributoruser.DistributorUserConvert;
import co.yixiang.yshop.module.distributor.dal.mysql.distributoruser.DistributorUserMapper;

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 DistributorUserServiceImpl implements DistributorUserService {

    @Resource
    private DistributorUserMapper userMapper;

    @Override
    public Long createUser(DistributorUserCreateReqVO createReqVO) {
        // 插入
        DistributorUserDO user = DistributorUserConvert.INSTANCE.convert(createReqVO);
        userMapper.insert(user);
        // 返回
        return user.getId();
    }

    @Override
    public void updateUser(DistributorUserUpdateReqVO updateReqVO) {
        // 校验存在
        validateUserExists(updateReqVO.getId());
        // 更新
        DistributorUserDO updateObj = DistributorUserConvert.INSTANCE.convert(updateReqVO);
        userMapper.updateById(updateObj);
    }

    @Override
    public void deleteUser(Long id) {
        // 校验存在
        validateUserExists(id);
        // 删除
        userMapper.deleteById(id);
    }

    private void validateUserExists(Long id) {
        if (userMapper.selectById(id) == null) {
            throw exception(USER_NOT_EXISTS);
        }
    }

    @Override
    public DistributorUserDO getUser(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public List<DistributorUserDO> getUserList(Collection<Long> ids) {
        return userMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<DistributorUserDO> getUserPage(DistributorUserPageReqVO pageReqVO) {
        return userMapper.selectPage(pageReqVO);
    }

    @Override
    public List<DistributorUserDO> getUserList(DistributorUserExportReqVO exportReqVO) {
        return userMapper.selectList(exportReqVO);
    }

    @Override
    public void clearance(Long id) {
        userMapper.deleteP1(id);
        userMapper.deleteP2(id);
    }

    @Override
    public DistributorUserDO getByUserId(Long userId) {
        return userMapper.selectOne(DistributorUserDO::getUserId, userId);
    }

}
