package cn.iocoder.yudao.module.system.service.position;

import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.system.controller.admin.position.vo.PositionPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.position.vo.PositionSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.position.PositionDO;
import cn.iocoder.yudao.module.system.dal.mysql.position.PositionMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.POSITION_NOT_EXISTS;

/**
 * 岗位信息 Service 实现类
 *
 * @author 符溶馨
 */
@Service
@Validated
public class PositionServiceImpl implements PositionService {

    @Resource
    private PositionMapper positionMapper;

    @Override
    public Long createPosition(PositionSaveReqVO createReqVO) {
        // 插入
        PositionDO position = BeanUtils.toBean(createReqVO, PositionDO.class);
        positionMapper.insert(position);
        // 返回
        return position.getId();
    }

    @Override
    public void updatePosition(PositionSaveReqVO updateReqVO) {
        // 校验存在
        validatePositionExists(updateReqVO.getId());
        // 更新
        PositionDO updateObj = BeanUtils.toBean(updateReqVO, PositionDO.class);
        positionMapper.updateById(updateObj);
    }

    @Override
    public void deletePosition(Long id) {
        // 校验存在
        validatePositionExists(id);
        // 删除
        positionMapper.deleteById(id);
    }

    private void validatePositionExists(Long id) {
        if (positionMapper.selectById(id) == null) {
            throw exception(POSITION_NOT_EXISTS);
        }
    }

    @Override
    public PositionDO getPosition(Long id) {
        return positionMapper.selectById(id);
    }

    @Override
    public PageResult<PositionDO> getPositionPage(PositionPageReqVO pageReqVO) {
        return positionMapper.selectPage(pageReqVO);
    }

    @Override
    public List<PositionDO> getPositionList() {
        return positionMapper.selectList(PositionDO::getStatus, CommonStatusEnum.ENABLE.getStatus());
    }

    @Override
    public List<PositionDO> getPositionList(List<Long> ids) {
        return positionMapper.selectList(new LambdaQueryWrapperX<PositionDO>()
                .eq(PositionDO::getStatus, CommonStatusEnum.ENABLE.getStatus())
                .inIfPresent(PositionDO::getId, ids));
    }
}