package com.xunhong.erp.turbo.web.interceptor;

import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.alibaba.fastjson2.JSONObject;
import com.xunhong.erp.turbo.base.dto.UserSession;
import com.xunhong.erp.turbo.web.utils.IPUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

/**
 * @author shenyifei
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class UserInterceptor implements AsyncHandlerInterceptor {

	/**
	 * This implementation always returns {@code true}.
	 *
	 * @param request  请求
	 * @param response 响应
	 * @param handler
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		boolean login = StpUtil.isLogin();

		UserSession userSession = new UserSession();
		if (login) {
			Long userId = Long.parseLong(StpUtil.getLoginId().toString());
			userSession.setUserId(userId);

			userSession.setCreatedBy(StpUtil.getSession().getLong("createdBy"));
			userSession.setCreatedByName(StpUtil.getSession().getString("createdByName"));
		}

		String ipAddr = IPUtils.getIpAddr(request);
		if (CharSequenceUtil.isNotBlank(ipAddr)) {
			userSession.setIpAddr(ipAddr);
		}

		String platformStr = request.getHeader("Xh-Platform-Id");
		if (CharSequenceUtil.isNotBlank(platformStr)) {
			userSession.setPlatformId(Long.parseLong(platformStr));
		}

		String roleSlug = request.getHeader("Xh-Role-Slug");
		if (CharSequenceUtil.isNotBlank(roleSlug)) {
			userSession.setRoleSlug(roleSlug);

			Object userAuthVO = StpUtil.getSession().get("userAuth");

			if (JSONObject.from(userAuthVO).getJSONArray("userRoleVOList").stream().noneMatch(userRoleVO -> JSONObject.from(userRoleVO).getString("slug").equals(roleSlug))) {
				StpUtil.logout(StpUtil.getLoginId());
				throw new NotPermissionException("用户权限不足");
			}
		}

		UserSession.USER_THREAD_LOCAL.set(userSession);

		return true;
	}

}
