package com.yonge.cooleshow.auth.core.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

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

@Component
public class BaseAuthenticationFailureEvenHandler extends ExceptionMappingAuthenticationFailureHandler {

    private final static Logger logger = LoggerFactory.getLogger(BaseAuthenticationFailureEvenHandler.class);

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
    	
    	int resultCode = HttpStatus.SC_CONFLICT;
    	
        String message = exception.getLocalizedMessage();

        String data = null;
        if (message.equals("Bad credentials")) {
            message = "用户名或密码错误";
        }else if(message.equals("User is disabled")){
            resultCode = 5005;
            message = "账户被锁定";
        }else if(message.equals("404.9")){
        	message = "用户名或密码错误";
        	resultCode = 99;
        } else if (message.startsWith("MA:5001:")) {
            // 返回用户绑定openId
            data = message.split(":")[2];
            // 用户未绑定openId错误码
            resultCode = 5001;
            // 用户未绑定openId错误信息
            message = "用户未绑定小程序账号";
        } else if (message.startsWith("MA:5004:")) {
            // 返回用户绑定openId
            data = message.split(":")[2];
            // 用户未绑定openId错误码
            resultCode = 5004;
            // 用户未绑定openId错误信息
            message = "该机构已被冻结，请联系管理员";
        } else if (message.startsWith("MA:5005:")) {
            // 返回用户绑定openId
            data = message.split(":")[2];
            // 用户未绑定openId错误码
            resultCode = 5005;
            // 用户未绑定openId错误信息
            message = "账号已冻结";
        }
        logger.info("登录失败，异常：{}", message);
        HttpResponseResult result = new HttpResponseResult(false, resultCode, data, message);
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }
}
