package com.github.wxiaoqi.security.common.handler;

import com.github.wxiaoqi.security.common.constant.CommonConstants;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.exception.auth.ClientTokenException;
import com.github.wxiaoqi.security.common.exception.auth.UserInvalidException;
import com.github.wxiaoqi.security.common.exception.auth.UserTokenException;
import com.github.wxiaoqi.security.common.msg.BaseResponse;
import com.github.wxiaoqi.security.common.util.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import static org.springframework.http.HttpStatus.NOT_EXTENDED;

/**
 * Created by ace on 2017/9/8.
 */
@ControllerAdvice("com.github.wxiaoqi.security")
@ResponseBody
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    @Value("${spring.application.name}")
    private String applicationName;

    @Value("${email.log.account}")
    private  String emailLogAccount;

    @Value("${email.log.title}")
    private String emailLogTitle;

    @Value("${email.log.host}")
    private String emailLogHost;
    /**
     * 在controller里面内容执行之前，校验一些参数不匹配啊，Get post方法不对啊之类的
     */
    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
        logger.error(ex.getMessage(),ex);
        return new ResponseEntity<>("出错了", NOT_EXTENDED);
    }


    @ExceptionHandler(ClientTokenException.class)
    public BaseResponse clientTokenExceptionHandler(HttpServletResponse response, ClientTokenException ex) {
        response.setStatus(403);
        logger.error(ex.getMessage(),ex);
        return new BaseResponse(ex.getStatus(), ex.getMessage());
    }

    @ExceptionHandler(UserTokenException.class)
    public BaseResponse userTokenExceptionHandler(HttpServletResponse response, UserTokenException ex) {
        response.setStatus(200);
        logger.error(ex.getMessage(),ex);
        return new BaseResponse(ex.getStatus(), ex.getMessage());
    }

    @ExceptionHandler(UserInvalidException.class)
    public BaseResponse userInvalidExceptionHandler(HttpServletResponse response, UserInvalidException ex) {
        response.setStatus(200);
        logger.error(ex.getMessage(),ex);
        return new BaseResponse(ex.getStatus(), ex.getMessage());
    }

    @ExceptionHandler(BaseException.class)
    public BaseResponse baseExceptionHandler(HttpServletResponse response, BaseException ex) {
        logger.error(ex.getMessage(),ex);
        if(0 == ex.getStatus()) {
            response.setStatus(500);
        }
        return new BaseResponse(ex.getStatus(), ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public BaseResponse otherExceptionHandler(HttpServletResponse response, Exception ex) {
        response.setStatus(500);
        logger.error(ex.getMessage(),ex);
        Throwable cause = ex.getCause();
        if(cause != null && cause.toString().contains("Exception")) {
            StringWriter stringWriter = new StringWriter();
            cause.printStackTrace(new PrintWriter(stringWriter));
            logger.error(cause.getMessage(), ex);
            Map<String, String> map = new HashMap<>();
            map.put("toUser", emailLogAccount);
            map.put("subject", emailLogTitle);
            map.put("content", initCommonLogPrePart()+ ":" +stringWriter.toString());
            try {
                HttpUtils.doPost(emailLogHost,"/api/universal/mail/app/unauth/send", map);
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
            return new BaseResponse(5000, "Server exception: " + ex.getMessage());
        }
        Map<String, String> map = new HashMap<>();
        map.put("toUser", emailLogAccount);
        map.put("subject", emailLogTitle);
        map.put("content", initCommonLogPrePart()+ ":" + ex.toString() + ":" + ex.getMessage());
        try {
            HttpUtils.doPost(emailLogHost,"/api/universal/mail/app/unauth/send", map);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return new BaseResponse(CommonConstants.EX_OTHER_CODE, ex.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();
    }
}
