package com.zfire.jiasm.syncdata.config;

import cn.hutool.core.util.ReUtil;
import com.alibaba.fastjson.JSONObject;
import com.zfire.jiasm.syncdata.exception.RemoteServiceException;
import com.zfire.jiasm.syncdata.helper.ResponseHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
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(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());
        }

        if (ex instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) ex;
            BindingResult bindingResult = methodArgumentNotValidException.getBindingResult();
            StringBuilder sb = new StringBuilder();
            bindingResult.getFieldErrors().forEach( item -> {
                if (ReUtil.isMatch("^\\w+\\[\\d+\\]\\.\\w+", item.getField())) {
                    String field = item.getField();
                    int rowCount = Integer.parseInt(field.substring(field.indexOf("[") + 1, field.indexOf("]"))) + 1;
                    sb.append("第").append(rowCount).append("行 ");
                }
                sb.append(item.getDefaultMessage()).append(",");
            });
            sb.deleteCharAt(sb.length() - 1);
            log.error("bean验证有误：" + ex.getMessage() + sb);
            return ResponseHelper.error(ResponseHelper.ResponseCode_VALIDATION_ERROR, sb.toString());
        }

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

    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.isNotEmpty(wholeStr)){
//                params = JSON.parseObject(wholeStr,Map.class);
//            }
//        } catch (IOException e1) {
//            log.error(""+e1);
//        }
        return params;
    }


}
