package com.ltgk.framework.interceptor;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ltgk.common.constant.ReturnMsgConstants;
import com.ltgk.common.core.domain.AjaxResult;
import com.ltgk.common.utils.DateUtils;
import com.ltgk.common.utils.ServletUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: wan kun
 * @Description: 软件授权拦截器
 * @Date: 2024/12/26 10:21
 * @Version: 1.0
 */
@Component
public class LicencesInterceptor implements HandlerInterceptor {
    @Value("${licences.nextTime}")
    private String nextLicencesTime;
    @Value("${licences.releaseUrl}")
    private String releaseUrl;

    /**
     * 拦截请求查询是不是在授权期内 部分url链接不做拦截
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUri = request.getRequestURI();
        //如果放行的url为空那么直接不拦截所有的
        if (ObjectUtils.isEmpty(releaseUrl)) return true;
        List<String> urls = Arrays.asList(releaseUrl.split(","));
//        // 如果请求的url在放行中也不拦截
        if (urls.contains(requestUri)) return true;
        // 计算时间看看在不在授权期内
        if (DateUtils.getNowDate().after(DateUtils.parseDate(nextLicencesTime))) {
            // 授权过期了
            AjaxResult ajaxResult = AjaxResult.warn(ReturnMsgConstants.LICENCES_EXPIRED);
            ServletUtils.renderString(response, JSON.toJSONString(ajaxResult));
            return false;
        }
        return true;
    }
}
