package com.muchinfo.mtp3century.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.muchinfo.mtp3century.service.ISysUserDetailsService;
import com.muchinfo.mtp3century.utils.RedisServiceUtil;
import com.muchinfo.mtp3common.enumtype.RedisConstants;
import com.muchinfo.mtp3interface.mapper.IRoleuserMapper;
import com.muchinfo.mtp3interface.mapper.ISystemmanagerMapper;
import com.muchinfo.mtp3pojos.entity.Roleuser;
import com.muchinfo.mtp3pojos.entity.Systemmanager;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserDetailsServiceImpl implements ISysUserDetailsService {
    @Resource
    private ISystemmanagerMapper iSystemmanagerMapper;
    @Resource
    private IRoleuserMapper iRoleuserMapper;
    @Resource
    private RedisServiceUtil redisServiceUtil;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        Systemmanager systemmanager = iSystemmanagerMapper.selectOne(new QueryWrapper<Systemmanager>().eq("LOGINCODE", userName));
        if (Objects.isNull(systemmanager)) {
            throw new UsernameNotFoundException("账号或密码错误！");
        }
        redisServiceUtil.setCacheObject("user-login-fail", systemmanager.getLogincode(), RedisConstants.LOGIN_CODE_TIME, TimeUnit.SECONDS);
        List<Roleuser> roleuserList = iRoleuserMapper.selectList(new QueryWrapper<Roleuser>().eq("MANAGERID", systemmanager.getAutoid()));
        Long[] roleCodeArray = roleuserList.stream().map(Roleuser::getRoleid).toArray(Long[]::new);

        return User.withUsername(systemmanager.getLogincode())
                .password(systemmanager.getPassword())
                .authorities(Arrays.toString(roleCodeArray))
                .build();
    }
}
