package com.th.demo.tools;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.th.demo.model.system.ResponseCodeMsg;
import com.th.demo.model.system.ResultJSON;
import com.th.demo.model.system.SysUser;
import com.th.demo.model.system.Type;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
 
/**
 * Created by dell on 2019-01-10.
 */

public class TokenInterceptor  implements HandlerInterceptor{


    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception arg3)
            throws Exception {
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView model) throws Exception {
    }

    //拦截每个请求
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        String result="";

        String token = request.getHeader("token");
        String userId = request.getHeader("userId");
        String belongId = request.getHeader("belongId");
        String url =  request.getRequestURL().toString();
        if (url.contains("download")||url.contains("show")){
            request.setAttribute("userId",userId);
            request.setAttribute("belongId",belongId);
            return true;
        }
        //token不存在
        if(null != token) {
            SysUser user = TokenTools.unsign(token, SysUser.class);

            //解密token后的loginId与用户传来的loginId不一致，一般都是token过期
            if(null != userId && null != user) {
                if(userId.equals( user.getId())) {
                    //System.out.println(request.getRequestURL());
                    request.setAttribute("userId",userId);
                    request.setAttribute("belongId",belongId);
                    return true;
                }
                else{
                    result = JSON.toJSONString(new ResultJSON(ResponseCodeMsg.CODE_NO_TOKEN, ResponseCodeMsg.MSG_NO_TOKEN,null));
                    Tools.out(response,result);
                    return false;
                }
            }
            else
            {
                result = JSON.toJSONString(new ResultJSON(ResponseCodeMsg.CODE_NO_TOKEN, ResponseCodeMsg.MSG_NO_TOKEN,null));

                Tools.out(response,result);
                return false;
            }
        }
        else
        {
            result = JSON.toJSONString(new ResultJSON(ResponseCodeMsg.CODE_NO_TOKEN, ResponseCodeMsg.MSG_NO_TOKEN,null));
            Tools.out(response,result);
            return false;
        }
    }

}
