package com.kcim.common.exception;

import com.kcim.common.util.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.UnsupportedEncodingException;
import java.util.List;

@Slf4j
@RestControllerAdvice
public class CostExceptionHandler {


    @ExceptionHandler(value = CostException.class)
    public ErrorResult handlerEmosException(CostException e) {
        e.printStackTrace();
        log.info("GlobalExceptionHandler...");
        log.info("错误代码:" + e.getMessage());
        return ErrorResult.errorMsg(500, e.getMessage());
    }

//    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ErrorResult handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        e.printStackTrace();
        log.info("GlobalExceptionHandler...");
        log.info("错误代码：" + e.getMessage());
        return ErrorResult.errorMsg(500, this.formatAllErrorMessages(e.getBindingResult().getAllErrors()));
    }

    @ExceptionHandler(value = BindException.class)
    public ErrorResult handlerBindException(BindException e) {
        e.printStackTrace();
        log.info("GlobalExceptionHandler...");
        log.info("错误代码：" + e.getMessage());
        return ErrorResult.errorMsg(500, this.formatAllErrorMessages(e.getBindingResult().getAllErrors()));
    }

//    @ResponseStatus(value = HttpStatus.UNAUTHORIZED)
//    @ExceptionHandler(value = UnauthorizedException.class)
//    public ErrorResult handlerUnauthorizedException(UnauthorizedException e) {
//        e.printStackTrace();
//        log.info("GlobalExceptionHandler...");
//        log.info("错误代码：" + e.getMessage());
//        return ErrorResult.errorMsg(403,"您的权限不足,请联系管理员添加");
//    }

//    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = Exception.class)
    public ErrorResult handlerException(Exception e) {
        e.printStackTrace();
        log.info("===============================GlobalExceptionHandler异常信息===============================");
        log.info("错误代码：" + e.getLocalizedMessage());
        return ErrorResult.errorMsg(500,e.getLocalizedMessage());
    }

    private String formatAllErrorMessages(List<ObjectError> errors) {
        StringBuffer errorMsg = new StringBuffer();
        errors.forEach(error -> {
            String defaultMessage = error.getDefaultMessage();
            try {
                defaultMessage = new String(defaultMessage.getBytes("UTF-8"), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            errorMsg.append(defaultMessage).append(';');
        });
        return errorMsg.toString();
    }

    @ExceptionHandler(DataAccessException.class)
    @ResponseBody
    public ErrorResult handleDataAccessException(DataAccessException e) {
        log.error("数据库错误:{}", e.getMessage(), e);
        return ErrorResult.errorMsg(500,"数据库错误");

    }
}
