package com.community.huiju.security;

import com.alibaba.fastjson.JSONObject;
import com.community.commom.constant.Constant;
import com.community.commom.mode.ResponseBean;
import com.community.huiju.constant.Header;
import com.community.huiju.constant.Status;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

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

/**
 * 统一出口
 * @author weiximei
 */
@Slf4j
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        ResponseBean result = new ResponseBean();
        String headerError = (String) request.getAttribute(Header.HEADER_ERROR.getValue());
        if (StringUtils.isNotBlank(headerError)) {
            if (Status.RESPONSE_STATUS_800.getValue().equals(headerError)) {
                result.addError(Status.RESPONSE_STATUS_800.getValue(),Status.RESPONSE_STATUS_800.getComment());
            } else if (Status.RESPONSE_STATUS_801.getValue().equals(headerError)) {
                result.addError(Status.RESPONSE_STATUS_801.getValue(),Status.RESPONSE_STATUS_801.getComment());
            }else if (Status.RESPONSE_STATUS_802.getValue().equals(headerError)) {
                result.addError(Status.RESPONSE_STATUS_802.getValue(),Status.RESPONSE_STATUS_802.getComment());
            }else if (Status.RESPONSE_STATUS_803.getValue().equals(headerError)) {
                result.addError(Status.RESPONSE_STATUS_803.getValue(),Status.RESPONSE_STATUS_803.getComment());
            }
        } else {
            result.addError(Status.RESPONSE_STATUS_888.getValue(),Status.RESPONSE_STATUS_888.getComment());
        }

        try {
            //设置跨域请求 请求结果json刷到响应里
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEADER");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, user-token, Content-Type, Accept, version, type, platform");
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.getWriter().write(JSONObject.toJSONString(result));
            response.flushBuffer();
        } catch (Exception er) {
            log.error("响应错误!",er);
            er.printStackTrace();
        }

    }
}
