package com.github.wxiaoqi.security.common.handler;


import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.BaseResponse;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice("com.upyuns.platform.rs")
@Slf4j
public class PlatformExceptionHandler {
    @Value("${spring.application.name}")
    private String applicationName;

    @ExceptionHandler(value = {BaseException.class})
    public BaseResponse baseExceptionHandler(Exception e) {
        if (e instanceof BaseException){
            BaseException be = (BaseException) e;
            return new BaseResponse(be.getStatus(), StringUtils.isEmpty(be.getSubCode())?"NAN":be.getSubCode(), be.getMessage());
        }
        return new BaseResponse(400,e.getMessage());
    }

    //服务器异常
    @ExceptionHandler(Exception.class)
    public ObjectRestResponse<?> exceptionHandler(Exception e){
        return assembleResult(ObjectRestResponse.createFailedResult(5000, "服务器开小差了，请稍后重试！"), "Server exception: " + e.getMessage());
    }

    protected ObjectRestResponse<?> assembleResult(ObjectRestResponse<?> error, String msg) {
        log.debug("Exception: " + msg);
        return error;
    }

    protected ObjectRestResponse<?> assembleResult(ObjectRestResponse<?> error, Throwable e) {
        return assembleResult(error, e.getClass().getSimpleName() + ": " + e.getMessage());
    }


}
