package com.wgb.system.service.config;


import com.alibaba.fastjson.JSON;
import com.data.model.restful.response.InternalResponse;
import com.tool.data.external.exception.SystemException;
import com.wgb.system.service.exception.InternalSystemUnHandlerException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

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

@Slf4j
@ControllerAdvice
public class GlobalDefultExceptionHandler {


    @Value("${component.name}")
    private String componentName;

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public InternalResponse defultExcepitonHandler(HttpServletRequest request, Exception e) {
        log.error("request servicePath={} System appears Exception  e={} ", request.getServletPath(), e);
        log.error(" Completed execute ServletPath={}", request.getServletPath());
        return InternalResponse.fail();
    }

    @ExceptionHandler(InternalSystemUnHandlerException.class)
    @ResponseBody
    public InternalResponse InternalSystemUnHandlerExceptionHandler(HttpServletRequest request, InternalSystemUnHandlerException e) {
        log.error(" request servicePath={} Send exception  code={}, message= {}", request.getServletPath(), e.getErrorCode(), JSON.toJSON(InternalResponse.fail(e.getErrorCode())));
        log.error(" Completed execute ServletPath={}", request.getServletPath());
        return InternalResponse.withParamsMessage(componentName, e.getErrorCode()).withBody(e.getErrorMsg());
    }

    @ExceptionHandler({SystemException.class})
    @ResponseBody
    public InternalResponse SystemException(HttpServletRequest request, SystemException e) {
        log.error(" request servicePath={} Send exception  code={}, message= {}", request.getServletPath(), e.getCode(), JSON.toJSON(InternalResponse.fail(e.getCode())));
        log.error(" Completed execute ServletPath={}", request.getServletPath());
        return InternalResponse.withParamsMessage(componentName, e.getCode()).withBody(e.getMsg());
    }

    @ExceptionHandler(IOException.class)
    @ResponseBody
    public InternalResponse IOExceptionHandler(HttpServletRequest request, IOException e) {
        log.error("request servicePath={} System appears IOException  e={} ", request.getServletPath(), e);
        log.error(" Completed execute ServletPath={}", request.getServletPath());
        return InternalResponse.fail();
    }

}
