package com.emr.shiro;

import com.alibaba.fastjson.JSONObject;
import com.emr.util.HttpClientUtils;
import org.apache.poi.ss.formula.functions.T;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.List;

/**
 * @author HJL
 * @create 2019/4/29
 */
public class MyRealm extends AuthorizingRealm {
      //获取权限列表
    /*@Autowired
    private PermissionService permissionService;
    //获取用户
    @Autowired
    private UserService userService;
    ////获取用户角色
    @Autowired
    private RoleService roleService;*/

    @Value("${powerUrl}")
    private String powerUrl;


    /**
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录时输入的用户名
        String username = (String) principalCollection.getPrimaryPrincipal();
        if (username != null) {
            //获取用户信息
            //User user = userService.getUserByUsername(username);
            //获取用户角色
            //List<Role> roles = roleService.getRoles(username);
            //获取权限列表
            //List<String> permission = permissionService.getTheUrl(user.getId());
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            info.addStringPermission("/login");
            info.addStringPermission("index");
            info.addRole("0");

//            String url = powerUrl + "?sysFlag=emr_medical_record&userName=" + username;
//            JSONObject obj = HttpClientUtils.httpGet(url);
//            if (obj != null) {
//                if ((obj.getString("code")).equals("100")) {
//
//                }
//            }
           /* if (permission != null && !permission.isEmpty()) {
                for (String url : permission) {
                    info.addStringPermission(url);//加入权限
                }
            }
            if (roles != null && !roles.isEmpty()) {
                for (Role role : roles) {
                    info.addRole(role.getRole());//加入角色
                }
            }*/
            return info;
        }
        return null;
    }

    /**
     * 认证回调函数,登录时调用.
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //通过表单接收的用户名
        String username = token.getUsername();
        String userpwd = String.valueOf(token.getPassword());

        if (username != null && !"".equals(username)) {
            /*User user = userService.getUserByUsername(username);
            if (user != null) {
                return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
            }
            http://120.27.212.36:8888/power/font/getMenusByUserIdAndSysFlag?sysFlag=emr_medical_record&userName=admin*/
            String url = powerUrl+"?sysFlag=emr_medical_record&userName="+ username;
            JSONObject obj = HttpClientUtils.httpGet(url);
            if(obj!=null){
                if((obj.getString("code")).equals("100")){
                    //当验证都通过后，把用户信息放在 session 里
                    Session session = SecurityUtils.getSubject().getSession();
                    //session.setTimeout(4 * 3600);//以秒为单位，即在没有活动4小时后，session将失效
                    session.setTimeout(-1);//以秒为单位，session将失效
                    session.setAttribute("menuList", obj);
                    //session.setAttribute("userSession",username);
                    //session.setAttribute("userSessionId", users.get(0).getId());
                    //session.setAttribute("userRoles", org.apache.commons.lang.StringUtils.join(roleList, ","));
                    //当验证都通过后，把用户信息放在 session 里
                    JSONObject list= (JSONObject) obj.getJSONObject("extend");
                    //System.out.println(list);
                     session.setAttribute("userSession", username);
                    return new SimpleAuthenticationInfo(username, userpwd, getName());
                }
            }

        }

        return null;
    }
}
 

