

package com.tuoheng.admin.interceptor;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tuoheng.admin.entity.User;
import com.tuoheng.admin.service.IUserService;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.utils.SecurityUserUtils;
import com.tuoheng.common.core.utils.StringUtils;
import com.tuoheng.common.core.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;

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

//@Component
//@Slf4j
//public class UserInterceptor implements HandlerInterceptor {
//
//    @Autowired
//    private IUserService userService;
//
//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        log.info("开始执行过滤器");
//        String username = SecurityUserUtils.username();
//
//        if (StringUtils.isEmpty(username)) {
//            throw new ServiceException(HttpStatus.BAD_REQUEST.value(),"username不能为空");
//        }
//
//        if(userService==null){
//            log.info("userService is null!!!");
//            BeanFactory factory = WebApplicationContextUtils
//                    .getRequiredWebApplicationContext(request.getServletContext());
//            userService = (IUserService) factory
//                    .getBean("UserServiceImpl");
//        }
//        User user = userService.getOne(Wrappers.<User>lambdaQuery()
//                .eq(User::getMark, 1)
//                .eq(User::getStatus, 1)
//                .eq(StringUtils.isNotEmpty(username), User::getUsername, username));
//        if (StringUtils.isNull(user)) {
//            log.error("用户信息不存在:{}", user);
//            return false;
//        }
//        ThreadLocalUtil.set(user);
//        log.info("执行完毕");
//        return true;
//    }
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//       //结束方法清理内存
//        ThreadLocalUtil.remove();
//        log.info("清理ThreadLocal内存完毕");
//    }
//}

