package com.ningdatech.pmapi.user.security.auth.password;


import com.ningdatech.pmapi.user.manage.UserAuthLoginManage;
import com.ningdatech.pmapi.user.security.auth.model.UserFullInfoDTO;
import com.ningdatech.pmapi.user.security.auth.model.UserInfoDetails;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author LiuXinXin
 * @date 2022/9/30 上午9:49
 */

@Service("passwordLoginUserDetailService")
@RequiredArgsConstructor
public class PasswordLoginUserDetailService implements UserDetailsService {

    private final UserAuthLoginManage userAuthLoginManage;

    @Override
    public UserInfoDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserFullInfoDTO userFullInfoDTO = userAuthLoginManage.queryUserInfoInPasswordAuth(username);
        if (Objects.isNull(userFullInfoDTO)) {
            throw new UsernameNotFoundException(String.format("%s user not exist", username));
        }
        UserInfoDetails userInfoDetails = new UserInfoDetails();
        userInfoDetails.setUserId(userFullInfoDTO.getUserId());
        userInfoDetails.setUsername(userFullInfoDTO.getUsername());
        userInfoDetails.setRealName(userFullInfoDTO.getRealName());
        userInfoDetails.setRole(userFullInfoDTO.getRole());
        userInfoDetails.setRegionCode(userFullInfoDTO.getRegionCode());
        userInfoDetails.setCompanyId(userFullInfoDTO.getCompanyId());
        userInfoDetails.setIdentifier(userFullInfoDTO.getIdentifier());
        userInfoDetails.setPassword(userFullInfoDTO.getCredential());
        return userInfoDetails;
    }
}
