/**
 * $Id: RestControllerAdviceHandler.java 13331 2016-07-06 09:09:33Z anjiabin $
 * Copyright(C) 2014-2020 easegame, All Rights Reserved.
 */
package com.liquidnet.common.exception;

import com.alibaba.fastjson.JSON;
import com.liquidnet.common.exception.entity.Error;
import com.liquidnet.service.ResponseDto;
import com.liquidnet.service.constant.GlobalConstant;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;

/**
 * Created by Administrator on 2017/6/17.
 */
@ControllerAdvice(annotations = RestController.class)
public class RestControllerAdviceHandler {
    private final Logger logger = LoggerFactory.getLogger(RestControllerAdviceHandler.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity serviceExceptionHandler(Exception rex, WebRequest request) {
        logger.error("serviceExceptionHandler request : {} param:{}", request.getContextPath(), JSON.toJSONString(request.getParameterMap()));

        if ( rex instanceof LiquidnetFeignException) {
            LiquidnetFeignException ygex = ((LiquidnetFeignException) rex);
            String errorCode = ygex.errorCode().getCode();
            String message = ygex.getMessage();
            message = message == null ? ygex.errorCode().getMessage() : message;
            logger.error("LiquidnetServiceException errorCode:{} error : {}", errorCode, ygex.getMessage());
            return new ResponseEntity<Error>(new Error(errorCode,message), HttpStatus.OK);
        }
        if (rex instanceof LiquidnetServiceException) {
            LiquidnetServiceException ygex = ((LiquidnetServiceException) rex);
            String errorCode = ygex.errorCode().getCode();
            String message = ygex.getMessage();
            String url  =  ygex.getUrl();
            if(StringUtils.isNoneEmpty(url)){
                return new ResponseEntity<ResponseDto>(ResponseDto.failure(errorCode,message,url), HttpStatus.OK);
            }
            message = message == null ? ygex.errorCode().getMessage() : message;
            logger.error("LiquidnetServiceException errorCode:{} error : {}", errorCode, ygex.getMessage());
            return new ResponseEntity<Error>(new Error(errorCode,message), HttpStatus.OK);
        } else {
            logger.error("serviceExceptionHandler  error : {}", rex);
            return new ResponseEntity<Error>(new Error("-1", GlobalConstant.RESPONSE_ERROE_UNKNOWN), HttpStatus.OK);
        }
    }
}
