/**
 * Copyright (C), 2015-2019
 * Author:   HJL
 * Date:     2019/8/22 13:49
 * Description:
 */
package com.emr.controller;

import com.emr.entity.Power_User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class UrlInterceptor implements HandlerInterceptor {
    @Value("${POWER_URLHEAD}")
    private String POWER_URLHEAD;

    @Value("${powerUrl}")
    private String powerUrl;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
//        String url = request.getServletPath();
//        String token = "";
//        if (!"/login".equals(url) && StringUtils.isNoneBlank(token)) {
//            token = (String) request.getSession().getAttribute("token");
//            if (StringUtils.isNoneBlank(token)) {
//                JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
//                Client client = dcf.createClient(POWER_URLHEAD + "/WebService/PowerWebService?wsdl");
//                Object[] objects = new Object[0];
//                Power_User powerUser = new Power_User();
//                try {
//                    objects = client.invoke("getInfosByUserId", token, "emr_medical_record");
//                    ObjectMapper mapper = new ObjectMapper();
//                    powerUser = mapper.readValue(objects[0].toString(), Power_User.class);
//                    UsernamePasswordToken userToken = new UsernamePasswordToken(powerUser.getUserName(), "123456");
//                    Subject subject = SecurityUtils.getSubject();
//                    subject.login(userToken);
//                    //设置进session
//                    request.getSession().setAttribute("CURRENT_USER", powerUser);
//
//                    if (null == powerUser.getUserId()) {
//                        response.sendRedirect(POWER_URLHEAD + "/login");
//                        return false;
//                    }
//
//
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    response.sendRedirect(POWER_URLHEAD + "/login");
//                    return false;
//                }
//            } else {
//                response.sendRedirect(POWER_URLHEAD + "/login");
//                return false;
//            }
//        }
//        return true;

        String url = request.getServletPath();
        String token = (String) request.getSession().getAttribute("token");
        if (!"/login".equals(url) && StringUtils.isNoneBlank(token)) {
            try {
                JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
                Client client = dcf.createClient(POWER_URLHEAD + "/WebService/PowerWebService?wsdl");
                Object[] objects = client.invoke("getInfosByUserId", token, "emr_medical_record");
                ObjectMapper mapper = new ObjectMapper();
                Power_User powerUser = mapper.readValue(objects[0].toString(), Power_User.class);
                //设置进session
                request.getSession().setAttribute("CURRENT_USER", powerUser);
                if (null == powerUser.getUserId()) {
                    response.sendRedirect( "/emr_medical_record/error.jsp");

                    //request.setAttribute("param", "重新登录");
                    return false;
                }
            } catch (Exception e) {
                response.sendRedirect("/emr_medical_record/error.jsp");
                e.printStackTrace();
               // response.sendRedirect(POWER_URLHEAD + "/login");
                //request.setAttribute("param", "重新登录");
                return false;
            }
        }else{

//       response.sendRedirect("/emr_medical_record/error.jsp");
//       String url2 = request.getRequestURL().toString();
//       System.out.println("当前访问地址：" + url2);
//       toAlert(response);
//        return false;


        }
//        } else {
//            response.sendRedirect(POWER_URLHEAD + "/login");
//            return false;
//        }
        return true;
    }


    //前台弹出alert框
    public void toAlert(HttpServletResponse response) throws IOException {
        //response.sendRedirect("/emr_medical_record/error.jsp");
        try {
            response.setContentType("text/html;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");

            OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream());

            String msg = "由于您长时间没有操作，session已过期，请重新登录!";
            msg = new String(msg.getBytes("UTF-8"));

            out.write("<meta http-equiv='Content-Type' content='text/html';charset='UTF-8'>");
            out.write("<script>");
            out.write("alert('" + msg + "');");
            out.write("top.location.href = '/emr_medical_record/error.jsp'; ");
            out.write("</script>");
            out.flush();
            out.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
 

