package com.gyee.wisdom.alarm.sharding.filter;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.gyee.wisdom.alarm.sharding.entity.AlarmUser;
import com.gyee.wisdom.alarm.sharding.service.AlarmUserService;
import com.gyee.wisdom.alarm.sharding.util.PassToken;
import com.gyee.wisdom.alarm.sharding.util.UserLoginToken;
import com.gyee.wisdom.alarm.sharding.util.ResponseWrapper;
import com.gyee.wisdom.alarm.sharding.util.TokenUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @descrition:拦截器，拦截token
 * @author:Wanghs
 * @date:2020-05-21
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    protected AlarmUserService alarmUserService;

    //提供查询
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
    }

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        String headerToken = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
        ServletOutputStream resultWriter = httpServletResponse.getOutputStream();
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(UserLoginToken.class)) {
            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
            if (userLoginToken.required()) {
                // 执行认证
                if (headerToken == null) {
                    ResponseWrapper wrapper=ResponseWrapper.error("请登陆!",521);
                    resultWriter.write(JSON.toJSONString(wrapper).getBytes());
                    resultWriter.flush();
                    resultWriter.close();
                    return false;
                }

                //解析Token信息
                try {
                    //根据token获取用户名
                    Claims claims = TokenUtil.parseJWT(headerToken);
                    String tokenUserName = (String) claims.get("jti");

                    //根据用户名获取用户
                    AlarmUser myTokenUser = alarmUserService.isExistUser(tokenUserName);

                    //如果用户名不存在,则说明token错误
                    if (null == myTokenUser) {
                        ResponseWrapper wrapper=ResponseWrapper.error("身份验证错误,请重新登陆!",521);
                        resultWriter.write(JSON.toJSONString(wrapper).getBytes());
                        resultWriter.flush();
                        resultWriter.close();
                        return false;
                    }

                    //判断Token过期
                    Date tokenDate = claims.getExpiration();
                    int overTime = (int) (new Date().getTime() - tokenDate.getTime()) / 1000;
                    //过期时间为一个小时
                    if (overTime > 60*60  ) {
                        ResponseWrapper wrapper=ResponseWrapper.error("身份验证过期,请重新登陆!",521);
                        resultWriter.write(JSON.toJSONString(wrapper).getBytes());
                        resultWriter.flush();
                        resultWriter.close();
                        return false;
                    }

                } catch (Exception e) {
                    ResponseWrapper wrapper=ResponseWrapper.error("身份验证错误,请重新登陆!",521);
                    resultWriter.write(JSON.toJSONString(wrapper).getBytes());
                    resultWriter.flush();
                    resultWriter.close();
                    return false;
                }
                return true;
            }
        }
        return true;
    }
}
