package com.oauth.service;


import com.alibaba.fastjson.JSON;
import com.oauth.entity.PermissionEntity;
import com.oauth.entity.RoleEntity;
import com.oauth.entity.UserEntity;
import com.oauth.mapper.UUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
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.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 * @version 1.0
 **/
@Slf4j
@Component(value = "starbosUserDetailsService")
public class StarbosUserDetailsService implements UserDetailsService {
    @Autowired
    private UUserMapper uuserMapper;

//    @Autowired
//    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("\r\nusername is:" + username);
//        // 查询数据库操作
        //将来连接数据库根据账号查询用户信息
        UserEntity userDto = uuserMapper.findByUsername(username);
//        UserDto userDto = userDao.getUserByUsername(username);
        if(userDto == null){
            //如果用户查不到，返回null，由provider来抛出异常
            return null;
        }
        //根据用户的id查询用户的权限
//        List<String> permissions = userDao.findPermissionsByUserId(userDto.getId());
        List<PermissionEntity> permissions = uuserMapper.findPermissionByUsername(userDto.getUsername());
        List<RoleEntity> roleByUsername = uuserMapper.findRoleByUsername(userDto.getUsername());

        List<String> permissionList = new ArrayList<>();
        permissions.forEach((p -> {
            permissionList.add(p.getPermTag());
        }));
        roleByUsername.forEach((p -> {
            permissionList.add("ROLE_"+p.getRoleCode());
        }));
        log.info("\r\n"+permissionList);
        //将permissions转成数组
        String[] permissionArray = new String[permissionList.size()];
//        permissionArray.
        permissionList.toArray(permissionArray);

        //将userDto转成json
        String principal = JSON.toJSONString(userDto);
        UserDetails userDetails = User.withUsername(principal).password(userDto.getPassword()).authorities(permissionArray).build();
        return userDetails;
    }
}