package com.shanghaichengdi.ghjgitem.config;

import com.alibaba.fastjson.JSONObject;
import com.shanghaichengdi.ghjgitem.constant.Constants;
import com.shanghaichengdi.ghjgitem.vo.response.ReturnMsg;
import com.shanghaichengdi.ghjgitem.service.RedisService;
import com.shanghaichengdi.ghjgitem.util.CharsetKit;
import java.util.Objects;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

  @Resource
  private RedisService redisService;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    String token = request.getHeader("Authorization");
    log.info("======> 获取到token为:{}", token);
    if (Objects.isNull(token)) {
      response.setCharacterEncoding(CharsetKit.UTF_8);
      response.setContentType("application/json;charset=utf-8");
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Cache-Control", "no-cache");
      response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
      ReturnMsg errorMsg = ReturnMsg.error(HttpServletResponse.SC_UNAUTHORIZED,
          "请将获取到的token放入请求头Authorization中");
      response.getWriter().write(JSONObject.toJSONString(errorMsg));
      return false;
    }
    if (Boolean.FALSE.equals(redisService.hasKey(Constants.TOKEN + Constants.SPLIT, token))) {
      response.setCharacterEncoding(CharsetKit.UTF_8);
      response.setContentType("application/json;charset=utf-8");
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Cache-Control", "no-cache");
      response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
      ReturnMsg errorMsg = ReturnMsg.error(HttpServletResponse.SC_UNAUTHORIZED,
          "token已过期,请重新获取!");
      response.getWriter().write(JSONObject.toJSONString(errorMsg));
      return false;
    }
    return true;
  }
}
