package com.liangjian.dataplatform.member.interceptor;

import com.liangjian.dataplatform.member.entity.po.secondary.WeixinUserInfo;
import com.liangjian.dataplatform.member.entity.token.JwtTokenObject;
import com.liangjian.dataplatform.member.entity.token.WeixinJwtTokenGetter;
import com.liangjian.dataplatform.member.service.IWeixinUserInfoService;
import com.liangjian.dataplatform.member.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * @Author: 黄子奇
 * @Date: 2019/11/27
 */
@Component
public class WeixinInterceptor implements HandlerInterceptor {

    @Value("${jwt.expire-time}")
    private Long expireTime;
    @Autowired
    private IWeixinUserInfoService iWeixinUserInfoService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String jwt = request.getHeader("jwt");
        if(jwt == null || jwt.isEmpty() || jwt.equals("null")) {
            return true;
        }

        Optional<JwtTokenObject<WeixinUserInfo>> opt = JwtUtil.getPlayload(jwt, WeixinUserInfo.class);
        if(opt.isEmpty()) {
            return true;
        }

        JwtTokenObject<WeixinUserInfo> tokenObject = opt.get();
        Long signTime = tokenObject.getSignTime();
        String remark = tokenObject.getRemark();
        //判断是否是预先定的类型
        //并进行失效判断
        if(remark.equals(IWeixinUserInfoService.WECHAT) || remark.equals(IWeixinUserInfoService.WEB)) {
            if(System.currentTimeMillis() > signTime + expireTime) {
                return true;
            }
        } else if(remark.equals(IWeixinUserInfoService.APP)) {
            if(System.currentTimeMillis() > signTime + (expireTime*24)) { //app两天过期
                return true;
            }
        }

        //放进threadlocal里
        WeixinJwtTokenGetter.UserInfo.set(tokenObject);

        //重新签发
        String newToken = iWeixinUserInfoService.encodeJwt(tokenObject.getObject(), tokenObject.getRemark())
                .orElseGet(() -> {
                    throw new RuntimeException("发生未知错误");
                });
        response.addHeader("jwt", newToken);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //这个线程请求要结束了，清掉ThreadLocal
        WeixinJwtTokenGetter.UserInfo.remove();
    }
}
