package com.ruoyi.framework.interceptor;

import com.ruoyi.system.domain.AccessCount;
import com.ruoyi.system.mapper.AccessCountMapper;
import java.time.Year;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 访问计数拦截器
 */
@Component
public class AccessCountInterceptor implements HandlerInterceptor {

    @Autowired
    private AccessCountMapper accessCountMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        int currentYear = Year.now().getValue();

        AccessCount accessCount = accessCountMapper.selectByYear(currentYear);
        if (accessCount == null) {
            accessCountMapper.insertOrUpdateAccessCount(currentYear);
        } else {
            accessCountMapper.incrementCount(currentYear);
        }
        return true;
    }
}
