package com.zhongzheng.framework.web.service;

import cn.hutool.core.lang.Validator;
import com.zhongzheng.common.core.domain.entity.SysUser;
import com.zhongzheng.common.core.domain.entity.TopSysUser;
import com.zhongzheng.common.core.domain.model.LoginUser;
import com.zhongzheng.common.core.domain.model.TopLoginUser;
import com.zhongzheng.common.enums.UserStatus;
import com.zhongzheng.common.exception.BaseException;
import com.zhongzheng.modules.system.service.ISysUserService;
import com.zhongzheng.modules.top.service.ITopSysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 java.util.HashSet;
import java.util.Set;

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


    @Autowired
    private ITopSysUserService topUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        //超级管理系统用户
        TopSysUser super_user = topUserService.selectUserByUserName(username);
        if (Validator.isNull(super_user))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }
        else if (UserStatus.DELETED.getCode().equals(super_user.getDelFlag()))
        {
            log.info("登录用户：{} 已被删除.", username);
            throw new BaseException("对不起，您的账号：" + username + " 已被删除");
        }
        else if (UserStatus.DISABLE.getCode().equals(super_user.getStatus()))
        {
            log.info("登录用户：{} 已被停用.", username);
            throw new BaseException("对不起，您的账号：" + username + " 已停用");
        }
        return createTopLoginUser(super_user);
    }

    public UserDetails createTopLoginUser(TopSysUser user)
    {
        Set<String> perms = new HashSet<String>();
        //拥有所有权限
        perms.add("*:*:*");
        return new TopLoginUser(user, perms);
    }
}
