package com.purui.prims.auth.authentication.persistence.repository.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.purui.prims.auth.authentication.persistence.dataobject.RoleDO;
import com.purui.prims.auth.authentication.persistence.dataobject.UserDO;
import com.purui.prims.auth.authentication.persistence.dataobject.UserDOExample;
import com.purui.prims.auth.authentication.persistence.mapper.RoleDOMapper;
import com.purui.prims.auth.authentication.persistence.mapper.UserDOMapper;
import com.purui.prims.auth.authentication.persistence.repository.UserRepository;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

@Component
public class UserRepositoryImpl implements UserRepository {


    private UserDOMapper userDOMapper;

    private RoleDOMapper roleDOMapper;


    public UserRepositoryImpl(UserDOMapper userDOMapper, RoleDOMapper roleDOMapper) {
        this.userDOMapper = userDOMapper;
        this.roleDOMapper = roleDOMapper;
    }

    @Override
    public List<UserDO> getUserList() {
        return userDOMapper.selectByExample(new UserDOExample());
    }

    @Override
    public void addUser(UserDO userDO) {
        if (userDO.getRoleId() == null) {
            userDO.setRoleId(0);
        }
        userDOMapper.insert(userDO);
    }

    @Override
    public void updateUser(UserDO userDO) {
        userDOMapper.updateById(userDO);
    }

    @Override
    public UserDO getUser(String name) {
        UserDOExample userDOExample = new UserDOExample();
        userDOExample.createCriteria().andUserNameEqualTo(name);
        List<UserDO> userDOS = userDOMapper.selectByExample(userDOExample);
        Optional<UserDO> userDOOptional = userDOS.stream().findFirst();
        return userDOOptional.orElse(null);
    }

    @Override
    public List<UserDO> getUserByRoleId(Integer roleId) {
        UserDOExample userDOExample = new UserDOExample();
        userDOExample.createCriteria().andRoleIdEqualTo(roleId);
        List<UserDO> userDOS = userDOMapper.selectByExample(userDOExample);
        return userDOS;
    }

    @Override
    public List<RoleDO> getRoles() {
        QueryWrapper<RoleDO> queryWrapper = new QueryWrapper<>();
        return roleDOMapper.selectList(queryWrapper);
    }

    @Override
    public RoleDO getRole(Integer id) {
        return roleDOMapper.selectById(id);
    }

}
