package com.iformall.common;


import com.iformall.exception.MallinkException;
import com.iformall.service.MailService;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

@ControllerAdvice
public class GlobalDefultExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private boolean isFmException;

    @Autowired
    private String fmExceptionEmails;

    @Autowired
    private MailService mailService;

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultData defultExcepitonHandler(HttpServletRequest request, Exception e) {
        log(e, request);

        if(isFmException) {
            // 处理异常，发送邮件
            if(checkExceptionType(e)) {
                // 某些异常不发邮件
                MallinkException me = (MallinkException)e;
                return new ResultData(me.getErrorCode(),me.getMessage());
            }
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式

            StringBuilder sb = new StringBuilder();
            sb.append(df.format(new Date()));
            sb.append("\n");
            sb.append(sw.toString());

            String[] receivers = fmExceptionEmails.split(",");

            //发送邮件
            mailService.sendSimpleMail(receivers, "请求地址：" + request.getRequestURL() + "异常", sb.toString());
        }

        if(checkExceptionType(e)) {
            MallinkException me = (MallinkException)e;
            return new ResultData(me.getErrorCode(),me.getMessage());
        } else if(checkAuthException(e)) {
            return new ResultData(ErrorCode.SYS_AUTH_ERROR);
        } else {
            return new ResultData(Result.ERROR, e.getMessage());
        }
    }


    private void log(Exception ex, HttpServletRequest request) {
        logger.error("************************异常开始*******************************");
        if(checkExceptionType(ex)) {
            // 特殊异常不打印堆栈
            logger.error(ex.getMessage());
            logger.error("************************异常结束*******************************");
            return;
        }
        logger.error("请求地址：" + request.getRequestURL());
        logger.error("message："+ ex.getMessage());
        Enumeration enumeration = request.getParameterNames();
        logger.error("请求参数");
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement().toString();
            logger.error(name + "---" + request.getParameter(name));
        }
        StackTraceElement[] error = ex.getStackTrace();
        for (StackTraceElement stackTraceElement : error) {
            logger.error(stackTraceElement.toString());
        }
        logger.error("************************异常结束*******************************");
    }

    private boolean checkExceptionType(Exception e) {
        if(e instanceof MallinkException) {
            MallinkException me = (MallinkException)e;
            if(me.getErrorCode() == ErrorCode.NET_TOKEN_EMPTY.getCode()
                    || me.getErrorCode() == ErrorCode.NET_TOKEN_INVALID.getCode()) {
                // token异常问题, 不发邮件
                return true;
            } else if(me.getErrorCode() == ErrorCode.SYS_REPEAT_SUBMIT_EXCEPTION.getCode()) {
                // 重复访问不打印异常消息
                return true;
            }
        }
        return false;
    }

    private boolean checkAuthException(Exception e) {
        return e instanceof AuthorizationException;
    }
}
