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


import com.ningdatech.pmapi.common.helper.UserInfoHelper;
import com.ningdatech.pmapi.user.constant.UserAvailableEnum;
import com.ningdatech.pmapi.user.security.auth.model.UserFullInfoDTO;
import com.ningdatech.pmapi.user.security.auth.model.UserInfoDetails;
import com.ningdatech.pmapi.user.security.auth.validate.CommonLoginException;
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("agentLoginUserDetailService")
@RequiredArgsConstructor
public class AgentLoginUserDetailService implements UserDetailsService {

    private final UserInfoHelper userInfoHelper;

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

        final Long userId = Long.parseLong(username);

        UserFullInfoDTO userFullInfoDTO = userInfoHelper.getUserFullInfo(userId);

        if (Objects.isNull(userFullInfoDTO)) {
            throw new UsernameNotFoundException(String.format("%s user not exist", username));
        }
        if (UserAvailableEnum.DISABLE.equals(userFullInfoDTO.getAvailable())) {
            throw new CommonLoginException("该账号已被禁用");
        }

        UserInfoDetails userInfoDetails = new UserInfoDetails();
        userInfoDetails.setUserId(userFullInfoDTO.getUserId());
        userInfoDetails.setUsername(userFullInfoDTO.getUsername());
        userInfoDetails.setRealName(userFullInfoDTO.getRealName());
        userInfoDetails.setUserRoleList(userFullInfoDTO.getUserRoleList());
        userInfoDetails.setRegionCode(userFullInfoDTO.getRegionCode());
        userInfoDetails.setRegionLevel(userFullInfoDTO.getRegionLevel());
        userInfoDetails.setIdentifier(userFullInfoDTO.getIdentifier());
        userInfoDetails.setPassword(userFullInfoDTO.getCredential());
        userInfoDetails.setEmployeeCode(userFullInfoDTO.getEmployeeCode());
        userInfoDetails.setOrganizationCode(userFullInfoDTO.getOrganizationCode());
        userInfoDetails.setOrganizationName(userFullInfoDTO.getOrganizationName());
        userInfoDetails.setEmpPosUnitCode(userFullInfoDTO.getEmpPosUnitCode());
        userInfoDetails.setEmpPosUnitName(userFullInfoDTO.getOrganizationName());
        return userInfoDetails;
    }
}
