package cn.ezhizao.framework.security.service;

import cn.ezhizao.common.exception.ServiceException;
import cn.ezhizao.framework.security.LoginUser;
import cn.ezhizao.project.business.domain.BizSupplierUser;
import cn.ezhizao.project.business.service.IBizSupplierUserService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Resource
    private IBizSupplierUserService userService;

    @Resource
    private SysPasswordService passwordService;

    @Resource
    private SysPermissionService permissionService;

    @Resource
    HttpServletRequest request;

    @Override
    public UserDetails loadUserByUsername(String userName) {
        final String supplierId = request.getHeader("tenantId");
        BizSupplierUser user = userService.selectUserByUserNameAndSupplierId(userName, supplierId);
        if (user == null)
            throw new ServiceException("登录用户：" + userName + " 不存在");

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(BizSupplierUser user) {
        return new LoginUser(user.getId(), user, permissionService.getMenuPermission(user));
    }
}
