package com.platform.shiro;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.alibaba.fastjson.JSONObject;
import com.platform.cache.J2CacheUtils;
import com.platform.shiro.jwt.JwtToken;
import com.platform.service.impl.ZhiHouseService;
import com.platform.utils.Constant;
import com.platform.utils.JwtUtil;
import com.platform.utils.LettuceRedisClientUtils;
import com.platform.vos.CurrentUserLoginVo;
import com.platform.vos.TbUser;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import net.oschina.j2cache.redis.RedisUtils;
import org.apache.commons.lang.StringEscapeUtils;
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
 */
@Slf4j
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private ZhiHouseService zhiHouseService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }


    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        TbUser user = (TbUser) principals.getPrimaryPrincipal();
        Long userId = user.getId();
        Set<String> permsSet = new HashSet<String>();
        List<String> permsList;
        //系统管理员，拥有最高权限
        if (user.getRoleIdList().contains(1)) {
            permsList = zhiHouseService.getAllPerms(null);
        } else {
            permsList = zhiHouseService.getAllPerms(userId);
        }
        //用户权限列表
        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 auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        Claims claims = JwtUtil.parseJWT(token);
        String userId = claims.get("id", String.class);
        //查询用户信息
        TbUser userEntity = zhiHouseService.getByUserId(Long.valueOf(userId));

        //账号不存在
        if (userEntity == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }
        CurrentUserLoginVo user = new CurrentUserLoginVo();
        BeanUtils.copyProperties(userEntity, user);
        // 把当前用户放入到session中
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession(true);
        if (!ObjectUtils.isEmpty(user.getCompanyId())) {
            // 获取用户所在企业信息
            JSONObject componyInfo = zhiHouseService.getCompanyId(user.getCompanyId());
            if(componyInfo !=null){
                user.setCompanyName(componyInfo.getString("name"));
                user.setCompanyId(componyInfo.getLong("id"));
                user.setCompanyManagerPhoneNum(componyInfo.getString("phone"));
                user.setCompanyExpirationDate(componyInfo.getDate("expirationTime"));
            }
        }
        session.setAttribute(Constant.CURRENT_USER, user);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, token, getName());
        return info;
    }
}
