package com.zhgd.xmgl.security;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhgd.xmgl.modules.basicdata.entity.SystemUser;
import com.zhgd.xmgl.modules.basicdata.entity.SystemUserRole;
import com.zhgd.xmgl.modules.basicdata.mapper.BaseActionMapper;
import com.zhgd.xmgl.modules.basicdata.mapper.SystemUserMapper;
import com.zhgd.xmgl.modules.basicdata.mapper.SystemUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @program: devManage
 * @description:
 * @author: Mr.Peng
 * @create: 2019-09-24 11:02
 **/

@Component(value="CustomUserDetailsService")
public class MyUserDetailsImpl implements UserDetailsService {

    @Autowired
    private SystemUserMapper systemUserMapper;

    @Autowired
    private SystemUserRoleMapper systemUserRoleMapper;

    @Autowired
    private BaseActionMapper baseActionMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        final SystemUser user = systemUserMapper.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("User '" + username + "' not found");
        }
        Set<String> actionCodes = new HashSet<>();
        if (user.getIsManager()) {
            actionCodes = baseActionMapper.getActionCodes(user.getAccountType());
        } else {
            Long roleId = systemUserRoleMapper.selectOne(Wrappers.<SystemUserRole>lambdaQuery().eq(SystemUserRole::getUserId, user.getUserId())).getRoleId();
            actionCodes = baseActionMapper.getActionCodeByRole(roleId);
        }
        Collection<? extends GrantedAuthority> grantedAuthorityList = AuthorityUtils
                .createAuthorityList(actionCodes.toArray(new String[0]));
        return new SecurityUser(user.getUserId(), user.getAccount(), user.getRealName(),
                user.getUserTel(), user.getAccountType(), user.getSn(), user.getIsManager(), user.getEngineeringSn(), user.getShowPassword(),
                true,
                true, true,
                false, grantedAuthorityList);
    }

}
