package com.gree.mall.miniapp.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import com.gree.mall.miniapp.helper.ResponseHelper;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
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 javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalDefaultExceptionHandler {


    @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;
    }


}
