package com.nokia.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nokia.dao.UserDao;
import com.nokia.dao.UserRoleCityDao;
import com.nokia.pojo.Area;
import com.nokia.pojo.Role;
import com.nokia.pojo.User;
import com.nokia.pojo.UserRoleCity;

@Service
public class UserService extends ServiceImpl<UserDao, User> {

    private final UserDao userDao;
    private final UserRoleCityDao userRoleCityDao;

    @Autowired
    public UserService(UserDao userDao, UserRoleCityDao userRoleCityDao) {
        this.userDao = userDao;
        this.userRoleCityDao = userRoleCityDao;
    }

    /**
     * 指定的登陆名是否已存在
     */
    public boolean hasLoginName(String loginName) {
        return null != userDao.hasLoginName(loginName);
    }

    /**
     * 用户是否存在某个权限
     */
    public boolean hasRoleCity(User user, Role role, Area city) {
        return null != userRoleCityDao.hasRoleCity(user.getUserId(), role.getRoleId(), city.getAreaId());
    }

    /**
     * 添加用户
     */
    @Transactional
    public String add(User user) {
        User query = new User();
        query.setLoginName(user.getLoginName());
        User one = baseMapper.selectOne(Wrappers.query(query));
        if (one != null) {
            return "loginName: " + user.getLoginName() + " 已存在";
        } else {
            user.setCityId(user.getCity().getAreaId());
            baseMapper.insert(user);
        }
        return "ok";
    }

    /*
     * 添加权限
     */
    public void addUserRoleCity(UserRoleCity userRoleCity) {
        userRoleCityDao.insert(userRoleCity);
    }

    /**
     * 通过用户的登录名获取用户完整信息
     */
    public User getByLoginName(String loginName) {
        return userDao.getByLoginName(loginName);
    }

}
