package com.emr.controller;

import com.alibaba.fastjson.JSONArray;
import com.emr.entity.Power_User;
import com.emr.util.HttpClientTool;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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

public class UrlInterceptor extends HandlerInterceptorAdapter {
    @Value("${POWER_URLHEAD}")
    private String POWER_URLHEAD;
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取相对路径
        String url = request.getServletPath();
        //从session中取token
        String token = (String) request.getSession().getAttribute("token");
        String[] split = url.split("/");
        String headUrl = "/" + split[1];
        //过滤第一次进入该系统请求
        if(!"/login".equals(url) && StringUtils.isNoneBlank(token)) {
            //静态资源不拦截验证
            if (url.endsWith(".css") || url.endsWith(".js") || url.endsWith(".jpg")
                    || url.endsWith(".gif") || url.endsWith(".png")) {
                return true;
            }
            try {
                // 创建url
                String requestUrl = POWER_URLHEAD + "/font/checkToken";
                //拼接请求参数
                Map<String, String> params = new HashMap<>();
                params.put("token", token);
                // httpClient执行请求
                String resultString = HttpClientTool.doPost(requestUrl, params);
                //获取返回code
                String code = JSONArray.toJSONString(JSONObject.fromObject(resultString).get("code"));
                //100成功，200失败跳转到权限系统登录界面
                if ("200".equals(code)) {
                    response.sendRedirect(POWER_URLHEAD + "/login");
                }
            } catch (Exception e) {
                e.printStackTrace();
                //失败跳转到权限系统登录界面
                response.sendRedirect(POWER_URLHEAD + "/login");
            }
        }else{
            if("/font".equals(headUrl)){
                response.setHeader("Access-Control-Allow-Origin","*");
            }
        }
        return true;
    }
}
