package com.rf.psychological.filter;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.rf.psychological.enums.UserRole;
import com.rf.psychological.enums.UserStatus;
import com.rf.psychological.user.service.UserService;
import com.rf.psychological.user.dao.model.UserEntity;
import com.rf.psychological.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * @author lpf
 * @description:
 * @date 2021/01/20 16:54
 */
@Slf4j
@Component
public class UserCheckInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HashMap<String, Object> resultJson = new HashMap<>();
        String uri = request.getRequestURI();
        //获取请求头token
        String token = request.getHeader("Authorization");
        String[] len = token.split(" ");
        if (len.length >1){
            token = len[1];
            JWTUtil.verify(token);
        } else if (len.length==1) {
            token = len[0];
            JWTUtil.verify(token);
        }
        //token = token.split(" ")[1];//以空格划分Bearer token，获取token
        //JWTUtil.verify(token);//验证令牌
        //从请求头中获取token
        DecodedJWT verify = JWTUtil.verify(token);
        String userId = verify.getClaim("userId").asString();
        //获取此时操作的用户类型，分别是user，admin，superAdmin
        String type = verify.getClaim("type").asString();
        if (UserRole.COMMON.getType().equals(type) || UserRole.ADMIN.getType().equals(type)) {
            UserEntity one = userService.getOne(userId);
            if (one == null) {
                resultJson.put("code", HttpServletResponse.SC_UNAUTHORIZED);
                resultJson.put("msg", "账户已被删除，请联系管理员");
                String s = JSON.toJSONString(resultJson);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println(s);
                return false;
            }
            if (one.getUserStatus().equals(UserStatus.UPDATE.getType())) {
                resultJson.put("code", HttpServletResponse.SC_UNAUTHORIZED);
                resultJson.put("msg", "登录密码被重置，请联系管理员");
                String s = JSON.toJSONString(resultJson);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println(s);
                return false;
            }
        }
        return true; //放行
    }
}
