package com.auth.module.security.service.impl;

import com.auth.dao.base.entity.UserEntity;
import com.auth.dao.base.mapper.v1.UserMapper;
import com.auth.dao.base.view.UserRolePermission;
import com.auth.module.security.service.DbUserDetailService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.jaas.JaasGrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
@RequiredArgsConstructor
public class DbUserDetailServiceImpl implements DbUserDetailService {

    private final UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询当前用户
        UserEntity userEntity = userMapper.selectByUsername(username);

        // 判断当前用户是否存在
        if (userEntity == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        Long userId = userEntity.getId();
        List<JaasGrantedAuthority> jaasGrantedAuthorities = new ArrayList<>();

        List<UserRolePermission> userRolePermissionList = userMapper.selectUserRolePermissionByUsername(userId);
        Map<String, List<UserRolePermission>> roleCodeMap = userRolePermissionList.stream().collect(Collectors.groupingBy(UserRolePermission::getRoleCode));
        roleCodeMap.forEach((s, permissionCode) -> {
            List<SimpleGrantedAuthority> permissions = getPermissionByRoleCode(s, roleCodeMap).stream().map(SimpleGrantedAuthority::new).toList();
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(s, null, permissions);
            JaasGrantedAuthority jaasGrantedAuthority = new JaasGrantedAuthority(s, (Principal) usernamePasswordAuthenticationToken.getPrincipal());
            jaasGrantedAuthorities.add(jaasGrantedAuthority);
        });

        List<String> roles = userRolePermissionList.stream().map(UserRolePermission::getRoleCode).toList();

        return User.builder()
                .username(username)
                .password(userEntity.getPassword())
                .roles(roles.toArray(String[]::new))
                .authorities(jaasGrantedAuthorities)
                // 0=禁用,1=正常,2=锁定
                .disabled(!userEntity.getStatus().equals(1))
                .build();
    }

    /**
     * 根据角色码获取当前角色权限
     *
     * @param userRolePermissionList 用户角色权限关系列表
     * @return 权限Code
     */
    private List<String> getPermissionByRoleCode(String roleCode, Map<String, List<UserRolePermission>> userRolePermissionList) {
        return userRolePermissionList.get(roleCode)
                .stream().map(UserRolePermission::getPermissionCode)
                .toList();
    }

}
