package com.infoepoch.pms.dispatchassistant.common.exception;


import com.infoepoch.pms.dispatchassistant.common.component.Result;
import com.infoepoch.pms.dispatchassistant.common.constant.ErrorCodes;
import com.infoepoch.pms.dispatchassistant.common.constant.StoreKeys;
import com.infoepoch.pms.dispatchassistant.common.utils.StringUtils;
import com.infoepoch.pms.dispatchassistant.common.utils.UrlTool;
import com.infoepoch.pms.dispatchassistant.domain.basic.store.KeyValueStoreService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.multipart.MaxUploadSizeExceededException;

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

/**
 * 全局异常处理器
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    protected static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @Autowired
    private KeyValueStoreService keyValueStoreService;

    @Value("${spring.application.name}")
    private String applicationName;

    /**
     * 上传文件大小超过限制异常处理器，此异常在上传方法中无法捕捉，只能在此捕捉
     */
    @ExceptionHandler(value = MaxUploadSizeExceededException.class)
    @ResponseBody
    public Result maxUploadSizeExceededExceptionHandler(HttpServletResponse response, MaxUploadSizeExceededException e) {
        return Result.error(ErrorCodes.DEFAULT, "上传文件大小超过限制。");
    }

    /**
     * 未登录异常处理器
     */
    @ExceptionHandler(value = NotLoginException.class)
    @ResponseBody
    public Result notLoginExceptionHandler(HttpServletResponse response, NotLoginException e) {
        if (e.getCode() == ErrorCodes.SUPPLIER_NOT_LOGIN)
            return Result.error(e.getCode(), "请重新登录。");
        return Result.error(ErrorCodes.NOT_LOGIN, "请重新登录。");
    }

    /**
     * 验证异常处理器
     */
    @ExceptionHandler(value = ValidationException.class)
    @ResponseBody
    public Result validationExceptionHandler(HttpServletResponse response, Exception e) {
//        logger.info("捕获到验证异常。", e);
        return Result.error(ErrorCodes.VALIDATION, e.getMessage());
    }

    /**
     * 默认异常处理器，返回JSON
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result defaultExceptionHandler(HttpServletResponse response, Exception e) {
        logger.info("捕捉到未处理的异常。", e);
        return Result.error(ErrorCodes.DEFAULT, "服务器异常，请联系管理员。");
    }

}
