package com.gree.mall.manager.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gree.mall.manager.helper.ResponseHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class BuyServiceInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        CommonLogic commonLogic = ApplicationContextUtils.getBean(CommonLogic.class);
//        AdminUserCom adminUser = commonLogic.getAdminUser(request);
//        if (adminUser != null && adminUser.getType() != null && adminUser.getType() != 2) {
//            Date expireTime = adminUser.getAdminCompanyWechat().getExpireTime();
//            DateTime curTime = DateUtil.parseDate(DateUtil.formatDate(DateUtil.date()));
//
//            if (Objects.isNull(expireTime)) {
//                expireTime = DateUtil.offsetDay(DateUtil.date(), -1);
//            }
//
//            if (curTime.getTime() > expireTime.getTime()) {
//                this.handleFalseRequest(response);
//                throw new RemoteServiceException(ResponseHelper.ResponseCode_STOP_SERVICE, "商户购买产品服务过期");
//                return false;
//            }
//        }
        return HandlerInterceptor.super.preHandle(request, response, handler);

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    private void handleFalseRequest(HttpServletResponse response) throws Exception {
        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        ObjectMapper om = new ObjectMapper();
        ResponseHelper helper = ResponseHelper.error(ResponseHelper.ResponseCode_STOP_SERVICE, "商户购买产品服务过期");
        response.getWriter().write(om.writeValueAsString(helper));
        response.getWriter().flush();
    }
}
