package cn.feast.coding.service.system;

import cn.feast.coding.mapper.system.UserMapper;
import cn.feast.coding.model.generator.Page;
import cn.feast.coding.model.system.Permission;
import cn.feast.coding.model.system.Role;
import cn.feast.coding.model.system.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created By FeastCoding.
 */
@Service
public class UserService {

    @Autowired
    private UserMapper mapper;

    public Integer save(User user) {
        return mapper.save(user);
    }

    public void update(User user) {
        mapper.update(user);
    }

    public void deleteById(Integer id) {
        mapper.deleteById(id);
    }

    public int queryByCount(User user) {
        return mapper.queryByCount(user);
    }

    public List<User> queryByList(Page page, User user) {
        String pageQueryCondition = " limit " + page.getStart() + " , " + page.getMaxRows();
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("userName", user.getUserName());
        paramsMap.put("userPass", user.getUserPass());
        paramsMap.put("userSalt", user.getUserSalt());
        paramsMap.put("userReal", user.getUserReal());
        paramsMap.put("userGender", user.getUserGender());
        paramsMap.put("userPhone", user.getUserPhone());
        paramsMap.put("userEmail", user.getUserEmail());
        paramsMap.put("pageQueryCondition", pageQueryCondition);
        return mapper.queryByList(paramsMap);
    }

    public List<User> queryByUser(User user) {
        return mapper.queryByUser(user);
    }

    public User queryById(Integer id) {
        return mapper.queryById(id);
    }

    public User findByUsername(String username) {
        User user = mapper.findByUsername(username);
        return user;
    }

    public Set<String> findRoles(String username) {
        Set<String> roles = new HashSet<String>();
        List<Role> roleList = mapper.findRoles(username);
        for (Role r : roleList) {
            roles.add(r.getRole());
        }
        return roles;
    }

    public Set<String> findPermissions(String username) {
        Set<String> permissions = new HashSet<String>();
        List<Permission> permissionList = mapper.findPermissions(username);
        for (Permission p : permissionList) {
            permissions.add(p.getPermission());
        }
        return permissions;
    }

    public boolean checkName(String userName) {
        User user = new User();
        user.setUserName(userName);
        List<User> list = mapper.queryByUser(user);
        if(list.size() > 0){
            return true;
        }
        return false;
    }

}
