package com.micer.easyball.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.micer.easyball.mapper.ClubPlayerMapper;
import com.micer.easyball.mapper.PlayerLastClubMapper;
import com.micer.easyball.mapper.UserMapper;
import com.micer.easyball.pojo.ClubPlayer;
import com.micer.easyball.pojo.LoginUser;
import com.micer.easyball.pojo.PlayerLastClub;
import com.micer.easyball.pojo.User;
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;
import org.springframework.security.authentication.BadCredentialsException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PlayerLastClubMapper playerLastClubMapper;

    @Autowired
    private ClubPlayerMapper clubPlayerMapper;

    @Override
    public UserDetails loadUserByUsername(String telephone) throws UsernameNotFoundException {

        // 查询用户信息
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("telephone", telephone));

        // 统一错误提示，不暴露账号是否存在
        if (Objects.isNull(user))
        {
            throw new BadCredentialsException("用户名或密码错误");
        }


        // 查询对应的权限信息
        List<String> list = new ArrayList<>();
        list.add(user.getCurrentRole());

        // 把数据封装成UserDetail
        return new LoginUser(user, list);
    }
}
