package com.sundot.airport.framework.interceptor;

import com.sundot.airport.common.constant.HttpStatus;
import com.sundot.airport.common.core.domain.entity.SysRole;
import com.sundot.airport.common.core.domain.model.LoginUser;
import com.sundot.airport.common.enums.RoleTypeEnum;
import com.sundot.airport.common.exception.ServiceException;
import com.sundot.airport.common.utils.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 请求来源拦截器
 * 仅超级管理员、站长、质检科、经理、大队行政角色可访问web端
 *
 * @author ruoyi
 */
@Component
public class RequestSourceInterceptor implements HandlerInterceptor {

    /**
     * 请求来源头
     */
    private static final String REQUEST_SOURCE_HEADER = "X-Request-Source";
    /**
     * PC端标识
     */
    private static final String SOURCE_WEB = "web";
    /**
     * 移动端标识
     */
    private static final String SOURCE_MOBILE = "mobile";

    /**
     * 请求处理之前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestSource = request.getHeader(REQUEST_SOURCE_HEADER);

        // 移动端请求或未指定来源，走原有逻辑
        if (SOURCE_MOBILE.equals(requestSource) || StringUtils.isEmpty(requestSource)) {
            return true;
        }

        // WEB端请求需要权限验证
        if (SOURCE_WEB.equals(requestSource)) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser == null) {
                throw new ServiceException("用户未登录", HttpStatus.UNAUTHORIZED);
            }

            List<SysRole> sysRoleList = loginUser.getUser().getRoles();
            Set<String> roles = sysRoleList.stream().map(SysRole::getRoleKey).collect(Collectors.toSet());
            if (!roles.contains(RoleTypeEnum.admin.getCode()) && !roles.contains(RoleTypeEnum.test.getCode()) && !roles.contains(RoleTypeEnum.zhijianke.getCode()) && !roles.contains(RoleTypeEnum.jingli.getCode()) && !roles.contains(RoleTypeEnum.xingzheng.getCode())) {
                throw new ServiceException("仅超级管理员、站长、质检科、经理、大队行政角色可访问web端", HttpStatus.FORBIDDEN);
            }
        }

        return true;
    }

}
