package com.changfa.exception;

import com.alibaba.fastjson.JSON;
import com.changfa.constants.ApiResult;
import com.changfa.enums.StatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MissingServletRequestParameterException;
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 javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author wwz
 */
@ControllerAdvice
public class GlobaExceptionHandler {

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


    @ExceptionHandler(value = BuzEx.class)
    @ResponseBody
    public ApiResult buzError(BuzEx throwable){
        logger.error("BuzExError:{},date:{}",throwable.getMessage(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        throwable.printStackTrace();
        return ApiResult.error(throwable.getMessage());
    }

    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    @ResponseBody
    public ApiResult buzError(MissingServletRequestParameterException throwable){
        logger.error("BuzExError:{},date:{}",throwable.getMessage(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        throwable.printStackTrace();
        return ApiResult.error(StatusEnum.PARAM_IS_EMPTY);
    }


    @ExceptionHandler(value = Throwable.class)
    @ResponseBody
    public ApiResult error(Throwable throwable){
        logger.error("error:{},date:{}",throwable.getMessage(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        throwable.printStackTrace();
        if(throwable.getCause() instanceof BuzEx){
           return buzError((BuzEx) throwable.getCause());
        }
        return ApiResult.error(StatusEnum.INTERNAL_SERVER_ERROR);
    }


    @ExceptionHandler(XssException.class)
    public void exceptionRevlose(XssException ex, HttpServletRequest request,HttpServletResponse response){
        responseBody(response,ex.getMessage());
        return;
    }

    public static boolean isAjaxRequest(HttpServletRequest request) {
        String requestedWith = request.getHeader("x-requested-with");
        if (requestedWith != null && requestedWith.equalsIgnoreCase("XMLHttpRequest")) {
            return true;
        } else {
            return false;
        }
    }
    public void responseForm(HttpServletResponse response,String message){
        //重置response
        response.reset();
        //设置编码格式
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        try(PrintWriter pw = response.getWriter();){
            pw.write("<script>alert('"+message+"')</script>");
            pw.flush();
        }catch (Exception e){

        }

    }
    public void responseBody(HttpServletResponse response,String message){
        //重置response
        response.reset();
        //设置编码格式
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        try(PrintWriter pw = response.getWriter();){
            pw.write(JSON.toJSONString(ApiResult.error(StatusEnum.ILLEGAL_PARAM)));
            pw.flush();
        }catch (Exception e){

        }

    }
}
