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.domain.SysDatashareUser;
import com.shanghaichengdi.ghjgitem.service.RedisService;
import com.shanghaichengdi.ghjgitem.service.SysDatashareServiceNewService;
import com.shanghaichengdi.ghjgitem.util.CharsetKit;
import com.shanghaichengdi.ghjgitem.vo.FrequencyInfoVo;
import com.shanghaigeography.Util.DateUtils;
import java.util.Date;
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 FrequencyLimitInterceptor implements HandlerInterceptor {

  @Resource
  private SysDatashareServiceNewService dataShareServiceNewService;
  @Resource
  private RedisService redisService;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    String token = request.getHeader("Authorization");
    String valueString = redisService.getValue(Constants.TOKEN + Constants.SPLIT, token);
    SysDatashareUser user = JSONObject.parseObject(valueString, SysDatashareUser.class);
    String requestURI = request.getRequestURI().replace("/ghThreeDataShare","");
    FrequencyInfoVo frequencyInfoVo = dataShareServiceNewService.getFrequencyInfoFromCache(
        user.getClient(), requestURI);
    if (!startDelay(frequencyInfoVo)) {
      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_BAD_REQUEST);
      ReturnMsg errorMsg = ReturnMsg.error(HttpServletResponse.SC_BAD_REQUEST,
          "接口:" + requestURI + ",请求被锁定,频率过快");
      response.getWriter().write(JSONObject.toJSONString(errorMsg));
      return false;
    }
    return true;
  }


  private boolean startDelay(FrequencyInfoVo vo) {
    long currentTime = System.currentTimeMillis();
    if (currentTime - vo.getLastTime() > vo.getFrequencyTime()) {
      vo.setLastTime(currentTime);
      dataShareServiceNewService.setNewLastRequestTime(vo);
      return true;
    }
    log.warn("变化后的接口限制频率为:{}",
        com.alibaba.fastjson.JSONObject.toJSONString(vo));
    log.error("{},调用时间间隔为:{}毫秒,该接口调用频率限制为:{}毫秒,上次调用时间为{}",
        vo.getUserAndUrl(), currentTime - vo.getLastTime(), vo.getFrequencyTime(),
        DateUtils.dateToString(new Date(vo.getLastTime()), DateUtils.DATE_FORMAT_19));
    return false;
  }
}
