package com.sifang.modules.sys.web;

import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

public class BaseExceptionController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Result<Void> exceptionHandler(Exception e){
        logger.error(" >> into exceptionHandler: ", e);
        e.printStackTrace();
        if(e instanceof BusinessException){
            BusinessException exception = (BusinessException) e;
            logger.info(" >> BusinessException, code: {}, message: {}", exception.getErrorCode(), exception.getMessage());
            return Result.fail(exception.getErrorCode(), exception.getMessage());
        }else if(e instanceof IllegalArgumentException){
            IllegalArgumentException exception = (IllegalArgumentException) e;
            return Result.fail("400", exception.getMessage());
        }else {
            return Result.fail("请联系管理员");
        }
    }

    public <T> Result<T> errRet(BindingResult result) {
        List<FieldError> fieldErrors = result.getFieldErrors();
        Result<T> ret = new Result<>();
        ret.setCode("422");
        if (!fieldErrors.isEmpty()) {
            String message = fieldErrors.get(0).getDefaultMessage();
            ret.setMsg("参数错误：" + message);
        } else {
            ret.setMsg("参数错误");
        }
        return ret;
    }

    @ResponseBody
    @ExceptionHandler(BindException.class)
    public Result validatedBindException(BindException e) {
        logger.error(e.getMessage(), e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return Result.fail("422", message);
    }

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object validExceptionHandler(MethodArgumentNotValidException e) {
        logger.error(e.getMessage(), e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return Result.fail("422", message);
    }
}
