package com.winsun.intercept;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.netflix.discovery.converters.Auto;
import com.winsun.auth.core.shiro.ShiroUser;
import com.winsun.item.core.shiro.ShiroKit;
import com.winsun.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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

/**
 * @author chengfengluo
 * @date 2022-03-15 14:47
 */
@Slf4j
@Component
public class AuthIntercept extends HandlerInterceptorAdapter {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            ShiroUser user = ShiroKit.getUser();
            if (user != null) {
                log.info("请求测试：" + JSON.toJSONString(user));
            }
            else {
                log.error("错误");
            }

            Integer integer = sysUserMapper.selectCount(new EntityWrapper<>());
            log.info("总数：" + integer);
        }catch (Exception e) {
            e.printStackTrace();
        }

        return super.preHandle(request, response, handler);
    }

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

        try {
            ShiroUser user = ShiroKit.getUser();
            if (user != null) {
                log.info(JSON.toJSONString(user));
            }
            else {
                log.error("错误");
            }

            Integer integer = sysUserMapper.selectCount(new EntityWrapper<>());
            log.info("总数：" + integer);
        }catch (Exception e) {
            e.printStackTrace();
        }

        Map<String, Object> model = modelAndView.getModel();
        log.info("结束信息: {}", JSONObject.toJSONString(model));

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