package com.fdkankan.ucenter.interceptor;


import cn.hutool.http.ContentType;
import com.alibaba.fastjson.JSONObject;
import com.fdkankan.common.util.JwtUtil;
import com.fdkankan.redis.constant.RedisKey;
import com.fdkankan.redis.util.RedisUtil;
import com.fdkankan.ucenter.common.RedisKeyUtil;
import com.fdkankan.ucenter.common.Result;
import com.fdkankan.ucenter.constant.LoginConstant;
import java.nio.charset.StandardCharsets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

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

@Component
@Slf4j
public class AppInterceptor implements HandlerInterceptor {

	@Autowired
	private RedisUtil redisUtil;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		response.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.JSON.getValue());
		response.setCharacterEncoding(StandardCharsets.UTF_8.name());
		String token = request.getHeader("token");
		if(StringUtils.isEmpty(token)){
			this.needLogin(request,response);
			return false;
		}
		try {
			String username = JwtUtil.getUsername(token);
			String redisKey = RedisKeyUtil.PREFIX_CACHE_CAMERA + username;
			if(redisUtil.hasKey(redisKey)){
				redisUtil.expire(redisKey,21800L);
				String redisKey2 =  String.format(RedisKey.TOKEN_V3 , token );
				if(redisUtil.hasKey(redisKey2)){
					redisUtil.expire(redisKey2,21800L);
				}else {
					redisUtil.set(redisKey2,token,21800L);
				}
				return true;
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		this.needLogin(request,response);
		return false;
	}

	private void needLogin(HttpServletRequest request, HttpServletResponse response) {
		try {
			String result = JSONObject.toJSONString(Result.failure(LoginConstant.FAILURE_CODE_3004, LoginConstant.FAILURE_MSG_3004));
			response.getWriter().append(result);
		} catch (IOException e) {
			log.info("LoginInterceptor|needLogin|IOException|" + e);
			e.printStackTrace();
		}
	}

}

