package com.yingxin.prms.config.filter;

import com.yingxin.prms.utils.TokenUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

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


/**
 * 拦截器配置实现
 *
 * @author gaozhentao
 * @version 1.0
 * @date 2020/08/31
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    private Map<String,String> tokenList;

    @Bean
    public Map<String,String> getTokenList(){
        tokenList = new HashMap<>();
        return tokenList;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception{

        String path = request.getServletPath();
        if(request.getMethod().equals("OPTIONS") ){
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        if(path.matches("/rest/(.*)")){
            response.setCharacterEncoding("utf-8");
            String token = request.getHeader("token");
            if(token != null){
                for(String key : tokenList.keySet()){
                    if(tokenList.get(key).equals(token)){
                        boolean result = TokenUtil.verify(token);
                        if(result){
                            return true;
                        }
                    }
                }
            }
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            try{
                JSONObject json = new JSONObject();
                json.put("msg","登陆超时");
                json.put("code","502");
                json.put("sign","false");
                response.getWriter().append(json.toString());
            }catch (Exception e){
                e.printStackTrace();
                response.sendError(500);
                return false;
            }
            return false;
        }else{
            return false;
        }
    }

}
