package com.hotent.uc.service;

import com.hotent.base.cache.annotation.Cacheable;
import com.hotent.base.constants.CacheKeyConst;
import com.hotent.base.constants.PlatformConsts;
import com.hotent.base.util.BeanUtils;
import com.hotent.uc.manager.UcCustomManager;
import com.hotent.uc.model.CustomUser;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;

@Service
public class CustomManagerDetailsServiceImpl implements UserDetailsService {

    @Resource
    UcCustomManager customManager;

    @Cacheable(value = CacheKeyConst.EIP_UC_COUSTOM, key = "#customKey", shortExpire = true)
    @Override
    public CustomUser loadUserByUsername(String customKey) throws UsernameNotFoundException {
        CustomUser user = null;
        try{
            user = customManager.getByCustomKey(customKey);
        } catch (Exception e){
            e.printStackTrace();
            throw new UsernameNotFoundException("账号不存在");
        }
        if(BeanUtils.isEmpty(user)){
            throw new UsernameNotFoundException("账号不存在");
        }
        user.setAuthorities(initAuthority());
        return user;
    }

    private Collection<GrantedAuthority> initAuthority(){
        Collection<GrantedAuthority> authorities=new ArrayList<GrantedAuthority>();
        authorities.add(PlatformConsts.CUSTOM_USER);
        return authorities;
    }

}
