package com.elephant.framework.galaxy.aroad.security.service;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.elephant.framework.galaxy.aroad.constant.CommonConstants;
import com.elephant.framework.galaxy.aroad.constant.SecurityConstants;
import com.elephant.framework.galaxy.aroad.module.system.dto.UserInfo;
import com.elephant.framework.galaxy.aroad.module.system.entity.User;
import com.elephant.framework.galaxy.aroad.module.system.service.UserService;
import com.elephant.framework.galaxy.aroad.security.entity.GalaxyUser;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * @Description
 * @auther wangjian
 * @create 2019-02-21 22:18
 */
@Slf4j
@Service
@AllArgsConstructor
public class GalaxyUserDetailsServiceImpl implements GalaxyUserDetailsService {

    private final CacheManager cacheManager;
    private final UserService userService;


    /**
     * 用户密码登录
     *
     * @param username 用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Cache cache = cacheManager.getCache("user_details");
        if (cache != null && cache.get(username) != null) {
            return (GalaxyUser) cache.get(username).get();
        }
        User user = userService.getOne(Wrappers.<User>query()
                .lambda().eq(User::getUsername, username));
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码存在");
        }
        UserInfo userInfo = userService.findUserInfo(user);
        UserDetails userDetails = getUserDetails(userInfo);
        cache.put(username, userDetails);
        return userDetails;
    }


    /**
     * 构建userdetails
     *
     * @param info 用户信息
     * @return
     */
    private UserDetails getUserDetails(UserInfo info) {
        if (info == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        Set<String> dbAuthsSet = new HashSet<>();
        if (ArrayUtil.isNotEmpty(info.getRoles())) {
            // 获取角色
            Arrays.stream(info.getRoles()).forEach(roleId -> dbAuthsSet.add(SecurityConstants.ROLE + roleId));
            // 获取资源
            dbAuthsSet.addAll(Arrays.asList(info.getPermissions()));

        }
        Collection<? extends GrantedAuthority> authorities
                = AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0]));
        User user = info.getUser();
        boolean enabled = StrUtil.equals(user.getLockFlag(), CommonConstants.STATUS_NORMAL);
        // 构造security用户
        return new GalaxyUser(user.getUserId(), user.getDeptId(), user.getTenantId(), user.getUsername(), SecurityConstants.BCRYPT + user.getPassword(), enabled,
                true, true, !CommonConstants.STATUS_LOCK.equals(user.getLockFlag()), authorities);
    }
}
