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


import com.ningdatech.pmapi.user.constant.LoginTypeEnum;
import com.ningdatech.pmapi.user.manage.UserAuthLoginManage;
import com.ningdatech.pmapi.user.security.auth.constants.UserDeatilsServiceConstant;
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("credentialLoginUserDetailService")
@RequiredArgsConstructor
public class CredentialLoginUserDetailService implements UserDetailsService {

    private final UserAuthLoginManage userAuthLoginManage;

    @Override
    public UserInfoDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String[] split = username.split(UserDeatilsServiceConstant.USER_DETAILS_SERVICE_SEPARATOR);
        username = split[0];
        String loginTypeStr = split[1];
        LoginTypeEnum loginTypeEnum = LoginTypeEnum.valueOf(loginTypeStr);

        UserFullInfoDTO userFullInfoDTO = null;
        switch (loginTypeEnum) {
            case PHONE_VERIFICATION_CODE_LOGIN: {
                userFullInfoDTO = userAuthLoginManage.queryUserInfoInPhoneNoAuth(username);
            }
            break;
            case USERNAME_PASSWORD_LOGIN: {
                userFullInfoDTO = userAuthLoginManage.queryUserInfoInPasswordAuth(username);
            }
            break;
            case DING_QR_LOGIN: {
                userFullInfoDTO = userAuthLoginManage.queryUserInfoInAccountIdAuth(username);
            }
            break;
            default: {
                throw new UsernameNotFoundException(String.format("%s user not exist", 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.setUserRoleList(userFullInfoDTO.getUserRoleList());
        userInfoDetails.setRegionCode(userFullInfoDTO.getRegionCode());
        userInfoDetails.setIdentifier(userFullInfoDTO.getIdentifier());
        userInfoDetails.setPassword(userFullInfoDTO.getCredential());

        userInfoDetails.setOrganizationCode(userFullInfoDTO.getOrganizationCode());
        userInfoDetails.setOrganizationName(userFullInfoDTO.getOrganizationName());
        return userInfoDetails;
    }
}
