package com.platform.shiro;

import com.platform.cache.J2CacheUtils;
import com.platform.dao.SysDeptDao;
import com.platform.dao.SysMenuDao;
import com.platform.dao.SysUserDao;
import com.platform.dao.SysUserRoleDao;
import com.platform.entity.SysDeptEntity;
import com.platform.entity.SysMenuEntity;
import com.platform.entity.SysUserEntity;
import com.platform.utils.Constant;
import com.platform.vos.CurrentUserLoginVo;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * 认证
 *
 * @author lipengjun
 * @date 2017年11月19日 上午9:49:19
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysMenuDao sysMenuDao;

    @Autowired
    private SysDeptDao sysDeptDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SysUserEntity user = (SysUserEntity) principals.getPrimaryPrincipal();
        Long userId = user.getUserId();

        List<String> permsList;

        //系统管理员，拥有最高权限
        if (userId == Constant.SUPER_ADMIN) {
            List<SysMenuEntity> menuList = sysMenuDao.queryList(new HashMap<>());
            permsList = new ArrayList<>(menuList.size());
            for (SysMenuEntity menu : menuList) {
                permsList.add(menu.getPerms());
            }
        } else {
            permsList = sysUserDao.queryAllPerms(userId);
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<String>();
        if (permsList != null && permsList.size() != 0) {
            for (String perms : permsList) {
                if (StringUtils.isBlank(perms)) {
                    continue;
                }
                permsSet.addAll(Arrays.asList(perms.trim().split(",")));
            }
        }

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());

        //查询用户信息
        SysUserEntity userEntity = sysUserDao.queryByUserMobile(username);

        //账号不存在
        if (userEntity == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }

        //账号锁定
        if (userEntity.getStatus() == 0) {
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        // 获取用户角色
        List<Long> roles = sysUserRoleDao.queryRoleIdList(userEntity.getUserId());
        if(ObjectUtils.isEmpty(roles)){
            throw new AuthenticationException("用户角色为空！");
        }
        Long roleId = roles.stream().min(Comparator.naturalOrder()).get();
        CurrentUserLoginVo user = new CurrentUserLoginVo();
        BeanUtils.copyProperties(userEntity,user);
        user.setRoleIdList(roles);
        user.setRoleId(roleId);
        // 把当前用户放入到session中
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession(true);
        if(!ObjectUtils.isEmpty(user.getDeptId())){
            // 获取用户所在企业信息
            SysDeptEntity deptEntity = sysDeptDao.queryObject(user.getDeptId());
            user.setDeptName(deptEntity.getName());
            user.setDeptManagerPhoneNum(deptEntity.getManagerPhoneNum());
            user.setDeptExpirationDate(deptEntity.getExpirationDate());
            user.setParentDeptId(deptEntity.getParentId());
            user.setParentDeptName(deptEntity.getParentName());
        }
        session.setAttribute(Constant.CURRENT_USER, user);
        List<String> permsList;
        //系统管理员，拥有最高权限
        if (Constant.SUPER_ADMIN == user.getUserId()) {
            List<SysMenuEntity> menuList = sysMenuDao.queryList(new HashMap<String, Object>());
            permsList = new ArrayList<>(menuList.size());
            for (SysMenuEntity menu : menuList) {
                permsList.add(menu.getPerms());
            }
        } else {
            permsList = sysUserDao.queryAllPerms(user.getUserId());
        }
        J2CacheUtils.put(Constant.PERMS_LIST + user.getUserId(), permsList);

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
        return info;
    }

}
