package org.ta.pddserver.config.security;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.ta.pdd.entity.UserEntity;
import org.ta.pdd.entity.UserRoleEntity;
import org.ta.pddserver.service.impl.UserImpl;
import org.ta.pddserver.service.impl.UserRoleImpl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserImpl userService;
    @Resource
    private UserRoleImpl userRoleImpl;
    @Resource
    PasswordEncoder passwordEncoder;
    private static Map<String, RoleUserDetails> UserMap = new HashMap();



    @Override
    public RoleUserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        log.info("UserDetailsManager loadUserByUsername username={}", username);
        if (UserMap.get(username) != null) {
            return UserMap.get(username);
        }
        UserEntity userEntity = userService.getInfoByAccount(username);
        if (userEntity == null) {
            log.info("UserDetailsManager loadUserByUsername user is null");
            //用户不存在，抛出异常
            throw new UsernameNotFoundException(username);
        }
        List<UserRoleEntity> roles = userRoleImpl.getByUserId(userEntity.getUid());
        RoleUserDetails userDetails = new RoleUserDetails();
        userDetails.setUid(userEntity.getUid());
        userDetails.setUsername(username);
        userDetails.setPassword(passwordEncoder.encode(userEntity.getPassword()));
        for (UserRoleEntity role : roles) {
            userDetails.addRole(role.getRole());
        }
        userDetails.addAuthority("all");
        UserMap.put(username, userDetails);
        return userDetails;
    }

    public RoleUserDetails checkLoginUserDetails(String username) {
        return UserMap.get(username);
    }

    public void removeUser(String username) {
        UserMap.remove(username);
    }
}
