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.xxfc.platform")
@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){

        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);
            Map<String, String> map = new HashMap<>();
            map.put("toUser", "jiaoruizhen@126.com");
            map.put("subject", "服务器异常");
            map.put("content", initCommonLogPrePart()+ ":" +stringWriter.toString());
            try {
                HttpUtils.doPost("http://10.5.52.3:8765","/api/universal/mail/app/unauth/send", map);
            } catch (Exception ex) {
                log.error(ex.getMessage());
            }
            return assembleResult(ObjectRestResponse.createFailedResult(5000, "服务器开小差了，请稍后重试！"), "Server exception: " + e.getMessage());
        }
        log.error("Server exception: ", e);
        Map<String, String> map = new HashMap<>();
        map.put("toUser", "jiaoruizhen@126.com");
        map.put("subject", "服务器异常");
        map.put("content", initCommonLogPrePart()+ ":" + e.toString() + ":" + e.getMessage());
        try {
            HttpUtils.doPost("http://10.5.52.3:8765","/api/universal/mail/app/unauth/send", map);
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
        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());
    }


    public String initCommonLogPrePart() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();//获取request
        StringBuilder stringBuilder = new StringBuilder();
        //request 获得头部
        stringBuilder.append(request.getHeader("app"));
        LocalDateTime startTime= LocalDateTime.now();//开始时间
        stringBuilder.append("》》" +startTime.toString());
        stringBuilder.append("》》" +request.getServletPath());
        stringBuilder.append("》》" +applicationName + ":" + request.getServletPath());
        return stringBuilder.toString();
    }

}
