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 lombok.extern.slf4j.Slf4j;

@Slf4j
@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;
    }

    /**
     * 添加用户，不考虑权限
     * 
     * @param user
     * @return
     */
    public boolean addUser(User user) {
        // 检查是否已存在同名用户
        if (hasLoginName(user.getLoginName())) {
            log.debug("", user.getLoginName());
            return false;
        }
        userDao.insert(user);
        return true;
    }

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

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

    /**
     * 添加用户
     * 
     * @param user
     * @return
     */
    @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";
    }

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

}
