package com.fdkanfang.web.shiro;

import com.alibaba.fastjson.JSONObject;
import com.fdkanfang.common.enums.ResultCodeEnum;
import com.fdkanfang.common.exception.JwtAuthenticationException;
import com.fdkanfang.common.util.HttpClientUtil;
import com.fdkanfang.domain.backend.UserEntity;
import com.fdkanfang.service.backend.ResourceService2;
import com.fdkanfang.service.backend.UserService2;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 配置不校验的话，是不会走这个方法的
 */
@Log4j2
@Service
public class MyRealm extends AuthorizingRealm {



    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserService2 userService2;


    @Autowired
    private ResourceService2 resourceService2;

    @Value("${4dkankan.host}")
    private String KankanHost;



    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     *
     * principals： 是token
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = JWTUtil.getUserName(principals.toString());
        UserEntity dbUser = userService2.findByUserName(username);

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();


        Set<String> rolekeys  = userService2.findRoleByUserId(dbUser.getId());




        Set<String>  permissions = resourceService2.findResourceKeyByUserId(dbUser.getId());

        // 设置角色、权限
        simpleAuthorizationInfo.addRoles(rolekeys);
        simpleAuthorizationInfo.addStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        if (token == null) {
            log.error("token is null");
            throw new JwtAuthenticationException(5001, "token is null");
        }
        // 解密获得username，用于和数据库进行对比
        String username = JWTUtil.getUserName(token);
        if (username == null) {
            log.error("error token username");
            throw new JwtAuthenticationException(5001, "账户登录已过期，请重新登录");

        }

        UserEntity user = userService2.findByUserName(username);
        if (user == null) {
            log.error("error token user");
            throw new JwtAuthenticationException(5001, "User didn't existed!");
        }

        // 校验请求token是否跟redis token一致 TODO:改成从看看中获取token
        validateToken(token);

       /* String redisToken = redisTemplate.opsForValue().get(user.getUserName());
        if (!token.equals(redisToken)) {
            log.error("error token redis");
            throw new JwtAuthenticationException(5001, "token invalid");

        }*/


     /*   if (! JWTUtil.verify(token, username, user.getPassword())) {
            log.error("error token username or password");
            throw new JwtAuthenticationException(5001, "token invalid");
        }*/


        return new SimpleAuthenticationInfo(token, token, "my_realm");
    }

    private void validateToken(String token) {
        String url = KankanHost + "api/sso/user/checkToken";
        log.info("验证token的url:{}",url);
        Map<String , Object> headers = new HashMap<>();
        headers.put("token" , token);
        String kankanResult = HttpClientUtil.doPostJsonWithHeader(url, ""  , headers);
        //把信息封装为json
        JSONObject res = JSONObject.parseObject(kankanResult);
        if(null != res){
            log.info("登录态校验接口返回:{}", res.toJSONString());
            int code = -10;
            if(res.containsKey("code")){
                code = (int) res.get("code");
                if(code != 0){
                    throw new JwtAuthenticationException(ResultCodeEnum.D3002.getCode() , "账户登录已过期，请重新登录");
                }
            }else{
                throw new JwtAuthenticationException(ResultCodeEnum.D3002.getCode() , "账户登录已过期，请重新登录");
            }
        }
        log.info("验证token完成");

    }
}
