package com.ruoyi.framework.web.service;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.User;
import com.ruoyi.ss.user.domain.UserVO;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.ss.user.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
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;
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.MessageUtils;
import com.ruoyi.common.utils.StringUtils;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private IUserService userService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        /** 获取到用户类型*/
        Authentication authentication = AuthenticationContextHolder.getContext();
        if (authentication != null && authentication.getDetails() != null) {
            String userType = (String) authentication.getDetails();
            UserVO user;
            if(Constants.USER_TYPE_PC.equals(userType)){
                // PC用户登录
                user = userService.selectUserByUserName(username);
            }else if(Constants.USER_TYPE_APP.equals(userType)){
                // app用户登录 如果是app用户则用openid查询
                user = userService.selectUserByWxopenid(username);
            }else{
                // app用户登录（短信登录） 如果是app用户则用手机号
                user = userService.selectUserByUserName(username);
                verifyUser(username, user);
                if(Constants.USER_TYPE_PASSWORD.equals(userType)){
                    if(StrUtil.isBlank(user.getPassword())){
                        String password = authentication.getCredentials().toString();
                        String newPassword = SecurityUtils.encryptPassword(password);
                        userService.updateUserPwd(user.getUserId(), newPassword);
                    }else{
                        passwordService.validate(user);
                    }
                }
                return createLoginUser(user);
            }
            verifyUser(username, user);
            if(!(Constants.USER_TYPE_TEST.equals(userType) || Constants.USER_TYPE_APP.equals(userType))){
                passwordService.validate(user);
            }
            return createLoginUser(user);

        } else {
            log.info("用户类型未正常获取");
            throw new ServiceException(MessageUtils.message("user.not.type"));
        }
    }

    /** 校验用户*/
    private void verifyUser(String username, User user) {
        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException(MessageUtils.message("user.password.delete"));
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }
    }

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