package org.linlinjava.jz.admin.shiro;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.linlinjava.jz.admin.service.LogHelper;
import org.linlinjava.jz.admin.vo.MyUsernamePasswordToken;
import org.linlinjava.jz.admin.web.AdminAuthController;
import org.linlinjava.jz.core.util.MD5Utils;
import org.linlinjava.jz.core.util.bcrypt.BCryptPasswordEncoder;
import org.linlinjava.jz.db.domain.SysUser;
import org.linlinjava.jz.db.service.JzPermissionService;
import org.linlinjava.jz.db.service.JzRoleService;
import org.linlinjava.jz.db.service.JzSysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;

public class AdminAuthorizingRealm extends AuthorizingRealm {

    @Autowired
    private JzSysUserService adminService;
    @Autowired
    private JzRoleService roleService;
    @Autowired
    private JzPermissionService permissionService;

    private final Log logger = LogFactory.getLog(AdminAuthController.class);

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        if (principals == null) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        }

        SysUser admin = (SysUser) getAvailablePrincipal(principals);
        Integer[] roleIds = admin.getRoleIds();
        Set<String> roles = roleService.queryByIds(roleIds);
        Set<String> permissions = permissionService.queryByRoleIds(roleIds);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

    	MyUsernamePasswordToken upToken = (MyUsernamePasswordToken) token;
        //UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();
        String password = new String(upToken.getPassword());
        Integer userType = upToken.getUserType();//sys_user type 0内部账户，1加盟商账号,2微信游客注册

        if (StringUtils.isEmpty(username)) {
            throw new AccountException("用户名不能为空");
        }
        if (StringUtils.isEmpty(password)) {
            throw new AccountException("密码不能为空");
        }
        if (StringUtils.isEmpty(userType)) {
            throw new AccountException("登录类型不能为空");
        }
        //md5加密
        String pwd_md5= MD5Utils.stringToMD5(password);

        List<SysUser> adminList = adminService.userserLong(username, pwd_md5, userType);
//        Assert.state(adminList.size() < 2, "同一个用户名存在两个账户");
        if (adminList.size() == 0) {
            throw new UnknownAccountException("找不到用户（" + username + "）的帐号信息");
        }
        SysUser admin = adminList.get(0);

       
        //logger.info(password);

//        if(!pwd_md5.equals(admin.getUserPassword()))
//            throw new UnknownAccountException("找不到用户（" + username + "）的帐号信息");

       /* BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(admin.getPassword(), admin.getPassword())) {
            throw new UnknownAccountException("找不到用户（" + username + "）的帐号信息");
        }*/

        return new SimpleAuthenticationInfo(admin, password, getName());
    }

}
