package com.ruoyi.framework.web.service;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service("userDetailsByPhonenumber")
public class UserDetailsByPhonenumberServiceImpl implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(UserDetailsByPhonenumberServiceImpl.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String phoneNumber) throws UsernameNotFoundException {
        // 防止漏查角色等所需的信息，尽量模仿根据用户名查用户的方法开发：ISysUserService.selectUserByUserName(username)
        SysUser user = userService.selectUserByUserName(phoneNumber);
        SysUser user1 = userService.selectUserByIdCard(phoneNumber);
        SysUser user2 = userService.selectUserByNickName(phoneNumber);
        if (StringUtils.isNull(user)) {
            if ( StringUtils.isNull(user1)){
                if (StringUtils.isNull(user2)){
                    log.info("登录用户：{} 不存在.", phoneNumber);
                    throw new ServiceException("登录用户：" + phoneNumber + " 不存在");
                }
                return createLoginUser(user2);
            }
            return createLoginUser(user1);
        }
//        else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
//            log.info("登录用户：{} 已被删除.", phoneNumber);
//            throw new ServiceException("对不起，您的账号：" + phoneNumber + " 已被删除");
//        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
//            log.info("登录用户：{} 已被停用.", phoneNumber);
//            throw new ServiceException("对不起，您的账号：" + phoneNumber + " 已停用");
//        }
        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
        // return new LoginUser(user, permissionService.getMenuPermission(user));
    }

}
