package com.bcrjl.miwifi.common.exceptions;

import cn.dev33.satoken.exception.NotLoginException;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONUtil;
import com.bcrjl.miwifi.common.enums.GlobalEnumCode;
import com.bcrjl.miwifi.common.response.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
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.IOException;

/**
 * 全局异常处理类
 *
 * @author yanqs
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理Exception异常
     * <p>
     * 全局异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public void exceptionHandler(HttpServletResponse response, HttpServletRequest req, Exception e) {
        response.setStatus(HttpServletResponse.SC_OK);
        try {
            response.setContentType("application/json");
            ObjectMapper om = new ObjectMapper();
            om.writeValue(response.getOutputStream(), R.fail(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Sa-Token 全局异常拦截（拦截项目中的NotLoginException异常）
     *
     * @param nle
     * @return
     */
    @ExceptionHandler(NotLoginException.class)
    public void handlerNotLoginException(HttpServletResponse response,NotLoginException nle) {
        // 打印堆栈，以供调试
        // nle.printStackTrace();
        // 判断场景值，定制化异常信息
        String message = "";
        if (nle.getType().equals(NotLoginException.NOT_TOKEN)) {
            message = "未提供token";
        } else if (nle.getType().equals(NotLoginException.INVALID_TOKEN)) {
            message = "token无效";
        } else if (nle.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
            message = "token已过期";
        } else if (nle.getType().equals(NotLoginException.BE_REPLACED)) {
            message = "token已被顶下线";
        } else if (nle.getType().equals(NotLoginException.KICK_OUT)) {
            message = "token已被踢下线";
        } else {
            message = "当前会话未登录";
        }
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setCharacterEncoding("utf-8");
        ServletUtil.write(response,
                JSONUtil.toJsonPrettyStr(R.fail(GlobalEnumCode.UNAUTHORIZED.getCode(), message)),
                "application/json");
        // 返回给前端
        //return   R.failed(ServiceExceptionEnum.UNAUTHORIZED.getCode(), null, message);
    }
}
