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.HttpRequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.PrintWriter;
import java.io.StringWriter;

@RestControllerAdvice("com.xxfc.platform")
@Slf4j
public class PlatformExceptionHandler {

    @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){

        Throwable cause = e.getCause();
        if(cause != null && cause.toString().contains("Exception")) {
            StringWriter stringWriter = new StringWriter();
            cause.printStackTrace(new PrintWriter(stringWriter));
            log.error(cause.getMessage(), e);
            HttpRequestUtil.httpGet("http://10.5.52.3:8765/api/universal/mail/app/unauth/send?toUser=jiaoruizhen@126.com&subject=服务器异常&content=" + stringWriter.toString());
            return assembleResult(ObjectRestResponse.createFailedResult(5000, "服务器开小差了，请稍后重试！"), "Server exception: " + e.getMessage());
        }
        log.error("Server exception: ", e);
        HttpRequestUtil.httpGet("http://10.5.52.3:8765/api/universal/mail/app/unauth/send?toUser=jiaoruizhen@126.com&subject=服务器异常&content=" + e.getStackTrace().toString());
        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());
    }

}
