package com.xunmei.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunmei.common.core.constant.UserConstants;
import com.xunmei.common.core.utils.StringUtils;
import com.xunmei.system.api.domain.Role;
import com.xunmei.system.api.domain.User;
import com.xunmei.system.dto.user.UserPageDto;
import com.xunmei.system.mapper.RoleMapper;
import com.xunmei.system.mapper.UserMapper;
import com.xunmei.system.service.IUserService;
import com.xunmei.system.vo.user.UserPageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Page<User> selectPage(Page<User> page, User user) {
        return baseMapper.selectPage(page, user);
    }

    @Override
    public User selectUserByUserName(String username) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("username", username);
        qw.eq("deleted", 0);
        User user = baseMapper.selectOne(qw);

        //获取用户下的权限role
        List<Role> roles = roleMapper.selectRolePermissionByUserId(user.getId());
        user.setRoles(roles);
        return user;
    }

    @Override
    public boolean checkUserNameUnique(User user) {
        Long userId = StringUtils.isNull(user.getId()) ? -1L : user.getId();
        User info = baseMapper.checkUserNameUnique(user.getUsername());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public Page<UserPageVo> selectPageData(UserPageDto request) {
        final Page<UserPageVo> page = request.getPageDto();
        Page<UserPageVo> pageData = userMapper.selectPageData(page, request);
        return pageData;
    }
}
