package com.gree.mall.manager.config;

import com.alibaba.fastjson.JSONObject;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.helper.ResponseHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
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 java.util.HashMap;
import java.util.Map;

@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalDefaultExceptionHandler {

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseHelper handleHttpMessageNotReadableException(HttpMessageNotReadableException e){
        return ResponseHelper.error(501,"检测到参数内容格式错误");
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseHelper handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.warn(e.getMessage(), e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return ResponseHelper.error(ResponseHelper.ResponseCode_VALIDATION_ERROR, message);
    }

    @ExceptionHandler(value = Exception.class)
    public ResponseHelper<Object> defaultErrorHandler(HttpServletRequest req, Exception ex) {

        if(ex instanceof RemoteServiceException){
            //自定义错误就不抛出栈异常
            //log.error("网络异常:",ex);
            log.error("网络异常:"+ex.getMessage()+req.getRequestURI()+JSONObject.toJSONString(this.bodyParam(req)));
            return ResponseHelper.error(((RemoteServiceException) ex).getCode(),"温馨提示："+ex.getMessage());
        }

        log.error("系统错误:"+ex.getMessage()+req.getRequestURI()+JSONObject.toJSONString(this.bodyParam(req)),ex);
        return ResponseHelper.error(501,"网络异常");
    }

    private Map<String,Object> bodyParam(HttpServletRequest request){
        Map<String,Object> params = new HashMap<String, Object>();
//        BufferedReader br;
//        try {
//            br = request.getReader();
//            String str, wholeStr = "";
//            while((str = br.readLine()) != null){
//                wholeStr += str;
//            }
//            if(StringUtils.isNotBlank(wholeStr)){
//                params = JSON.parseObject(wholeStr,Map.class);
//            }
//        } catch (IOException e1) {
//            log.error(""+e1);
//        }
        return params;
    }


}
