package com.tykj.dev.device.user.util;

import com.tykj.dev.device.user.subject.entity.Role;
import com.tykj.dev.device.user.subject.entity.SecurityUser;
import com.tykj.dev.device.user.subject.entity.User;
import com.tykj.dev.device.user.subject.entity.UserRole;
import com.tykj.dev.device.user.subject.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户实体相关工具类
 *
 * @author HuangXiahao
 * @version V1.0
 * @class AuthenticationUtils
 * @packageName com.example.personnelmanager.common.utils
 * @data 2020/5/14
 **/
@Slf4j
public class AuthenticationUtils {
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RolePermissionsService rolePermissionsService;
    @Autowired
    PermissionsService permissionsService;
    @Autowired
    UnitsService unitsService;

    public static String ANONYMOUS_USER_STRING = "anonymousUser";
    /***
     * 获取当前登录用户
     *
     * @Return : com.example.personnelmanager.entity.UserDetail
    */
    public static SecurityUser getAuthentication(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication!=null){
            if (ANONYMOUS_USER_STRING.equals(authentication.getPrincipal())){
                log.info("当前无登录用户");
            }
            return (SecurityUser) authentication.getPrincipal();
        }else {
            log.info("当前无登录用户");
            return null;
        }

    }

    /**
     * 根据用户名称查询登入对象
     * @param userName 用户名称
     */
    private SecurityUser findUserNameToSecurity(String userName) {
        SecurityUser securityUser = new SecurityUser();
        User user = userService.findByUserName(userName);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不正确");
        } else {
            List<UserRole> userRoles = userRoleService.findByUserId(user.getUserId());
            List<Integer> roleIds = new ArrayList<>();
            if (userRoles != null) {
                for (UserRole userRole : userRoles) {
                    roleIds.add(userRole.getRoleId());
                }
            }
            List<Role> roles = roleService.findAllByRoles(roleIds);
            user.setUnits(unitsService.findById(user.getUnitsId()));
            securityUser.setCurrentUserInfo(user);
            securityUser.setRoleList(roles);
            securityUser.setUsername(userName);
            return securityUser;
        }
    }

}
