package com.hz.pm.api.user.security.auth.credential;


import com.hz.pm.api.user.model.enumeration.LoginTypeEnum;
import com.hz.pm.api.user.model.enumeration.UserAvailableEnum;
import com.hz.pm.api.user.convert.UserInfoConvertor;
import com.hz.pm.api.user.manage.UserInfoManage;
import com.hz.pm.api.user.security.auth.constants.UserDetailsServiceConstant;
import com.hz.pm.api.user.security.model.UserFullInfoDTO;
import com.hz.pm.api.user.security.model.UserInfoDetails;
import com.hz.pm.api.user.security.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("credentialLoginUserDetailService")
@RequiredArgsConstructor
public class CredentialLoginUserDetailService implements UserDetailsService {

    private final UserInfoManage userInfoManage;

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

        UserFullInfoDTO userFullInfo;
        switch (loginTypeEnum) {
            case PHONE_VERIFICATION_CODE_LOGIN: {
                userFullInfo = userInfoManage.queryUserInfoInPhoneNoAuth(username);
                if (Objects.isNull(userFullInfo)) {
                    throw new CommonLoginException("该手机号未绑定用户");
                }
            }
            break;
            case USERNAME_PASSWORD_LOGIN: {
                userFullInfo = userInfoManage.queryUserInfoInPasswordAuth(username);
                if (Objects.isNull(userFullInfo)) {
                    throw new UsernameNotFoundException(String.format("%s user not exist", username));
                }
            }
            break;
            case DING_MD_LOGIN:
            case DING_QR_LOGIN: {
                userFullInfo = userInfoManage.queryUserInfoInAccountIdAuth(username);
                if (Objects.isNull(userFullInfo)) {
                    throw new CommonLoginException("浙政钉账号无法登陆");
                }
            }
            break;
            default: {
                throw new UsernameNotFoundException(String.format("%s user not exist", username));
            }
        }

        if (UserAvailableEnum.DISABLE.equals(userFullInfo.getAvailable())) {
            throw new CommonLoginException("该账号已被禁用");
        }
        return UserInfoConvertor.convert(userFullInfo);
    }
}
