package com.xhpc.evcs.config;

import com.xhpc.evcs.dto.CommonRequest;
import com.xhpc.evcs.http.HttpServletRequestRepeatReadWrapper;
import com.xhpc.evcs.utils.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Scanner;

@SuppressWarnings({"Duplicates"})
@Slf4j
public class EvcsInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        HttpServletRequest requestWrapper = new HttpServletRequestRepeatReadWrapper(request);
        Scanner scanner = new Scanner(requestWrapper.getInputStream(), "UTF-8").useDelimiter("\\A");
        String bodyString = scanner.hasNext() ? scanner.next() : null;
        if (!ObjectUtils.isEmpty(bodyString)) {
            CommonRequest commonRequest = JSONUtil.readParams(bodyString, CommonRequest.class);
            if (commonRequest != null) {
                // todo 三方对接 查AuthToken表
                String operatorID = commonRequest.getOperatorId();
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
                                Exception e) throws Exception {

    }

}
