package com.quinn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quinn.common.QuinnConstant;
import com.quinn.common.RoleType;
import com.quinn.pojo.User;
import com.quinn.mapper.UserMapper;
import com.quinn.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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 javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author limqsh
 * @since 2020-06-28
 */
// 该接口实现类被DaoAuthenticationProvider 类使用，用于认证过程中载入用户信息。
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService,UserDetailsService {

    @Autowired
    UserService userService;
    @Autowired
    HttpSession session;

    // 用户登录逻辑和验证处理
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 通过用户名查询用户
        User user = userService.getOne(new QueryWrapper<User>().eq("username", s));

        //创建一个新的UserDetails对象，最后验证登陆的需要
        UserDetails userDetails=null;
        if(user!=null){
            //System.out.println("未加密："+user.getPassword());
            //String BCryptPassword = new BCryptPasswordEncoder().encode(user.getPassword());
            // 登录后会将登录密码进行加密，然后比对数据库中的密码，数据库密码需要加密存储！
            String password = user.getPassword();
            user.setPassword(QuinnConstant.GUN);
            // 放入session
            session.setAttribute("loginUser",user);
            session.setMaxInactiveInterval(QuinnConstant.SESSION_TIME_OUT);
            //创建一个集合来存放权限
            List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
            RoleType roleType = RoleType.parse(user.getRole());
            if (roleType == null){
                roleType = RoleType.NORMAL;
            }
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(roleType.name());
            authList.add(authority);
            //实例化UserDetails对象
            userDetails=new org.springframework.security.core.userdetails.User(s,password,
                            true,
                            true,
                            true,
                            true, authList);
        }
        return userDetails;
    }

}
