package com.fkzy.warn.common.conf;

import com.alibaba.fastjson.JSONObject;

import com.fkzy.warn.common.constants.RedisKeyConstants;
import com.fkzy.warn.common.constants.ResponseMsgConstants;
import com.fkzy.warn.common.response.ApiResponse;
import com.fkzy.warn.common.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 拦截器
 *
 * @author yuyantian
 * @date 2021/09/07 14：30
 */
public class WebInterceptor implements HandlerInterceptor {
    @Autowired
    public RedisUtil redisUtil;


    private static final Logger logger = LoggerFactory.getLogger(WebInterceptor.class);


    private void returnError(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        try (PrintWriter writer = response.getWriter()) {
            ApiResponse apiResponse = new ApiResponse();
            apiResponse.setCode(ResponseMsgConstants.FAIL_CODE_401);
            apiResponse.setMessage("ticket无效，请重新登录后操作");
            writer.print(JSONObject.toJSONString(apiResponse));
        } catch (IOException e) {
            logger.error("web拦截器异常", e);
        }
    }

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

        try {
            logger.debug("请求：{}", request.getRequestURL());
            //校验ticket是否有效
//            String ticket = request.getHeader("ticket");
//            //如果header中不存在ticket，则从参数中获取ticket
//            if (StringUtils.isBlank(ticket)) {
//                ticket = request.getParameter("ticket");
//            }
//
//            if (redisUtil.exists(RedisKeyConstants.LOGIN_ST + ticket)) {
//                return true;
//            } else {
//                returnError(request, response);
//            }
            return true;
        } catch (Exception e) {
            logger.error("web拦截器异常", e);
            returnError(request, response);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object
        handler,
                           ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex)
        throws Exception {
        // TODO Auto-generated method stub

    }

}
