package com.hdkj.lt.si.filter;

import com.alibaba.fastjson.JSON;
import com.hdkj.hussar.ResultCode;
import com.hdkj.lt.utils.security.JwtUtils;
import com.hdkj.hussar.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.Charsets;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * @Description:
 * @Author: wenhao
 * @Create: 2024/03/22 14:54
 * @Version: 1.0
 */
@Slf4j
public class AuthenticationFilter implements Filter {

    public static final String FILTER_NAME = "authenticationFilter";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //nothing to do
    }

    @Override
    public void destroy() {
        //nothing to do
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String requestUri = request.getRequestURI();
        if (StringUtils.equals("/auth/token", requestUri)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader(HttpHeaders.DATE, new Date().toString());
        response.setHeader(HttpHeaders.ACCEPT_CHARSET, Charsets.UTF_8.toString());
        response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        ServletOutputStream sos = response.getOutputStream();
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (StringUtils.isBlank(token)) {
            ApiResponse<Object> apiResponse = ApiResponse.fail(ResultCode.FAILURE.getCode(), new Object(), "请求token不能为空！");
            sos.write(JSON.toJSONString(apiResponse).getBytes());
            sos.close();
            return;
        }
        try {
            JwtUtils.parseJwtToken(token);
        } catch (Exception e) {
            log.error("token解析失败: {}", e.getMessage());
            ApiResponse<Object> apiResponse = ApiResponse.fail(ResultCode.FAILURE.getCode(), new Object(), "token解析失败！");
            sos.write(JSON.toJSONString(apiResponse).getBytes());
            sos.close();
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

}
