package com.ywt.outpatient.interceptors;

import com.ywt.biz.common.util.Checker;
import com.ywt.biz.common.util.serializers.JsonSerializer;
import com.ywt.outpatient.core.BaseResponse;
import org.springframework.stereotype.Service;
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.nio.charset.StandardCharsets;

/**
 * @author Walker
 * Created on 2021/9/6
 */
@Service("covid19QuestSimpleTokenInterceptor")
public class Covid19QuestSimpleTokenInterceptor implements HandlerInterceptor {
    public static final String SIMPLE_FIXED_TOKEN = "UunV9!4VSB7n424";// 简单的静态 token
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String token = Checker.getStringValue(httpServletRequest.getHeader("token"));
        if (!SIMPLE_FIXED_TOKEN.equals(token)) {
            BaseResponse response = new BaseResponse();
            response.setCode(BaseResponse.NO_RIGHT);
            response.setInfo("invalid token!");
            this.toResponse(response, httpServletResponse);
            return false;
        }
        return true;
    }

    private void toResponse(BaseResponse response, HttpServletResponse httpServletResponse) throws IOException {
        httpServletResponse.addHeader("Content-Type", "application/json;charset=UTF-8");
        String responseData = JsonSerializer.toJson(response);
        httpServletResponse.setStatus(200);
        byte[] responseDataBytes = responseData.getBytes(StandardCharsets.UTF_8);
        httpServletResponse.setContentLength(responseDataBytes.length);
        httpServletResponse.getOutputStream().write(responseDataBytes);
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
